1 //! FIXME: write short doc here
3 use std::{convert::TryInto, ops, process::Command};
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::{BuildData, BuildDataMap};
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,
32 impl ops::Index<Package> for CargoWorkspace {
33 type Output = PackageData;
34 fn index(&self, index: Package) -> &PackageData {
39 impl ops::Index<Target> for CargoWorkspace {
40 type Output = TargetData;
41 fn index(&self, index: Target) -> &TargetData {
46 #[derive(Default, Clone, Debug, PartialEq, Eq)]
47 pub struct CargoConfig {
48 /// Do not activate the `default` feature.
49 pub no_default_features: bool,
51 /// Activate all available features
52 pub all_features: bool,
54 /// List of features to activate.
55 /// This will be ignored if `cargo_all_features` is true.
56 pub features: Vec<String>,
58 /// Runs cargo check on launch to figure out the correct values of OUT_DIR
59 pub load_out_dirs_from_check: bool,
62 pub target: Option<String>,
64 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
65 /// when debugging isolated issues.
68 /// rustc private crate source
69 pub rustc_source: Option<AbsPathBuf>,
72 pub type Package = Idx<PackageData>;
74 pub type Target = Idx<TargetData>;
76 /// Information associated with a cargo crate
77 #[derive(Debug, Clone, Eq, PartialEq)]
78 pub struct PackageData {
79 /// Version given in the `Cargo.toml`
81 /// Name as given in the `Cargo.toml`
83 /// Path containing the `Cargo.toml`
84 pub manifest: AbsPathBuf,
85 /// Targets provided by the crate (lib, bin, example, test, ...)
86 pub targets: Vec<Target>,
87 /// Is this package a member of the current workspace
89 /// List of packages this package depends on
90 pub dependencies: Vec<PackageDependency>,
91 /// Rust edition for this package
93 /// Features provided by the crate, mapped to the features required by that feature.
94 pub features: FxHashMap<String, Vec<String>>,
95 /// List of features enabled on this package
96 pub active_features: Vec<String>,
97 /// Build script related data for this package
98 pub build_data: BuildData,
101 #[derive(Debug, Clone, Eq, PartialEq)]
102 pub struct PackageDependency {
107 /// Information associated with a package's target
108 #[derive(Debug, Clone, Eq, PartialEq)]
109 pub struct TargetData {
110 /// Package that provided this target
111 pub package: Package,
112 /// Name as given in the `Cargo.toml` or generated from the file name
114 /// Path to the main source file of the target
115 pub root: AbsPathBuf,
117 pub kind: TargetKind,
118 /// Is this target a proc-macro
119 pub is_proc_macro: bool,
122 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
123 pub enum TargetKind {
125 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
134 fn new(kinds: &[String]) -> TargetKind {
136 return match kind.as_str() {
137 "bin" => TargetKind::Bin,
138 "test" => TargetKind::Test,
139 "bench" => TargetKind::Bench,
140 "example" => TargetKind::Example,
141 "proc-macro" => TargetKind::Lib,
142 _ if kind.contains("lib") => TargetKind::Lib,
151 pub fn root(&self) -> &AbsPath {
152 self.manifest.parent().unwrap()
156 impl CargoWorkspace {
157 pub fn from_cargo_metadata(
158 cargo_toml: &AbsPath,
159 config: &CargoConfig,
160 progress: &dyn Fn(String),
161 ) -> Result<CargoWorkspace> {
162 let mut meta = MetadataCommand::new();
163 meta.cargo_path(toolchain::cargo());
164 meta.manifest_path(cargo_toml.to_path_buf());
165 if config.all_features {
166 meta.features(CargoOpt::AllFeatures);
168 if config.no_default_features {
169 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
170 // https://github.com/oli-obk/cargo_metadata/issues/79
171 meta.features(CargoOpt::NoDefaultFeatures);
173 if !config.features.is_empty() {
174 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
177 if let Some(parent) = cargo_toml.parent() {
178 meta.current_dir(parent.to_path_buf());
180 let target = if let Some(target) = config.target.as_ref() {
183 // cargo metadata defaults to giving information for _all_ targets.
184 // In the absence of a preference from the user, we use the host platform.
185 let mut rustc = Command::new(toolchain::rustc());
186 rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
187 log::debug!("Discovering host platform by {:?}", rustc);
188 match utf8_stdout(rustc) {
190 let field = "host: ";
191 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
192 if let Some(target) = target {
193 Some(target.to_string())
195 // If we fail to resolve the host platform, it's not the end of the world.
196 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
201 log::warn!("Failed to discover host platform: {}", e);
206 if let Some(target) = target {
207 meta.other_options(vec![String::from("--filter-platform"), target]);
210 // FIXME: Currently MetadataCommand is not based on parse_stream,
211 // So we just report it as a whole
212 progress("metadata".to_string());
213 let mut meta = meta.exec().with_context(|| {
214 let cwd: Option<AbsPathBuf> =
215 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
217 let workdir = cargo_toml
219 .map(|p| p.to_path_buf())
221 .map(|dir| dir.to_string_lossy().to_string())
222 .unwrap_or_else(|| "<failed to get path>".into());
225 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
226 cargo_toml.display(),
231 let resources = if config.load_out_dirs_from_check {
232 BuildDataMap::new(cargo_toml, config, &meta.packages, progress)?
234 BuildDataMap::with_cargo_env(&meta.packages)
237 let mut pkg_by_id = FxHashMap::default();
238 let mut packages = Arena::default();
239 let mut targets = Arena::default();
241 let ws_members = &meta.workspace_members;
243 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
244 for meta_pkg in meta.packages {
245 let id = meta_pkg.id.clone();
246 let build_data = resources.get(&id).cloned().unwrap_or_default();
248 let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
250 let is_member = ws_members.contains(&id);
251 let edition = edition
253 .with_context(|| format!("Failed to parse edition {}", edition))?;
254 let pkg = packages.alloc(PackageData {
256 version: version.to_string(),
257 manifest: AbsPathBuf::assert(manifest_path),
261 dependencies: Vec::new(),
262 features: meta_pkg.features.into_iter().collect(),
263 active_features: Vec::new(),
266 let pkg_data = &mut packages[pkg];
267 pkg_by_id.insert(id, pkg);
268 for meta_tgt in meta_pkg.targets {
269 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
270 let tgt = targets.alloc(TargetData {
273 root: AbsPathBuf::assert(meta_tgt.src_path.clone()),
274 kind: TargetKind::new(meta_tgt.kind.as_slice()),
277 pkg_data.targets.push(tgt);
280 let resolve = meta.resolve.expect("metadata executed with deps");
281 for mut node in resolve.nodes {
282 let source = match pkg_by_id.get(&node.id) {
284 // FIXME: replace this and a similar branch below with `.unwrap`, once
285 // https://github.com/rust-lang/cargo/issues/7841
286 // is fixed and hits stable (around 1.43-is probably?).
288 log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
292 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
293 for dep_node in node.deps {
294 let pkg = match pkg_by_id.get(&dep_node.pkg) {
298 "Dep node id do not match in cargo metadata, ignoring {}",
304 let dep = PackageDependency { name: dep_node.name, pkg };
305 packages[source].dependencies.push(dep);
307 packages[source].active_features.extend(node.features);
310 let workspace_root = AbsPathBuf::assert(meta.workspace_root);
311 Ok(CargoWorkspace { packages, targets, workspace_root: workspace_root })
314 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
315 self.packages.iter().map(|(id, _pkg)| id)
318 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
320 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
325 pub fn workspace_root(&self) -> &AbsPath {
329 pub fn package_flag(&self, package: &PackageData) -> String {
330 if self.is_unique(&*package.name) {
333 format!("{}:{}", package.name, package.version)
337 fn is_unique(&self, name: &str) -> bool {
338 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1