1 //! See [`CargoWorkspace`].
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;
12 use serde::Deserialize;
13 use serde_json::from_value;
15 use crate::{build_data::BuildDataConfig, utf8_stdout};
17 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
18 /// workspace. It pretty closely mirrors `cargo metadata` output.
20 /// Note that internally, rust analyzer uses a different structure:
21 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
22 /// while this knows about `Packages` & `Targets`: purely cargo-related
25 /// We use absolute paths here, `cargo metadata` guarantees to always produce
27 #[derive(Debug, Clone, Eq, PartialEq)]
28 pub struct CargoWorkspace {
29 packages: Arena<PackageData>,
30 targets: Arena<TargetData>,
31 workspace_root: AbsPathBuf,
32 build_data_config: BuildDataConfig,
35 impl ops::Index<Package> for CargoWorkspace {
36 type Output = PackageData;
37 fn index(&self, index: Package) -> &PackageData {
42 impl ops::Index<Target> for CargoWorkspace {
43 type Output = TargetData;
44 fn index(&self, index: Target) -> &TargetData {
49 /// Describes how to set the rustc source directory.
50 #[derive(Clone, Debug, PartialEq, Eq)]
51 pub enum RustcSource {
52 /// Explicit path for the rustc source directory.
54 /// Try to automatically detect where the rustc source directory is.
58 #[derive(Default, Clone, Debug, PartialEq, Eq)]
59 pub struct CargoConfig {
60 /// Do not activate the `default` feature.
61 pub no_default_features: bool,
63 /// Activate all available features
64 pub all_features: bool,
66 /// List of features to activate.
67 /// This will be ignored if `cargo_all_features` is true.
68 pub features: Vec<String>,
71 pub target: Option<String>,
73 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
74 /// when debugging isolated issues.
77 /// rustc private crate source
78 pub rustc_source: Option<RustcSource>,
81 pub type Package = Idx<PackageData>;
83 pub type Target = Idx<TargetData>;
85 /// Information associated with a cargo crate
86 #[derive(Debug, Clone, Eq, PartialEq)]
87 pub struct PackageData {
88 /// Version given in the `Cargo.toml`
90 /// Name as given in the `Cargo.toml`
92 /// Path containing the `Cargo.toml`
93 pub manifest: AbsPathBuf,
94 /// Targets provided by the crate (lib, bin, example, test, ...)
95 pub targets: Vec<Target>,
96 /// Is this package a member of the current workspace
98 /// List of packages this package depends on
99 pub dependencies: Vec<PackageDependency>,
100 /// Rust edition for this package
101 pub edition: Edition,
102 /// Features provided by the crate, mapped to the features required by that feature.
103 pub features: FxHashMap<String, Vec<String>>,
104 /// List of features enabled on this package
105 pub active_features: Vec<String>,
106 // String representation of package id
108 // The contents of [package.metadata.rust-analyzer]
109 pub metadata: RustAnalyzerPackageMetaData,
112 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
113 pub struct RustAnalyzerPackageMetaData {
114 pub rustc_private: bool,
117 #[derive(Debug, Clone, Eq, PartialEq)]
118 pub struct PackageDependency {
124 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
126 /// Available to the library, binary, and dev targets in the package (but not the build script).
128 /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
130 /// Available only to the build script target.
135 fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
136 let mut dep_kinds = Vec::new();
138 dep_kinds.push(Self::Normal);
141 let kind = match info.kind {
142 cargo_metadata::DependencyKind::Normal => Self::Normal,
143 cargo_metadata::DependencyKind::Development => Self::Dev,
144 cargo_metadata::DependencyKind::Build => Self::Build,
145 cargo_metadata::DependencyKind::Unknown => continue,
147 dep_kinds.push(kind);
149 dep_kinds.sort_unstable();
151 dep_kinds.into_iter()
155 /// Information associated with a package's target
156 #[derive(Debug, Clone, Eq, PartialEq)]
157 pub struct TargetData {
158 /// Package that provided this target
159 pub package: Package,
160 /// Name as given in the `Cargo.toml` or generated from the file name
162 /// Path to the main source file of the target
163 pub root: AbsPathBuf,
165 pub kind: TargetKind,
166 /// Is this target a proc-macro
167 pub is_proc_macro: bool,
170 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
171 pub enum TargetKind {
173 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
183 fn new(kinds: &[String]) -> TargetKind {
185 return match kind.as_str() {
186 "bin" => TargetKind::Bin,
187 "test" => TargetKind::Test,
188 "bench" => TargetKind::Bench,
189 "example" => TargetKind::Example,
190 "custom-build" => TargetKind::BuildScript,
191 "proc-macro" => TargetKind::Lib,
192 _ if kind.contains("lib") => TargetKind::Lib,
201 pub fn root(&self) -> &AbsPath {
202 self.manifest.parent().unwrap()
206 #[derive(Deserialize, Default)]
207 // Deserialise helper for the cargo metadata
208 struct PackageMetadata {
209 #[serde(rename = "rust-analyzer")]
210 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
213 impl CargoWorkspace {
214 pub fn from_cargo_metadata(
215 cargo_toml: &AbsPath,
216 config: &CargoConfig,
217 progress: &dyn Fn(String),
218 ) -> Result<CargoWorkspace> {
219 let mut meta = MetadataCommand::new();
220 meta.cargo_path(toolchain::cargo());
221 meta.manifest_path(cargo_toml.to_path_buf());
222 if config.all_features {
223 meta.features(CargoOpt::AllFeatures);
225 if config.no_default_features {
226 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
227 // https://github.com/oli-obk/cargo_metadata/issues/79
228 meta.features(CargoOpt::NoDefaultFeatures);
230 if !config.features.is_empty() {
231 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
234 if let Some(parent) = cargo_toml.parent() {
235 meta.current_dir(parent.to_path_buf());
237 let target = if let Some(target) = &config.target {
239 } else if let stdout @ Some(_) = cargo_config_build_target(cargo_toml) {
242 rustc_discover_host_triple(cargo_toml)
244 if let Some(target) = target {
245 meta.other_options(vec![String::from("--filter-platform"), target]);
248 // FIXME: Currently MetadataCommand is not based on parse_stream,
249 // So we just report it as a whole
250 progress("metadata".to_string());
251 let mut meta = meta.exec().with_context(|| {
252 let cwd: Option<AbsPathBuf> =
253 std::env::current_dir().ok().and_then(|p| p.try_into().ok());
255 let workdir = cargo_toml
257 .map(|p| p.to_path_buf())
259 .map(|dir| dir.to_string_lossy().to_string())
260 .unwrap_or_else(|| "<failed to get path>".into());
263 "Failed to run `cargo metadata --manifest-path {}` in `{}`",
264 cargo_toml.display(),
269 let mut pkg_by_id = FxHashMap::default();
270 let mut packages = Arena::default();
271 let mut targets = Arena::default();
273 let ws_members = &meta.workspace_members;
275 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
276 for meta_pkg in &meta.packages {
277 let cargo_metadata::Package {
278 id, edition, name, manifest_path, version, metadata, ..
280 let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
281 let is_member = ws_members.contains(&id);
282 let edition = edition
284 .with_context(|| format!("Failed to parse edition {}", edition))?;
286 let pkg = packages.alloc(PackageData {
289 version: version.to_string(),
290 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
294 dependencies: Vec::new(),
295 features: meta_pkg.features.clone().into_iter().collect(),
296 active_features: Vec::new(),
297 metadata: meta.rust_analyzer.unwrap_or_default(),
299 let pkg_data = &mut packages[pkg];
300 pkg_by_id.insert(id, pkg);
301 for meta_tgt in &meta_pkg.targets {
302 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
303 let tgt = targets.alloc(TargetData {
305 name: meta_tgt.name.clone(),
306 root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
307 kind: TargetKind::new(meta_tgt.kind.as_slice()),
310 pkg_data.targets.push(tgt);
313 let resolve = meta.resolve.expect("metadata executed with deps");
314 for mut node in resolve.nodes {
315 let source = match pkg_by_id.get(&node.id) {
317 // FIXME: replace this and a similar branch below with `.unwrap`, once
318 // https://github.com/rust-lang/cargo/issues/7841
319 // is fixed and hits stable (around 1.43-is probably?).
321 log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
325 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
326 for (dep_node, kind) in node
329 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
331 let pkg = match pkg_by_id.get(&dep_node.pkg) {
335 "Dep node id do not match in cargo metadata, ignoring {}",
341 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
342 packages[source].dependencies.push(dep);
344 packages[source].active_features.extend(node.features);
348 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
349 let build_data_config = BuildDataConfig::new(
350 cargo_toml.to_path_buf(),
352 Arc::new(meta.packages.clone()),
355 Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
358 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
359 self.packages.iter().map(|(id, _pkg)| id)
362 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
364 .filter_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
369 pub fn workspace_root(&self) -> &AbsPath {
373 pub fn package_flag(&self, package: &PackageData) -> String {
374 if self.is_unique(&*package.name) {
377 format!("{}:{}", package.name, package.version)
381 pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
382 &self.build_data_config
385 fn is_unique(&self, name: &str) -> bool {
386 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
390 fn rustc_discover_host_triple(cargo_toml: &AbsPath) -> Option<String> {
391 let mut rustc = Command::new(toolchain::rustc());
392 rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
393 log::debug!("Discovering host platform by {:?}", rustc);
394 match utf8_stdout(rustc) {
396 let field = "host: ";
397 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
398 if let Some(target) = target {
399 Some(target.to_string())
401 // If we fail to resolve the host platform, it's not the end of the world.
402 log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
407 log::warn!("Failed to discover host platform: {}", e);
413 fn cargo_config_build_target(cargo_toml: &AbsPath) -> Option<String> {
414 let mut cargo_config = Command::new(toolchain::cargo());
416 .current_dir(cargo_toml.parent().unwrap())
417 .args(&["-Z", "unstable-options", "config", "get", "build.target"])
418 .env("RUSTC_BOOTSTRAP", "1");
419 // if successful we receive `build.target = "target-triple"`
420 log::debug!("Discovering cargo config target by {:?}", cargo_config);
421 match utf8_stdout(cargo_config) {
423 .strip_prefix("build.target = \"")
424 .and_then(|stdout| stdout.strip_suffix('"'))
425 .map(ToOwned::to_owned),