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 #[derive(Default, Clone, Debug, PartialEq, Eq)]
48 pub struct CargoConfig {
49 /// Do not activate the `default` feature.
50 pub no_default_features: bool,
52 /// Activate all available features
53 pub all_features: bool,
55 /// List of features to activate.
56 /// This will be ignored if `cargo_all_features` is true.
57 pub features: Vec<String>,
60 pub target: Option<String>,
62 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
63 /// when debugging isolated issues.
66 /// rustc private crate source
67 pub rustc_source: Option<AbsPathBuf>,
70 pub type Package = Idx<PackageData>;
72 pub type Target = Idx<TargetData>;
74 /// Information associated with a cargo crate
75 #[derive(Debug, Clone, Eq, PartialEq)]
76 pub struct PackageData {
77 /// Version given in the `Cargo.toml`
79 /// Name as given in the `Cargo.toml`
81 /// Path containing the `Cargo.toml`
82 pub manifest: AbsPathBuf,
83 /// Targets provided by the crate (lib, bin, example, test, ...)
84 pub targets: Vec<Target>,
85 /// Is this package a member of the current workspace
87 /// List of packages this package depends on
88 pub dependencies: Vec<PackageDependency>,
89 /// Rust edition for this package
91 /// Features provided by the crate, mapped to the features required by that feature.
92 pub features: FxHashMap<String, Vec<String>>,
93 /// List of features enabled on this package
94 pub active_features: Vec<String>,
95 // String representation of package id
99 #[derive(Debug, Clone, Eq, PartialEq)]
100 pub struct PackageDependency {
105 /// Information associated with a package's target
106 #[derive(Debug, Clone, Eq, PartialEq)]
107 pub struct TargetData {
108 /// Package that provided this target
109 pub package: Package,
110 /// Name as given in the `Cargo.toml` or generated from the file name
112 /// Path to the main source file of the target
113 pub root: AbsPathBuf,
115 pub kind: TargetKind,
116 /// Is this target a proc-macro
117 pub is_proc_macro: bool,
120 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
121 pub enum TargetKind {
123 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
132 fn new(kinds: &[String]) -> TargetKind {
134 return match kind.as_str() {
135 "bin" => TargetKind::Bin,
136 "test" => TargetKind::Test,
137 "bench" => TargetKind::Bench,
138 "example" => TargetKind::Example,
139 "proc-macro" => TargetKind::Lib,
140 _ if kind.contains("lib") => TargetKind::Lib,
149 pub fn root(&self) -> &AbsPath {
150 self.manifest.parent().unwrap()
154 impl CargoWorkspace {
155 pub fn from_cargo_metadata(
156 cargo_toml: &AbsPath,
157 config: &CargoConfig,
158 progress: &dyn Fn(String),
159 ) -> Result<CargoWorkspace> {
160 let mut meta = MetadataCommand::new();
161 meta.cargo_path(toolchain::cargo());
162 meta.manifest_path(cargo_toml.to_path_buf());
163 if config.all_features {
164 meta.features(CargoOpt::AllFeatures);
166 if config.no_default_features {
167 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
168 // https://github.com/oli-obk/cargo_metadata/issues/79
169 meta.features(CargoOpt::NoDefaultFeatures);
171 if !config.features.is_empty() {
172 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
175 if let Some(parent) = cargo_toml.parent() {
176 meta.current_dir(parent.to_path_buf());
178 let target = if let Some(target) = config.target.as_ref() {
181 // cargo metadata defaults to giving information for _all_ targets.
182 // In the absence of a preference from the user, we use the host platform.
183 let mut rustc = Command::new(toolchain::rustc());
184 rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
185 log::debug!("Discovering host platform by {:?}", rustc);
186 match utf8_stdout(rustc) {
188 let field = "host: ";
189 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
190 if let Some(target) = target {
191 Some(target.to_string())
193 // If we fail to resolve the host platform, it's not the end of the world.
194 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
199 log::warn!("Failed to discover host platform: {}", e);
204 if let Some(target) = target {
205 meta.other_options(vec![String::from("--filter-platform"), target]);
208 // FIXME: Currently MetadataCommand is not based on parse_stream,
209 // So we just report it as a whole
210 progress("metadata".to_string());
211 let mut meta = meta.exec().with_context(|| {
212 let cwd: Option<AbsPathBuf> =
213 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
215 let workdir = cargo_toml
217 .map(|p| p.to_path_buf())
219 .map(|dir| dir.to_string_lossy().to_string())
220 .unwrap_or_else(|| "<failed to get path>".into());
223 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
224 cargo_toml.display(),
229 let mut pkg_by_id = FxHashMap::default();
230 let mut packages = Arena::default();
231 let mut targets = Arena::default();
233 let ws_members = &meta.workspace_members;
235 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
236 for meta_pkg in &meta.packages {
237 let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
239 let is_member = ws_members.contains(&id);
240 let edition = edition
242 .with_context(|| format!("Failed to parse edition {}", edition))?;
243 let pkg = packages.alloc(PackageData {
246 version: version.to_string(),
247 manifest: AbsPathBuf::assert(manifest_path.clone()),
251 dependencies: Vec::new(),
252 features: meta_pkg.features.clone().into_iter().collect(),
253 active_features: Vec::new(),
255 let pkg_data = &mut packages[pkg];
256 pkg_by_id.insert(id, pkg);
257 for meta_tgt in &meta_pkg.targets {
258 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
259 let tgt = targets.alloc(TargetData {
261 name: meta_tgt.name.clone(),
262 root: AbsPathBuf::assert(meta_tgt.src_path.clone()),
263 kind: TargetKind::new(meta_tgt.kind.as_slice()),
266 pkg_data.targets.push(tgt);
269 let resolve = meta.resolve.expect("metadata executed with deps");
270 for mut node in resolve.nodes {
271 let source = match pkg_by_id.get(&node.id) {
273 // FIXME: replace this and a similar branch below with `.unwrap`, once
274 // https://github.com/rust-lang/cargo/issues/7841
275 // is fixed and hits stable (around 1.43-is probably?).
277 log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
281 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
282 for dep_node in node.deps {
283 let pkg = match pkg_by_id.get(&dep_node.pkg) {
287 "Dep node id do not match in cargo metadata, ignoring {}",
293 let dep = PackageDependency { name: dep_node.name, pkg };
294 packages[source].dependencies.push(dep);
296 packages[source].active_features.extend(node.features);
299 let workspace_root = AbsPathBuf::assert(meta.workspace_root);
300 let build_data_config = BuildDataConfig::new(
301 cargo_toml.to_path_buf(),
303 Arc::new(meta.packages.clone()),
306 Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
309 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
310 self.packages.iter().map(|(id, _pkg)| id)
313 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
315 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
320 pub fn workspace_root(&self) -> &AbsPath {
324 pub fn package_flag(&self, package: &PackageData) -> String {
325 if self.is_unique(&*package.name) {
328 format!("{}:{}", package.name, package.version)
332 pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
333 &self.build_data_config
336 fn is_unique(&self, name: &str) -> bool {
337 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1