1 //! FIXME: write short doc here
3 use std::path::PathBuf;
4 use std::{convert::TryInto, ops, process::Command, sync::Arc};
6 use anyhow::{Context, Result};
8 use cargo_metadata::{CargoOpt, MetadataCommand};
9 use la_arena::{Arena, Idx};
10 use paths::{AbsPath, AbsPathBuf};
11 use rustc_hash::FxHashMap;
13 use crate::build_data::BuildDataConfig;
14 use crate::utf8_stdout;
16 /// `CargoWorkspace` represents the logical structure of, well, a Cargo
17 /// workspace. It pretty closely mirrors `cargo metadata` output.
19 /// Note that internally, rust analyzer uses a different structure:
20 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
21 /// while this knows about `Packages` & `Targets`: purely cargo-related
24 /// We use absolute paths here, `cargo metadata` guarantees to always produce
26 #[derive(Debug, Clone, Eq, PartialEq)]
27 pub struct CargoWorkspace {
28 packages: Arena<PackageData>,
29 targets: Arena<TargetData>,
30 workspace_root: AbsPathBuf,
31 build_data_config: BuildDataConfig,
34 impl ops::Index<Package> for CargoWorkspace {
35 type Output = PackageData;
36 fn index(&self, index: Package) -> &PackageData {
41 impl ops::Index<Target> for CargoWorkspace {
42 type Output = TargetData;
43 fn index(&self, index: Target) -> &TargetData {
48 /// Describes how to set the rustc source directory.
49 #[derive(Clone, Debug, PartialEq, Eq)]
50 pub enum RustcSource {
51 /// Explicit path for the rustc source directory.
53 /// Try to automatically detect where the rustc source directory is.
57 #[derive(Default, Clone, Debug, PartialEq, Eq)]
58 pub struct CargoConfig {
59 /// Do not activate the `default` feature.
60 pub no_default_features: bool,
62 /// Activate all available features
63 pub all_features: bool,
65 /// List of features to activate.
66 /// This will be ignored if `cargo_all_features` is true.
67 pub features: Vec<String>,
70 pub target: Option<String>,
72 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
73 /// when debugging isolated issues.
76 /// rustc private crate source
77 pub rustc_source: Option<RustcSource>,
80 pub type Package = Idx<PackageData>;
82 pub type Target = Idx<TargetData>;
84 /// Information associated with a cargo crate
85 #[derive(Debug, Clone, Eq, PartialEq)]
86 pub struct PackageData {
87 /// Version given in the `Cargo.toml`
89 /// Name as given in the `Cargo.toml`
91 /// Path containing the `Cargo.toml`
92 pub manifest: AbsPathBuf,
93 /// Targets provided by the crate (lib, bin, example, test, ...)
94 pub targets: Vec<Target>,
95 /// Is this package a member of the current workspace
97 /// List of packages this package depends on
98 pub dependencies: Vec<PackageDependency>,
99 /// Rust edition for this package
100 pub edition: Edition,
101 /// Features provided by the crate, mapped to the features required by that feature.
102 pub features: FxHashMap<String, Vec<String>>,
103 /// List of features enabled on this package
104 pub active_features: Vec<String>,
105 // String representation of package id
109 #[derive(Debug, Clone, Eq, PartialEq)]
110 pub struct PackageDependency {
115 /// Information associated with a package's target
116 #[derive(Debug, Clone, Eq, PartialEq)]
117 pub struct TargetData {
118 /// Package that provided this target
119 pub package: Package,
120 /// Name as given in the `Cargo.toml` or generated from the file name
122 /// Path to the main source file of the target
123 pub root: AbsPathBuf,
125 pub kind: TargetKind,
126 /// Is this target a proc-macro
127 pub is_proc_macro: bool,
130 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
131 pub enum TargetKind {
133 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
142 fn new(kinds: &[String]) -> TargetKind {
144 return match kind.as_str() {
145 "bin" => TargetKind::Bin,
146 "test" => TargetKind::Test,
147 "bench" => TargetKind::Bench,
148 "example" => TargetKind::Example,
149 "proc-macro" => TargetKind::Lib,
150 _ if kind.contains("lib") => TargetKind::Lib,
159 pub fn root(&self) -> &AbsPath {
160 self.manifest.parent().unwrap()
164 impl CargoWorkspace {
165 pub fn from_cargo_metadata(
166 cargo_toml: &AbsPath,
167 config: &CargoConfig,
168 progress: &dyn Fn(String),
169 ) -> Result<CargoWorkspace> {
170 let mut meta = MetadataCommand::new();
171 meta.cargo_path(toolchain::cargo());
172 meta.manifest_path(cargo_toml.to_path_buf());
173 if config.all_features {
174 meta.features(CargoOpt::AllFeatures);
176 if config.no_default_features {
177 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
178 // https://github.com/oli-obk/cargo_metadata/issues/79
179 meta.features(CargoOpt::NoDefaultFeatures);
181 if !config.features.is_empty() {
182 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
185 if let Some(parent) = cargo_toml.parent() {
186 meta.current_dir(parent.to_path_buf());
188 let target = if let Some(target) = config.target.as_ref() {
191 // cargo metadata defaults to giving information for _all_ targets.
192 // In the absence of a preference from the user, we use the host platform.
193 let mut rustc = Command::new(toolchain::rustc());
194 rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
195 log::debug!("Discovering host platform by {:?}", rustc);
196 match utf8_stdout(rustc) {
198 let field = "host: ";
199 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
200 if let Some(target) = target {
201 Some(target.to_string())
203 // If we fail to resolve the host platform, it's not the end of the world.
204 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
209 log::warn!("Failed to discover host platform: {}", e);
214 if let Some(target) = target {
215 meta.other_options(vec![String::from("--filter-platform"), target]);
218 // FIXME: Currently MetadataCommand is not based on parse_stream,
219 // So we just report it as a whole
220 progress("metadata".to_string());
221 let mut meta = meta.exec().with_context(|| {
222 let cwd: Option<AbsPathBuf> =
223 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
225 let workdir = cargo_toml
227 .map(|p| p.to_path_buf())
229 .map(|dir| dir.to_string_lossy().to_string())
230 .unwrap_or_else(|| "<failed to get path>".into());
233 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
234 cargo_toml.display(),
239 let mut pkg_by_id = FxHashMap::default();
240 let mut packages = Arena::default();
241 let mut targets = Arena::default();
243 let ws_members = &meta.workspace_members;
245 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
246 for meta_pkg in &meta.packages {
247 let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
249 let is_member = ws_members.contains(&id);
250 let edition = edition
252 .with_context(|| format!("Failed to parse edition {}", edition))?;
254 let pkg = packages.alloc(PackageData {
257 version: version.to_string(),
258 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
262 dependencies: Vec::new(),
263 features: meta_pkg.features.clone().into_iter().collect(),
264 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 {
272 name: meta_tgt.name.clone(),
273 root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
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);
311 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
312 let build_data_config = BuildDataConfig::new(
313 cargo_toml.to_path_buf(),
315 Arc::new(meta.packages.clone()),
318 Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
321 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
322 self.packages.iter().map(|(id, _pkg)| id)
325 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
327 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
332 pub fn workspace_root(&self) -> &AbsPath {
336 pub fn package_flag(&self, package: &PackageData) -> String {
337 if self.is_unique(&*package.name) {
340 format!("{}:{}", package.name, package.version)
344 pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
345 &self.build_data_config
348 fn is_unique(&self, name: &str) -> bool {
349 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1