1 //! See [`CargoWorkspace`].
4 use std::path::PathBuf;
5 use std::{convert::TryInto, ops, process::Command, sync::Arc};
7 use anyhow::{Context, Result};
9 use cargo_metadata::{CargoOpt, MetadataCommand};
10 use la_arena::{Arena, Idx};
11 use paths::{AbsPath, AbsPathBuf};
12 use rustc_hash::FxHashMap;
13 use serde::Deserialize;
14 use serde_json::from_value;
16 use crate::CfgOverrides;
17 use crate::{build_data::BuildDataConfig, utf8_stdout};
19 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
20 /// workspace. It pretty closely mirrors `cargo metadata` output.
22 /// Note that internally, rust analyzer uses a different structure:
23 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
24 /// while this knows about `Packages` & `Targets`: purely cargo-related
27 /// We use absolute paths here, `cargo metadata` guarantees to always produce
29 #[derive(Debug, Clone, Eq, PartialEq)]
30 pub struct CargoWorkspace {
31 packages: Arena<PackageData>,
32 targets: Arena<TargetData>,
33 workspace_root: AbsPathBuf,
34 build_data_config: BuildDataConfig,
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>,
87 pub fn cfg_overrides(&self) -> CfgOverrides {
88 self.unset_test_crates
91 .zip(iter::repeat_with(|| {
92 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap()
98 pub type Package = Idx<PackageData>;
100 pub type Target = Idx<TargetData>;
102 /// Information associated with a cargo crate
103 #[derive(Debug, Clone, Eq, PartialEq)]
104 pub struct PackageData {
105 /// Version given in the `Cargo.toml`
107 /// Name as given in the `Cargo.toml`
109 /// Path containing the `Cargo.toml`
110 pub manifest: AbsPathBuf,
111 /// Targets provided by the crate (lib, bin, example, test, ...)
112 pub targets: Vec<Target>,
113 /// Is this package a member of the current workspace
115 /// List of packages this package depends on
116 pub dependencies: Vec<PackageDependency>,
117 /// Rust edition for this package
118 pub edition: Edition,
119 /// Features provided by the crate, mapped to the features required by that feature.
120 pub features: FxHashMap<String, Vec<String>>,
121 /// List of features enabled on this package
122 pub active_features: Vec<String>,
123 // String representation of package id
125 // The contents of [package.metadata.rust-analyzer]
126 pub metadata: RustAnalyzerPackageMetaData,
129 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
130 pub struct RustAnalyzerPackageMetaData {
131 pub rustc_private: bool,
134 #[derive(Debug, Clone, Eq, PartialEq)]
135 pub struct PackageDependency {
141 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
143 /// Available to the library, binary, and dev targets in the package (but not the build script).
145 /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
147 /// Available only to the build script target.
152 fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
153 let mut dep_kinds = Vec::new();
155 dep_kinds.push(Self::Normal);
158 let kind = match info.kind {
159 cargo_metadata::DependencyKind::Normal => Self::Normal,
160 cargo_metadata::DependencyKind::Development => Self::Dev,
161 cargo_metadata::DependencyKind::Build => Self::Build,
162 cargo_metadata::DependencyKind::Unknown => continue,
164 dep_kinds.push(kind);
166 dep_kinds.sort_unstable();
168 dep_kinds.into_iter()
172 /// Information associated with a package's target
173 #[derive(Debug, Clone, Eq, PartialEq)]
174 pub struct TargetData {
175 /// Package that provided this target
176 pub package: Package,
177 /// Name as given in the `Cargo.toml` or generated from the file name
179 /// Path to the main source file of the target
180 pub root: AbsPathBuf,
182 pub kind: TargetKind,
183 /// Is this target a proc-macro
184 pub is_proc_macro: bool,
187 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
188 pub enum TargetKind {
190 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
200 fn new(kinds: &[String]) -> TargetKind {
202 return match kind.as_str() {
203 "bin" => TargetKind::Bin,
204 "test" => TargetKind::Test,
205 "bench" => TargetKind::Bench,
206 "example" => TargetKind::Example,
207 "custom-build" => TargetKind::BuildScript,
208 "proc-macro" => TargetKind::Lib,
209 _ if kind.contains("lib") => TargetKind::Lib,
218 pub fn root(&self) -> &AbsPath {
219 self.manifest.parent().unwrap()
223 #[derive(Deserialize, Default)]
224 // Deserialise helper for the cargo metadata
225 struct PackageMetadata {
226 #[serde(rename = "rust-analyzer")]
227 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
230 impl CargoWorkspace {
231 pub fn from_cargo_metadata(
232 cargo_toml: &AbsPath,
233 config: &CargoConfig,
234 progress: &dyn Fn(String),
235 ) -> Result<CargoWorkspace> {
236 let mut meta = MetadataCommand::new();
237 meta.cargo_path(toolchain::cargo());
238 meta.manifest_path(cargo_toml.to_path_buf());
239 if config.all_features {
240 meta.features(CargoOpt::AllFeatures);
242 if config.no_default_features {
243 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
244 // https://github.com/oli-obk/cargo_metadata/issues/79
245 meta.features(CargoOpt::NoDefaultFeatures);
247 if !config.features.is_empty() {
248 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
251 if let Some(parent) = cargo_toml.parent() {
252 meta.current_dir(parent.to_path_buf());
254 let target = if let Some(target) = &config.target {
256 } else if let stdout @ Some(_) = cargo_config_build_target(cargo_toml) {
259 rustc_discover_host_triple(cargo_toml)
261 if let Some(target) = target {
262 meta.other_options(vec![String::from("--filter-platform"), target]);
265 // FIXME: Currently MetadataCommand is not based on parse_stream,
266 // So we just report it as a whole
267 progress("metadata".to_string());
268 let mut meta = meta.exec().with_context(|| {
269 let cwd: Option<AbsPathBuf> =
270 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
272 let workdir = cargo_toml
274 .map(|p| p.to_path_buf())
276 .map(|dir| dir.to_string_lossy().to_string())
277 .unwrap_or_else(|| "<failed to get path>".into());
280 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
281 cargo_toml.display(),
286 let mut pkg_by_id = FxHashMap::default();
287 let mut packages = Arena::default();
288 let mut targets = Arena::default();
290 let ws_members = &meta.workspace_members;
292 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
293 for meta_pkg in &meta.packages {
294 let cargo_metadata::Package {
295 id, edition, name, manifest_path, version, metadata, ..
297 let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
298 let is_member = ws_members.contains(id);
299 let edition = edition
301 .with_context(|| format!("Failed to parse edition {}", edition))?;
303 let pkg = packages.alloc(PackageData {
306 version: version.to_string(),
307 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
311 dependencies: Vec::new(),
312 features: meta_pkg.features.clone().into_iter().collect(),
313 active_features: Vec::new(),
314 metadata: meta.rust_analyzer.unwrap_or_default(),
316 let pkg_data = &mut packages[pkg];
317 pkg_by_id.insert(id, pkg);
318 for meta_tgt in &meta_pkg.targets {
319 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
320 let tgt = targets.alloc(TargetData {
322 name: meta_tgt.name.clone(),
323 root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
324 kind: TargetKind::new(meta_tgt.kind.as_slice()),
327 pkg_data.targets.push(tgt);
330 let resolve = meta.resolve.expect("metadata executed with deps");
331 for mut node in resolve.nodes {
332 let source = match pkg_by_id.get(&node.id) {
334 // FIXME: replace this and a similar branch below with `.unwrap`, once
335 // https://github.com/rust-lang/cargo/issues/7841
336 // is fixed and hits stable (around 1.43-is probably?).
338 log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
342 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
343 for (dep_node, kind) in node
346 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
348 let pkg = match pkg_by_id.get(&dep_node.pkg) {
352 "Dep node id do not match in cargo metadata, ignoring {}",
358 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
359 packages[source].dependencies.push(dep);
361 packages[source].active_features.extend(node.features);
365 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
366 let build_data_config =
367 BuildDataConfig::new(cargo_toml.to_path_buf(), config.clone(), Arc::new(meta.packages));
369 Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
372 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
373 self.packages.iter().map(|(id, _pkg)| id)
376 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
378 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
383 pub fn workspace_root(&self) -> &AbsPath {
387 pub fn package_flag(&self, package: &PackageData) -> String {
388 if self.is_unique(&*package.name) {
391 format!("{}:{}", package.name, package.version)
395 pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
396 &self.build_data_config
399 fn is_unique(&self, name: &str) -> bool {
400 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
404 fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> Option<String> {
405 let mut rustc = Command::new(toolchain::rustc());
406 rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
407 log::debug!("Discovering host platform by {:?}", rustc);
408 match utf8_stdout(rustc) {
410 let field = "host: ";
411 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
412 if let Some(target) = target {
413 Some(target.to_string())
415 // If we fail to resolve the host platform, it's not the end of the world.
416 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
421 log::warn!("Failed to discover host platform: {}", e);
427 fn cargo_config_build_target(cargo_toml: &AbsPath) -> Option<String> {
428 let mut cargo_config = Command::new(toolchain::cargo());
430 .current_dir(cargo_toml.parent().unwrap())
431 .args(&["-Z", "unstable-options", "config", "get", "build.target"])
432 .env("RUSTC_BOOTSTRAP", "1");
433 // if successful we receive `build.target = "target-triple"`
434 log::debug!("Discovering cargo config target by {:?}", cargo_config);
435 match utf8_stdout(cargo_config) {
437 .strip_prefix("build.target = \"")
438 .and_then(|stdout| stdout.strip_suffix('"'))
439 .map(ToOwned::to_owned),