1 //! See [`CargoWorkspace`].
4 use std::path::PathBuf;
5 use std::{ops, process::Command};
7 use anyhow::{Context, Result};
9 use cargo_metadata::{CargoOpt, MetadataCommand};
10 use la_arena::{Arena, Idx};
11 use paths::{AbsPath, AbsPathBuf};
12 use rustc_hash::FxHashMap;
13 use serde::Deserialize;
14 use serde_json::from_value;
16 use crate::CfgOverrides;
17 use crate::{utf8_stdout, ManifestPath};
19 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
20 /// workspace. It pretty closely mirrors `cargo metadata` output.
22 /// Note that internally, rust analyzer uses a different structure:
23 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
24 /// while this knows about `Packages` & `Targets`: purely cargo-related
27 /// We use absolute paths here, `cargo metadata` guarantees to always produce
29 #[derive(Debug, Clone, Eq, PartialEq)]
30 pub struct CargoWorkspace {
31 packages: Arena<PackageData>,
32 targets: Arena<TargetData>,
33 workspace_root: AbsPathBuf,
36 impl ops::Index<Package> for CargoWorkspace {
37 type Output = PackageData;
38 fn index(&self, index: Package) -> &PackageData {
43 impl ops::Index<Target> for CargoWorkspace {
44 type Output = TargetData;
45 fn index(&self, index: Target) -> &TargetData {
50 /// Describes how to set the rustc source directory.
51 #[derive(Clone, Debug, PartialEq, Eq)]
52 pub enum RustcSource {
53 /// Explicit path for the rustc source directory.
55 /// Try to automatically detect where the rustc source directory is.
59 /// Crates to disable `#[cfg(test)]` on.
60 #[derive(Clone, Debug, PartialEq, Eq)]
61 pub enum UnsetTestCrates {
67 impl Default for UnsetTestCrates {
68 fn default() -> Self {
73 #[derive(Default, Clone, Debug, PartialEq, Eq)]
74 pub struct CargoConfig {
75 /// Do not activate the `default` feature.
76 pub no_default_features: bool,
78 /// Activate all available features
79 pub all_features: bool,
81 /// List of features to activate.
82 /// This will be ignored if `cargo_all_features` is true.
83 pub features: Vec<String>,
86 pub target: Option<String>,
88 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
89 /// when debugging isolated issues.
92 /// rustc private crate source
93 pub rustc_source: Option<RustcSource>,
95 /// crates to disable `#[cfg(test)]` on
96 pub unset_test_crates: UnsetTestCrates,
98 pub wrap_rustc_in_build_scripts: bool,
102 pub fn cfg_overrides(&self) -> CfgOverrides {
103 match &self.unset_test_crates {
104 UnsetTestCrates::None => CfgOverrides::Selective(iter::empty().collect()),
105 UnsetTestCrates::Only(unset_test_crates) => CfgOverrides::Selective(
109 .zip(iter::repeat_with(|| {
110 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())])
115 UnsetTestCrates::All => CfgOverrides::Wildcard(
116 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap(),
122 pub type Package = Idx<PackageData>;
124 pub type Target = Idx<TargetData>;
126 /// Information associated with a cargo crate
127 #[derive(Debug, Clone, Eq, PartialEq)]
128 pub struct PackageData {
129 /// Version given in the `Cargo.toml`
130 pub version: semver::Version,
131 /// Name as given in the `Cargo.toml`
133 /// Repository as given in the `Cargo.toml`
134 pub repository: Option<String>,
135 /// Path containing the `Cargo.toml`
136 pub manifest: ManifestPath,
137 /// Targets provided by the crate (lib, bin, example, test, ...)
138 pub targets: Vec<Target>,
139 /// Does this package come from the local filesystem (and is editable)?
141 // Whether this package is a member of the workspace
143 /// List of packages this package depends on
144 pub dependencies: Vec<PackageDependency>,
145 /// Rust edition for this package
146 pub edition: Edition,
147 /// Features provided by the crate, mapped to the features required by that feature.
148 pub features: FxHashMap<String, Vec<String>>,
149 /// List of features enabled on this package
150 pub active_features: Vec<String>,
151 /// String representation of package id
153 /// The contents of [package.metadata.rust-analyzer]
154 pub metadata: RustAnalyzerPackageMetaData,
157 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
158 pub struct RustAnalyzerPackageMetaData {
159 pub rustc_private: bool,
162 #[derive(Debug, Clone, Eq, PartialEq)]
163 pub struct PackageDependency {
169 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
171 /// Available to the library, binary, and dev targets in the package (but not the build script).
173 /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
175 /// Available only to the build script target.
180 fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
181 let mut dep_kinds = Vec::new();
183 dep_kinds.push(Self::Normal);
186 let kind = match info.kind {
187 cargo_metadata::DependencyKind::Normal => Self::Normal,
188 cargo_metadata::DependencyKind::Development => Self::Dev,
189 cargo_metadata::DependencyKind::Build => Self::Build,
190 cargo_metadata::DependencyKind::Unknown => continue,
192 dep_kinds.push(kind);
194 dep_kinds.sort_unstable();
196 dep_kinds.into_iter()
200 /// Information associated with a package's target
201 #[derive(Debug, Clone, Eq, PartialEq)]
202 pub struct TargetData {
203 /// Package that provided this target
204 pub package: Package,
205 /// Name as given in the `Cargo.toml` or generated from the file name
207 /// Path to the main source file of the target
208 pub root: AbsPathBuf,
210 pub kind: TargetKind,
211 /// Is this target a proc-macro
212 pub is_proc_macro: bool,
215 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
216 pub enum TargetKind {
218 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
228 fn new(kinds: &[String]) -> TargetKind {
230 return match kind.as_str() {
231 "bin" => TargetKind::Bin,
232 "test" => TargetKind::Test,
233 "bench" => TargetKind::Bench,
234 "example" => TargetKind::Example,
235 "custom-build" => TargetKind::BuildScript,
236 "proc-macro" => TargetKind::Lib,
237 _ if kind.contains("lib") => TargetKind::Lib,
245 #[derive(Deserialize, Default)]
246 // Deserialise helper for the cargo metadata
247 struct PackageMetadata {
248 #[serde(rename = "rust-analyzer")]
249 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
252 impl CargoWorkspace {
253 pub fn fetch_metadata(
254 cargo_toml: &ManifestPath,
255 current_dir: &AbsPath,
256 config: &CargoConfig,
257 progress: &dyn Fn(String),
258 ) -> Result<cargo_metadata::Metadata> {
262 .or_else(|| cargo_config_build_target(cargo_toml))
263 .or_else(|| rustc_discover_host_triple(cargo_toml));
265 let mut meta = MetadataCommand::new();
266 meta.cargo_path(toolchain::cargo());
267 meta.manifest_path(cargo_toml.to_path_buf());
268 if config.all_features {
269 meta.features(CargoOpt::AllFeatures);
271 if config.no_default_features {
272 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
273 // https://github.com/oli-obk/cargo_metadata/issues/79
274 meta.features(CargoOpt::NoDefaultFeatures);
276 if !config.features.is_empty() {
277 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
280 meta.current_dir(current_dir.as_os_str());
282 if let Some(target) = target {
283 meta.other_options(vec![String::from("--filter-platform"), target]);
286 // FIXME: Fetching metadata is a slow process, as it might require
287 // calling crates.io. We should be reporting progress here, but it's
288 // unclear whether cargo itself supports it.
289 progress("metadata".to_string());
291 let meta = meta.exec().with_context(|| {
292 format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display(),)
298 pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
299 let mut pkg_by_id = FxHashMap::default();
300 let mut packages = Arena::default();
301 let mut targets = Arena::default();
303 let ws_members = &meta.workspace_members;
305 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
306 for meta_pkg in &meta.packages {
307 let cargo_metadata::Package {
317 let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
318 let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
319 tracing::error!("Failed to parse edition {}", err);
322 // We treat packages without source as "local" packages. That includes all members of
323 // the current workspace, as well as any path dependency outside the workspace.
324 let is_local = meta_pkg.source.is_none();
325 let is_member = ws_members.contains(id);
327 let pkg = packages.alloc(PackageData {
330 version: version.clone(),
331 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)).try_into().unwrap(),
336 repository: repository.clone(),
337 dependencies: Vec::new(),
338 features: meta_pkg.features.clone().into_iter().collect(),
339 active_features: Vec::new(),
340 metadata: meta.rust_analyzer.unwrap_or_default(),
342 let pkg_data = &mut packages[pkg];
343 pkg_by_id.insert(id, pkg);
344 for meta_tgt in &meta_pkg.targets {
345 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
346 let tgt = targets.alloc(TargetData {
348 name: meta_tgt.name.clone(),
349 root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
350 kind: TargetKind::new(meta_tgt.kind.as_slice()),
353 pkg_data.targets.push(tgt);
356 let resolve = meta.resolve.expect("metadata executed with deps");
357 for mut node in resolve.nodes {
358 let source = match pkg_by_id.get(&node.id) {
360 // FIXME: replace this and a similar branch below with `.unwrap`, once
361 // https://github.com/rust-lang/cargo/issues/7841
362 // is fixed and hits stable (around 1.43-is probably?).
364 tracing::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
368 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
369 for (dep_node, kind) in node
372 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
374 let pkg = match pkg_by_id.get(&dep_node.pkg) {
378 "Dep node id do not match in cargo metadata, ignoring {}",
384 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
385 packages[source].dependencies.push(dep);
387 packages[source].active_features.extend(node.features);
391 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
393 CargoWorkspace { packages, targets, workspace_root }
396 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
397 self.packages.iter().map(|(id, _pkg)| id)
400 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
402 .filter(|&pkg| self[pkg].is_member)
403 .find_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
407 pub fn workspace_root(&self) -> &AbsPath {
411 pub fn package_flag(&self, package: &PackageData) -> String {
412 if self.is_unique(&*package.name) {
415 format!("{}:{}", package.name, package.version)
419 pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
420 let mut found = false;
421 let parent_manifests = self
424 if !found && &self[pkg].manifest == manifest_path {
427 self[pkg].dependencies.iter().find_map(|dep| {
428 if &self[dep.pkg].manifest == manifest_path {
429 return Some(self[pkg].manifest.clone());
434 .collect::<Vec<ManifestPath>>();
436 // some packages has this pkg as dep. return their manifests
437 if parent_manifests.len() > 0 {
438 return Some(parent_manifests);
441 // this pkg is inside this cargo workspace, fallback to workspace root
444 ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
448 // not in this workspace
452 fn is_unique(&self, name: &str) -> bool {
453 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
457 fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
458 let mut rustc = Command::new(toolchain::rustc());
459 rustc.current_dir(cargo_toml.parent()).arg("-vV");
460 tracing::debug!("Discovering host platform by {:?}", rustc);
461 match utf8_stdout(rustc) {
463 let field = "host: ";
464 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
465 if let Some(target) = target {
466 Some(target.to_string())
468 // If we fail to resolve the host platform, it's not the end of the world.
469 tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
474 tracing::warn!("Failed to discover host platform: {}", e);
480 fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
481 let mut cargo_config = Command::new(toolchain::cargo());
483 .current_dir(cargo_toml.parent())
484 .args(&["-Z", "unstable-options", "config", "get", "build.target"])
485 .env("RUSTC_BOOTSTRAP", "1");
486 // if successful we receive `build.target = "target-triple"`
487 tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
488 match utf8_stdout(cargo_config) {
490 .strip_prefix("build.target = \"")
491 .and_then(|stdout| stdout.strip_suffix('"'))
492 .map(ToOwned::to_owned),