1 //! See [`CargoWorkspace`].
3 use std::convert::TryInto;
5 use std::path::PathBuf;
6 use std::{ops, process::Command};
8 use anyhow::{Context, Result};
10 use cargo_metadata::{CargoOpt, MetadataCommand};
11 use la_arena::{Arena, Idx};
12 use paths::{AbsPath, AbsPathBuf};
13 use rustc_hash::FxHashMap;
14 use serde::Deserialize;
15 use serde_json::from_value;
17 use crate::CfgOverrides;
18 use crate::{utf8_stdout, ManifestPath};
20 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
21 /// workspace. It pretty closely mirrors `cargo metadata` output.
23 /// Note that internally, rust analyzer uses a different structure:
24 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
25 /// while this knows about `Packages` & `Targets`: purely cargo-related
28 /// We use absolute paths here, `cargo metadata` guarantees to always produce
30 #[derive(Debug, Clone, Eq, PartialEq)]
31 pub struct CargoWorkspace {
32 packages: Arena<PackageData>,
33 targets: Arena<TargetData>,
34 workspace_root: AbsPathBuf,
37 impl ops::Index<Package> for CargoWorkspace {
38 type Output = PackageData;
39 fn index(&self, index: Package) -> &PackageData {
44 impl ops::Index<Target> for CargoWorkspace {
45 type Output = TargetData;
46 fn index(&self, index: Target) -> &TargetData {
51 /// Describes how to set the rustc source directory.
52 #[derive(Clone, Debug, PartialEq, Eq)]
53 pub enum RustcSource {
54 /// Explicit path for the rustc source directory.
56 /// Try to automatically detect where the rustc source directory is.
60 #[derive(Default, Clone, Debug, PartialEq, Eq)]
61 pub struct CargoConfig {
62 /// Do not activate the `default` feature.
63 pub no_default_features: bool,
65 /// Activate all available features
66 pub all_features: bool,
68 /// List of features to activate.
69 /// This will be ignored if `cargo_all_features` is true.
70 pub features: Vec<String>,
73 pub target: Option<String>,
75 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
76 /// when debugging isolated issues.
79 /// rustc private crate source
80 pub rustc_source: Option<RustcSource>,
82 /// crates to disable `#[cfg(test)]` on
83 pub unset_test_crates: Vec<String>,
85 pub wrap_rustc_in_build_scripts: bool,
89 pub fn cfg_overrides(&self) -> CfgOverrides {
90 self.unset_test_crates
93 .zip(iter::repeat_with(|| {
94 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap()
100 pub type Package = Idx<PackageData>;
102 pub type Target = Idx<TargetData>;
104 /// Information associated with a cargo crate
105 #[derive(Debug, Clone, Eq, PartialEq)]
106 pub struct PackageData {
107 /// Version given in the `Cargo.toml`
108 pub version: semver::Version,
109 /// Name as given in the `Cargo.toml`
111 /// Path containing the `Cargo.toml`
112 pub manifest: ManifestPath,
113 /// Targets provided by the crate (lib, bin, example, test, ...)
114 pub targets: Vec<Target>,
115 /// Is this package a member of the current workspace
117 /// List of packages this package depends on
118 pub dependencies: Vec<PackageDependency>,
119 /// Rust edition for this package
120 pub edition: Edition,
121 /// Features provided by the crate, mapped to the features required by that feature.
122 pub features: FxHashMap<String, Vec<String>>,
123 /// List of features enabled on this package
124 pub active_features: Vec<String>,
125 // String representation of package id
127 // The contents of [package.metadata.rust-analyzer]
128 pub metadata: RustAnalyzerPackageMetaData,
131 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
132 pub struct RustAnalyzerPackageMetaData {
133 pub rustc_private: bool,
136 #[derive(Debug, Clone, Eq, PartialEq)]
137 pub struct PackageDependency {
143 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
145 /// Available to the library, binary, and dev targets in the package (but not the build script).
147 /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
149 /// Available only to the build script target.
154 fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
155 let mut dep_kinds = Vec::new();
157 dep_kinds.push(Self::Normal);
160 let kind = match info.kind {
161 cargo_metadata::DependencyKind::Normal => Self::Normal,
162 cargo_metadata::DependencyKind::Development => Self::Dev,
163 cargo_metadata::DependencyKind::Build => Self::Build,
164 cargo_metadata::DependencyKind::Unknown => continue,
166 dep_kinds.push(kind);
168 dep_kinds.sort_unstable();
170 dep_kinds.into_iter()
174 /// Information associated with a package's target
175 #[derive(Debug, Clone, Eq, PartialEq)]
176 pub struct TargetData {
177 /// Package that provided this target
178 pub package: Package,
179 /// Name as given in the `Cargo.toml` or generated from the file name
181 /// Path to the main source file of the target
182 pub root: AbsPathBuf,
184 pub kind: TargetKind,
185 /// Is this target a proc-macro
186 pub is_proc_macro: bool,
189 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
190 pub enum TargetKind {
192 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
202 fn new(kinds: &[String]) -> TargetKind {
204 return match kind.as_str() {
205 "bin" => TargetKind::Bin,
206 "test" => TargetKind::Test,
207 "bench" => TargetKind::Bench,
208 "example" => TargetKind::Example,
209 "custom-build" => TargetKind::BuildScript,
210 "proc-macro" => TargetKind::Lib,
211 _ if kind.contains("lib") => TargetKind::Lib,
219 #[derive(Deserialize, Default)]
220 // Deserialise helper for the cargo metadata
221 struct PackageMetadata {
222 #[serde(rename = "rust-analyzer")]
223 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
226 impl CargoWorkspace {
227 pub fn fetch_metadata(
228 cargo_toml: &ManifestPath,
229 config: &CargoConfig,
230 progress: &dyn Fn(String),
231 ) -> Result<cargo_metadata::Metadata> {
235 .or_else(|| cargo_config_build_target(cargo_toml))
236 .or_else(|| rustc_discover_host_triple(cargo_toml));
238 let mut meta = MetadataCommand::new();
239 meta.cargo_path(toolchain::cargo());
240 meta.manifest_path(cargo_toml.to_path_buf());
241 if config.all_features {
242 meta.features(CargoOpt::AllFeatures);
244 if config.no_default_features {
245 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
246 // https://github.com/oli-obk/cargo_metadata/issues/79
247 meta.features(CargoOpt::NoDefaultFeatures);
249 if !config.features.is_empty() {
250 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
253 meta.current_dir(cargo_toml.parent().as_os_str());
255 if let Some(target) = target {
256 meta.other_options(vec![String::from("--filter-platform"), target]);
259 // FIXME: Fetching metadata is a slow process, as it might require
260 // calling crates.io. We should be reporting progress here, but it's
261 // unclear whether cargo itself supports it.
262 progress("metadata".to_string());
264 let meta = meta.exec().with_context(|| {
265 format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display(),)
271 pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
272 let mut pkg_by_id = FxHashMap::default();
273 let mut packages = Arena::default();
274 let mut targets = Arena::default();
276 let ws_members = &meta.workspace_members;
278 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
279 for meta_pkg in &meta.packages {
280 let cargo_metadata::Package {
281 id, edition, name, manifest_path, version, metadata, ..
283 let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
284 let is_member = ws_members.contains(id);
285 let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
286 tracing::error!("Failed to parse edition {}", err);
290 let pkg = packages.alloc(PackageData {
293 version: version.clone(),
294 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)).try_into().unwrap(),
298 dependencies: Vec::new(),
299 features: meta_pkg.features.clone().into_iter().collect(),
300 active_features: Vec::new(),
301 metadata: meta.rust_analyzer.unwrap_or_default(),
303 let pkg_data = &mut packages[pkg];
304 pkg_by_id.insert(id, pkg);
305 for meta_tgt in &meta_pkg.targets {
306 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
307 let tgt = targets.alloc(TargetData {
309 name: meta_tgt.name.clone(),
310 root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
311 kind: TargetKind::new(meta_tgt.kind.as_slice()),
314 pkg_data.targets.push(tgt);
317 let resolve = meta.resolve.expect("metadata executed with deps");
318 for mut node in resolve.nodes {
319 let source = match pkg_by_id.get(&node.id) {
321 // FIXME: replace this and a similar branch below with `.unwrap`, once
322 // https://github.com/rust-lang/cargo/issues/7841
323 // is fixed and hits stable (around 1.43-is probably?).
325 tracing::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
329 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
330 for (dep_node, kind) in node
333 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
335 let pkg = match pkg_by_id.get(&dep_node.pkg) {
339 "Dep node id do not match in cargo metadata, ignoring {}",
345 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
346 packages[source].dependencies.push(dep);
348 packages[source].active_features.extend(node.features);
352 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
354 CargoWorkspace { packages, targets, workspace_root }
357 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
358 self.packages.iter().map(|(id, _pkg)| id)
361 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
363 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
368 pub fn workspace_root(&self) -> &AbsPath {
372 pub fn package_flag(&self, package: &PackageData) -> String {
373 if self.is_unique(&*package.name) {
376 format!("{}:{}", package.name, package.version)
380 fn is_unique(&self, name: &str) -> bool {
381 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
385 fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
386 let mut rustc = Command::new(toolchain::rustc());
387 rustc.current_dir(cargo_toml.parent()).arg("-vV");
388 tracing::debug!("Discovering host platform by {:?}", rustc);
389 match utf8_stdout(rustc) {
391 let field = "host: ";
392 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
393 if let Some(target) = target {
394 Some(target.to_string())
396 // If we fail to resolve the host platform, it's not the end of the world.
397 tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
402 tracing::warn!("Failed to discover host platform: {}", e);
408 fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
409 let mut cargo_config = Command::new(toolchain::cargo());
411 .current_dir(cargo_toml.parent())
412 .args(&["-Z", "unstable-options", "config", "get", "build.target"])
413 .env("RUSTC_BOOTSTRAP", "1");
414 // if successful we receive `build.target = "target-triple"`
415 tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
416 match utf8_stdout(cargo_config) {
418 .strip_prefix("build.target = \"")
419 .and_then(|stdout| stdout.strip_suffix('"'))
420 .map(ToOwned::to_owned),