1 //! FIXME: write short doc here
3 use std::{convert::TryInto, ops, process::Command, sync::Arc};
5 use anyhow::{Context, Result};
7 use cargo_metadata::{CargoOpt, MetadataCommand};
8 use la_arena::{Arena, Idx};
9 use paths::{AbsPath, AbsPathBuf};
10 use rustc_hash::FxHashMap;
12 use crate::build_data::BuildDataConfig;
13 use crate::utf8_stdout;
15 /// `CargoWorkspace` represents the logical structure of, well, a Cargo
16 /// workspace. It pretty closely mirrors `cargo metadata` output.
18 /// Note that internally, rust analyzer uses a different structure:
19 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
20 /// while this knows about `Packages` & `Targets`: purely cargo-related
23 /// We use absolute paths here, `cargo metadata` guarantees to always produce
25 #[derive(Debug, Clone, Eq, PartialEq)]
26 pub struct CargoWorkspace {
27 packages: Arena<PackageData>,
28 targets: Arena<TargetData>,
29 workspace_root: AbsPathBuf,
30 build_data_config: BuildDataConfig,
33 impl ops::Index<Package> for CargoWorkspace {
34 type Output = PackageData;
35 fn index(&self, index: Package) -> &PackageData {
40 impl ops::Index<Target> for CargoWorkspace {
41 type Output = TargetData;
42 fn index(&self, index: Target) -> &TargetData {
47 /// Describes how to set the rustc source directory.
48 #[derive(Clone, Debug, PartialEq, Eq)]
49 pub enum RustcSource {
50 /// Explicit path for the rustc source directory.
52 /// Try to automatically detect where the rustc source directory is.
56 #[derive(Default, Clone, Debug, PartialEq, Eq)]
57 pub struct CargoConfig {
58 /// Do not activate the `default` feature.
59 pub no_default_features: bool,
61 /// Activate all available features
62 pub all_features: bool,
64 /// List of features to activate.
65 /// This will be ignored if `cargo_all_features` is true.
66 pub features: Vec<String>,
69 pub target: Option<String>,
71 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
72 /// when debugging isolated issues.
75 /// rustc private crate source
76 pub rustc_source: Option<RustcSource>,
79 pub type Package = Idx<PackageData>;
81 pub type Target = Idx<TargetData>;
83 /// Information associated with a cargo crate
84 #[derive(Debug, Clone, Eq, PartialEq)]
85 pub struct PackageData {
86 /// Version given in the `Cargo.toml`
88 /// Name as given in the `Cargo.toml`
90 /// Path containing the `Cargo.toml`
91 pub manifest: AbsPathBuf,
92 /// Targets provided by the crate (lib, bin, example, test, ...)
93 pub targets: Vec<Target>,
94 /// Is this package a member of the current workspace
96 /// List of packages this package depends on
97 pub dependencies: Vec<PackageDependency>,
98 /// Rust edition for this package
100 /// Features provided by the crate, mapped to the features required by that feature.
101 pub features: FxHashMap<String, Vec<String>>,
102 /// List of features enabled on this package
103 pub active_features: Vec<String>,
104 // String representation of package id
108 #[derive(Debug, Clone, Eq, PartialEq)]
109 pub struct PackageDependency {
114 /// Information associated with a package's target
115 #[derive(Debug, Clone, Eq, PartialEq)]
116 pub struct TargetData {
117 /// Package that provided this target
118 pub package: Package,
119 /// Name as given in the `Cargo.toml` or generated from the file name
121 /// Path to the main source file of the target
122 pub root: AbsPathBuf,
124 pub kind: TargetKind,
125 /// Is this target a proc-macro
126 pub is_proc_macro: bool,
129 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
130 pub enum TargetKind {
132 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
141 fn new(kinds: &[String]) -> TargetKind {
143 return match kind.as_str() {
144 "bin" => TargetKind::Bin,
145 "test" => TargetKind::Test,
146 "bench" => TargetKind::Bench,
147 "example" => TargetKind::Example,
148 "proc-macro" => TargetKind::Lib,
149 _ if kind.contains("lib") => TargetKind::Lib,
158 pub fn root(&self) -> &AbsPath {
159 self.manifest.parent().unwrap()
163 impl CargoWorkspace {
164 pub fn from_cargo_metadata(
165 cargo_toml: &AbsPath,
166 config: &CargoConfig,
167 progress: &dyn Fn(String),
168 ) -> Result<CargoWorkspace> {
169 let mut meta = MetadataCommand::new();
170 meta.cargo_path(toolchain::cargo());
171 meta.manifest_path(cargo_toml.to_path_buf());
172 if config.all_features {
173 meta.features(CargoOpt::AllFeatures);
175 if config.no_default_features {
176 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
177 // https://github.com/oli-obk/cargo_metadata/issues/79
178 meta.features(CargoOpt::NoDefaultFeatures);
180 if !config.features.is_empty() {
181 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
184 if let Some(parent) = cargo_toml.parent() {
185 meta.current_dir(parent.to_path_buf());
187 let target = if let Some(target) = config.target.as_ref() {
190 // cargo metadata defaults to giving information for _all_ targets.
191 // In the absence of a preference from the user, we use the host platform.
192 let mut rustc = Command::new(toolchain::rustc());
193 rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
194 log::debug!("Discovering host platform by {:?}", rustc);
195 match utf8_stdout(rustc) {
197 let field = "host: ";
198 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
199 if let Some(target) = target {
200 Some(target.to_string())
202 // If we fail to resolve the host platform, it's not the end of the world.
203 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
208 log::warn!("Failed to discover host platform: {}", e);
213 if let Some(target) = target {
214 meta.other_options(vec![String::from("--filter-platform"), target]);
217 // FIXME: Currently MetadataCommand is not based on parse_stream,
218 // So we just report it as a whole
219 progress("metadata".to_string());
220 let mut meta = meta.exec().with_context(|| {
221 let cwd: Option<AbsPathBuf> =
222 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
224 let workdir = cargo_toml
226 .map(|p| p.to_path_buf())
228 .map(|dir| dir.to_string_lossy().to_string())
229 .unwrap_or_else(|| "<failed to get path>".into());
232 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
233 cargo_toml.display(),
238 let mut pkg_by_id = FxHashMap::default();
239 let mut packages = Arena::default();
240 let mut targets = Arena::default();
242 let ws_members = &meta.workspace_members;
244 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
245 for meta_pkg in &meta.packages {
246 let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
248 let is_member = ws_members.contains(&id);
249 let edition = edition
251 .with_context(|| format!("Failed to parse edition {}", edition))?;
252 let pkg = packages.alloc(PackageData {
255 version: version.to_string(),
256 manifest: AbsPathBuf::assert(manifest_path.clone()),
260 dependencies: Vec::new(),
261 features: meta_pkg.features.clone().into_iter().collect(),
262 active_features: Vec::new(),
264 let pkg_data = &mut packages[pkg];
265 pkg_by_id.insert(id, pkg);
266 for meta_tgt in &meta_pkg.targets {
267 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
268 let tgt = targets.alloc(TargetData {
270 name: meta_tgt.name.clone(),
271 root: AbsPathBuf::assert(meta_tgt.src_path.clone()),
272 kind: TargetKind::new(meta_tgt.kind.as_slice()),
275 pkg_data.targets.push(tgt);
278 let resolve = meta.resolve.expect("metadata executed with deps");
279 for mut node in resolve.nodes {
280 let source = match pkg_by_id.get(&node.id) {
282 // FIXME: replace this and a similar branch below with `.unwrap`, once
283 // https://github.com/rust-lang/cargo/issues/7841
284 // is fixed and hits stable (around 1.43-is probably?).
286 log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
290 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
291 for dep_node in node.deps {
292 let pkg = match pkg_by_id.get(&dep_node.pkg) {
296 "Dep node id do not match in cargo metadata, ignoring {}",
302 let dep = PackageDependency { name: dep_node.name, pkg };
303 packages[source].dependencies.push(dep);
305 packages[source].active_features.extend(node.features);
308 let workspace_root = AbsPathBuf::assert(meta.workspace_root);
309 let build_data_config = BuildDataConfig::new(
310 cargo_toml.to_path_buf(),
312 Arc::new(meta.packages.clone()),
315 Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
318 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
319 self.packages.iter().map(|(id, _pkg)| id)
322 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
324 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
329 pub fn workspace_root(&self) -> &AbsPath {
333 pub fn package_flag(&self, package: &PackageData) -> String {
334 if self.is_unique(&*package.name) {
337 format!("{}:{}", package.name, package.version)
341 pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
342 &self.build_data_config
345 fn is_unique(&self, name: &str) -> bool {
346 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1