1 //! See [`CargoWorkspace`].
4 use std::path::PathBuf;
5 use std::{convert::TryInto, 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::utf8_stdout;
17 use crate::CfgOverrides;
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 #[derive(Default, Clone, Debug, PartialEq, Eq)]
60 pub struct CargoConfig {
61 /// Do not activate the `default` feature.
62 pub no_default_features: bool,
64 /// Activate all available features
65 pub all_features: bool,
67 /// List of features to activate.
68 /// This will be ignored if `cargo_all_features` is true.
69 pub features: Vec<String>,
72 pub target: Option<String>,
74 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
75 /// when debugging isolated issues.
78 /// rustc private crate source
79 pub rustc_source: Option<RustcSource>,
81 /// crates to disable `#[cfg(test)]` on
82 pub unset_test_crates: Vec<String>,
84 pub wrap_rustc_in_build_scripts: bool,
88 pub fn cfg_overrides(&self) -> CfgOverrides {
89 self.unset_test_crates
92 .zip(iter::repeat_with(|| {
93 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap()
99 pub type Package = Idx<PackageData>;
101 pub type Target = Idx<TargetData>;
103 /// Information associated with a cargo crate
104 #[derive(Debug, Clone, Eq, PartialEq)]
105 pub struct PackageData {
106 /// Version given in the `Cargo.toml`
107 pub version: semver::Version,
108 /// Name as given in the `Cargo.toml`
110 /// Path containing the `Cargo.toml`
111 pub manifest: AbsPathBuf,
112 /// Targets provided by the crate (lib, bin, example, test, ...)
113 pub targets: Vec<Target>,
114 /// Is this package a member of the current workspace
116 /// List of packages this package depends on
117 pub dependencies: Vec<PackageDependency>,
118 /// Rust edition for this package
119 pub edition: Edition,
120 /// Features provided by the crate, mapped to the features required by that feature.
121 pub features: FxHashMap<String, Vec<String>>,
122 /// List of features enabled on this package
123 pub active_features: Vec<String>,
124 // String representation of package id
126 // The contents of [package.metadata.rust-analyzer]
127 pub metadata: RustAnalyzerPackageMetaData,
130 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
131 pub struct RustAnalyzerPackageMetaData {
132 pub rustc_private: bool,
135 #[derive(Debug, Clone, Eq, PartialEq)]
136 pub struct PackageDependency {
142 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
144 /// Available to the library, binary, and dev targets in the package (but not the build script).
146 /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
148 /// Available only to the build script target.
153 fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
154 let mut dep_kinds = Vec::new();
156 dep_kinds.push(Self::Normal);
159 let kind = match info.kind {
160 cargo_metadata::DependencyKind::Normal => Self::Normal,
161 cargo_metadata::DependencyKind::Development => Self::Dev,
162 cargo_metadata::DependencyKind::Build => Self::Build,
163 cargo_metadata::DependencyKind::Unknown => continue,
165 dep_kinds.push(kind);
167 dep_kinds.sort_unstable();
169 dep_kinds.into_iter()
173 /// Information associated with a package's target
174 #[derive(Debug, Clone, Eq, PartialEq)]
175 pub struct TargetData {
176 /// Package that provided this target
177 pub package: Package,
178 /// Name as given in the `Cargo.toml` or generated from the file name
180 /// Path to the main source file of the target
181 pub root: AbsPathBuf,
183 pub kind: TargetKind,
184 /// Is this target a proc-macro
185 pub is_proc_macro: bool,
188 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
189 pub enum TargetKind {
191 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
201 fn new(kinds: &[String]) -> TargetKind {
203 return match kind.as_str() {
204 "bin" => TargetKind::Bin,
205 "test" => TargetKind::Test,
206 "bench" => TargetKind::Bench,
207 "example" => TargetKind::Example,
208 "custom-build" => TargetKind::BuildScript,
209 "proc-macro" => TargetKind::Lib,
210 _ if kind.contains("lib") => TargetKind::Lib,
219 pub fn root(&self) -> &AbsPath {
220 self.manifest.parent().unwrap()
224 #[derive(Deserialize, Default)]
225 // Deserialise helper for the cargo metadata
226 struct PackageMetadata {
227 #[serde(rename = "rust-analyzer")]
228 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
231 impl CargoWorkspace {
232 pub fn fetch_metadata(
233 cargo_toml: &AbsPath,
234 config: &CargoConfig,
235 progress: &dyn Fn(String),
236 ) -> Result<cargo_metadata::Metadata> {
237 let mut meta = MetadataCommand::new();
238 meta.cargo_path(toolchain::cargo());
239 meta.manifest_path(cargo_toml.to_path_buf());
240 if config.all_features {
241 meta.features(CargoOpt::AllFeatures);
243 if config.no_default_features {
244 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
245 // https://github.com/oli-obk/cargo_metadata/issues/79
246 meta.features(CargoOpt::NoDefaultFeatures);
248 if !config.features.is_empty() {
249 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
252 if let Some(parent) = cargo_toml.parent() {
253 meta.current_dir(parent.to_path_buf());
255 let target = if let Some(target) = &config.target {
257 } else if let stdout @ Some(_) = cargo_config_build_target(cargo_toml) {
260 rustc_discover_host_triple(cargo_toml)
262 if let Some(target) = target {
263 meta.other_options(vec![String::from("--filter-platform"), target]);
266 // FIXME: Fetching metadata is a slow process, as it might require
267 // calling crates.io. We should be reporting progress here, but it's
268 // unclear whether cargo itself supports it.
269 progress("metadata".to_string());
271 let meta = meta.exec().with_context(|| {
272 let cwd: Option<AbsPathBuf> =
273 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
275 let workdir = cargo_toml
277 .map(|p| p.to_path_buf())
279 .map(|dir| format!(" in `{}`", dir.display()))
280 .unwrap_or_default();
283 "Failed to run `cargo metadata --manifest-path {}`{}",
284 cargo_toml.display(),
292 pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
293 let mut pkg_by_id = FxHashMap::default();
294 let mut packages = Arena::default();
295 let mut targets = Arena::default();
297 let ws_members = &meta.workspace_members;
299 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
300 for meta_pkg in &meta.packages {
301 let cargo_metadata::Package {
302 id, edition, name, manifest_path, version, metadata, ..
304 let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
305 let is_member = ws_members.contains(id);
306 let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
307 log::error!("Failed to parse edition {}", err);
311 let pkg = packages.alloc(PackageData {
314 version: version.clone(),
315 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
319 dependencies: Vec::new(),
320 features: meta_pkg.features.clone().into_iter().collect(),
321 active_features: Vec::new(),
322 metadata: meta.rust_analyzer.unwrap_or_default(),
324 let pkg_data = &mut packages[pkg];
325 pkg_by_id.insert(id, pkg);
326 for meta_tgt in &meta_pkg.targets {
327 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
328 let tgt = targets.alloc(TargetData {
330 name: meta_tgt.name.clone(),
331 root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
332 kind: TargetKind::new(meta_tgt.kind.as_slice()),
335 pkg_data.targets.push(tgt);
338 let resolve = meta.resolve.expect("metadata executed with deps");
339 for mut node in resolve.nodes {
340 let source = match pkg_by_id.get(&node.id) {
342 // FIXME: replace this and a similar branch below with `.unwrap`, once
343 // https://github.com/rust-lang/cargo/issues/7841
344 // is fixed and hits stable (around 1.43-is probably?).
346 log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
350 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
351 for (dep_node, kind) in node
354 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
356 let pkg = match pkg_by_id.get(&dep_node.pkg) {
360 "Dep node id do not match in cargo metadata, ignoring {}",
366 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
367 packages[source].dependencies.push(dep);
369 packages[source].active_features.extend(node.features);
373 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
375 CargoWorkspace { packages, targets, workspace_root }
378 pub fn from_cargo_metadata3(
379 cargo_toml: &AbsPath,
380 config: &CargoConfig,
381 progress: &dyn Fn(String),
382 ) -> Result<CargoWorkspace> {
383 let meta = CargoWorkspace::fetch_metadata(cargo_toml, config, progress)?;
384 Ok(CargoWorkspace::new(meta))
387 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
388 self.packages.iter().map(|(id, _pkg)| id)
391 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
393 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
398 pub fn workspace_root(&self) -> &AbsPath {
402 pub fn package_flag(&self, package: &PackageData) -> String {
403 if self.is_unique(&*package.name) {
406 format!("{}:{}", package.name, package.version)
410 fn is_unique(&self, name: &str) -> bool {
411 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
415 fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> Option<String> {
416 let mut rustc = Command::new(toolchain::rustc());
417 rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
418 log::debug!("Discovering host platform by {:?}", rustc);
419 match utf8_stdout(rustc) {
421 let field = "host: ";
422 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
423 if let Some(target) = target {
424 Some(target.to_string())
426 // If we fail to resolve the host platform, it's not the end of the world.
427 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
432 log::warn!("Failed to discover host platform: {}", e);
438 fn cargo_config_build_target(cargo_toml: &AbsPath) -> Option<String> {
439 let mut cargo_config = Command::new(toolchain::cargo());
441 .current_dir(cargo_toml.parent().unwrap())
442 .args(&["-Z", "unstable-options", "config", "get", "build.target"])
443 .env("RUSTC_BOOTSTRAP", "1");
444 // if successful we receive `build.target = "target-triple"`
445 log::debug!("Discovering cargo config target by {:?}", cargo_config);
446 match utf8_stdout(cargo_config) {
448 .strip_prefix("build.target = \"")
449 .and_then(|stdout| stdout.strip_suffix('"'))
450 .map(ToOwned::to_owned),