1 //! See [`CargoWorkspace`].
4 use std::path::PathBuf;
5 use std::{ops, process::Command};
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::{utf8_stdout, ManifestPath};
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,
36 impl ops::Index<Package> for CargoWorkspace {
37 type Output = PackageData;
38 fn index(&self, index: Package) -> &PackageData {
43 impl ops::Index<Target> for CargoWorkspace {
44 type Output = TargetData;
45 fn index(&self, index: Target) -> &TargetData {
50 /// Describes how to set the rustc source directory.
51 #[derive(Clone, Debug, PartialEq, Eq)]
52 pub enum RustcSource {
53 /// Explicit path for the rustc source directory.
55 /// Try to automatically detect where the rustc source directory is.
59 /// Crates to disable `#[cfg(test)]` on.
60 #[derive(Clone, Debug, PartialEq, Eq)]
61 pub enum UnsetTestCrates {
67 impl Default for UnsetTestCrates {
68 fn default() -> Self {
73 #[derive(Default, Clone, Debug, PartialEq, Eq)]
74 pub struct CargoConfig {
75 /// Do not activate the `default` feature.
76 pub no_default_features: bool,
78 /// Activate all available features
79 pub all_features: bool,
81 /// List of features to activate.
82 /// This will be ignored if `cargo_all_features` is true.
83 pub features: Vec<String>,
86 pub target: Option<String>,
88 /// Don't load sysroot crates (`std`, `core` & friends). Might be useful
89 /// when debugging isolated issues.
92 /// rustc private crate source
93 pub rustc_source: Option<RustcSource>,
95 /// crates to disable `#[cfg(test)]` on
96 pub unset_test_crates: UnsetTestCrates,
98 pub wrap_rustc_in_build_scripts: bool,
100 pub run_build_script_command: Option<Vec<String>>,
104 pub fn cfg_overrides(&self) -> CfgOverrides {
105 match &self.unset_test_crates {
106 UnsetTestCrates::None => CfgOverrides::Selective(iter::empty().collect()),
107 UnsetTestCrates::Only(unset_test_crates) => CfgOverrides::Selective(
111 .zip(iter::repeat_with(|| {
112 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())])
117 UnsetTestCrates::All => CfgOverrides::Wildcard(
118 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap(),
124 pub type Package = Idx<PackageData>;
126 pub type Target = Idx<TargetData>;
128 /// Information associated with a cargo crate
129 #[derive(Debug, Clone, Eq, PartialEq)]
130 pub struct PackageData {
131 /// Version given in the `Cargo.toml`
132 pub version: semver::Version,
133 /// Name as given in the `Cargo.toml`
135 /// Repository as given in the `Cargo.toml`
136 pub repository: Option<String>,
137 /// Path containing the `Cargo.toml`
138 pub manifest: ManifestPath,
139 /// Targets provided by the crate (lib, bin, example, test, ...)
140 pub targets: Vec<Target>,
141 /// Does this package come from the local filesystem (and is editable)?
143 // Whether this package is a member of the workspace
145 /// List of packages this package depends on
146 pub dependencies: Vec<PackageDependency>,
147 /// Rust edition for this package
148 pub edition: Edition,
149 /// Features provided by the crate, mapped to the features required by that feature.
150 pub features: FxHashMap<String, Vec<String>>,
151 /// List of features enabled on this package
152 pub active_features: Vec<String>,
153 /// String representation of package id
155 /// The contents of [package.metadata.rust-analyzer]
156 pub metadata: RustAnalyzerPackageMetaData,
159 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
160 pub struct RustAnalyzerPackageMetaData {
161 pub rustc_private: bool,
164 #[derive(Debug, Clone, Eq, PartialEq)]
165 pub struct PackageDependency {
171 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
173 /// Available to the library, binary, and dev targets in the package (but not the build script).
175 /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
177 /// Available only to the build script target.
182 fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
183 let mut dep_kinds = Vec::new();
185 dep_kinds.push(Self::Normal);
188 let kind = match info.kind {
189 cargo_metadata::DependencyKind::Normal => Self::Normal,
190 cargo_metadata::DependencyKind::Development => Self::Dev,
191 cargo_metadata::DependencyKind::Build => Self::Build,
192 cargo_metadata::DependencyKind::Unknown => continue,
194 dep_kinds.push(kind);
196 dep_kinds.sort_unstable();
198 dep_kinds.into_iter()
202 /// Information associated with a package's target
203 #[derive(Debug, Clone, Eq, PartialEq)]
204 pub struct TargetData {
205 /// Package that provided this target
206 pub package: Package,
207 /// Name as given in the `Cargo.toml` or generated from the file name
209 /// Path to the main source file of the target
210 pub root: AbsPathBuf,
212 pub kind: TargetKind,
213 /// Is this target a proc-macro
214 pub is_proc_macro: bool,
215 /// Required features of the target without which it won't build
216 pub required_features: Vec<String>,
219 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
220 pub enum TargetKind {
222 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
232 fn new(kinds: &[String]) -> TargetKind {
234 return match kind.as_str() {
235 "bin" => TargetKind::Bin,
236 "test" => TargetKind::Test,
237 "bench" => TargetKind::Bench,
238 "example" => TargetKind::Example,
239 "custom-build" => TargetKind::BuildScript,
240 "proc-macro" => TargetKind::Lib,
241 _ if kind.contains("lib") => TargetKind::Lib,
249 #[derive(Deserialize, Default)]
250 // Deserialise helper for the cargo metadata
251 struct PackageMetadata {
252 #[serde(rename = "rust-analyzer")]
253 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
256 impl CargoWorkspace {
257 pub fn fetch_metadata(
258 cargo_toml: &ManifestPath,
259 current_dir: &AbsPath,
260 config: &CargoConfig,
261 progress: &dyn Fn(String),
262 ) -> Result<cargo_metadata::Metadata> {
266 .or_else(|| cargo_config_build_target(cargo_toml))
267 .or_else(|| rustc_discover_host_triple(cargo_toml));
269 let mut meta = MetadataCommand::new();
270 meta.cargo_path(toolchain::cargo());
271 meta.manifest_path(cargo_toml.to_path_buf());
272 if config.all_features {
273 meta.features(CargoOpt::AllFeatures);
275 if config.no_default_features {
276 // FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
277 // https://github.com/oli-obk/cargo_metadata/issues/79
278 meta.features(CargoOpt::NoDefaultFeatures);
280 if !config.features.is_empty() {
281 meta.features(CargoOpt::SomeFeatures(config.features.clone()));
284 meta.current_dir(current_dir.as_os_str());
286 if let Some(target) = target {
287 meta.other_options(vec![String::from("--filter-platform"), target]);
290 // FIXME: Fetching metadata is a slow process, as it might require
291 // calling crates.io. We should be reporting progress here, but it's
292 // unclear whether cargo itself supports it.
293 progress("metadata".to_string());
296 meta.exec().with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))?;
301 pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
302 let mut pkg_by_id = FxHashMap::default();
303 let mut packages = Arena::default();
304 let mut targets = Arena::default();
306 let ws_members = &meta.workspace_members;
308 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
309 for meta_pkg in &meta.packages {
310 let cargo_metadata::Package {
320 let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
321 let edition = match edition {
322 cargo_metadata::Edition::E2015 => Edition::Edition2015,
323 cargo_metadata::Edition::E2018 => Edition::Edition2018,
324 cargo_metadata::Edition::E2021 => Edition::Edition2021,
326 tracing::error!("Unsupported edition `{:?}`", edition);
330 // We treat packages without source as "local" packages. That includes all members of
331 // the current workspace, as well as any path dependency outside the workspace.
332 let is_local = meta_pkg.source.is_none();
333 let is_member = ws_members.contains(id);
335 let pkg = packages.alloc(PackageData {
338 version: version.clone(),
339 manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)).try_into().unwrap(),
344 repository: repository.clone(),
345 dependencies: Vec::new(),
346 features: meta_pkg.features.clone().into_iter().collect(),
347 active_features: Vec::new(),
348 metadata: meta.rust_analyzer.unwrap_or_default(),
350 let pkg_data = &mut packages[pkg];
351 pkg_by_id.insert(id, pkg);
352 for meta_tgt in &meta_pkg.targets {
353 let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
354 let tgt = targets.alloc(TargetData {
356 name: meta_tgt.name.clone(),
357 root: AbsPathBuf::assert(PathBuf::from(&meta_tgt.src_path)),
358 kind: TargetKind::new(meta_tgt.kind.as_slice()),
360 required_features: meta_tgt.required_features.clone(),
362 pkg_data.targets.push(tgt);
365 let resolve = meta.resolve.expect("metadata executed with deps");
366 for mut node in resolve.nodes {
367 let source = match pkg_by_id.get(&node.id) {
369 // FIXME: replace this and a similar branch below with `.unwrap`, once
370 // https://github.com/rust-lang/cargo/issues/7841
371 // is fixed and hits stable (around 1.43-is probably?).
373 tracing::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
377 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
378 for (dep_node, kind) in node
381 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
383 let pkg = match pkg_by_id.get(&dep_node.pkg) {
387 "Dep node id do not match in cargo metadata, ignoring {}",
393 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
394 packages[source].dependencies.push(dep);
396 packages[source].active_features.extend(node.features);
400 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
402 CargoWorkspace { packages, targets, workspace_root }
405 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
406 self.packages.iter().map(|(id, _pkg)| id)
409 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
411 .filter(|&pkg| self[pkg].is_member)
412 .find_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
416 pub fn workspace_root(&self) -> &AbsPath {
420 pub fn package_flag(&self, package: &PackageData) -> String {
421 if self.is_unique(&*package.name) {
424 format!("{}:{}", package.name, package.version)
428 pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
429 let mut found = false;
430 let parent_manifests = self
433 if !found && &self[pkg].manifest == manifest_path {
436 self[pkg].dependencies.iter().find_map(|dep| {
437 if &self[dep.pkg].manifest == manifest_path {
438 return Some(self[pkg].manifest.clone());
443 .collect::<Vec<ManifestPath>>();
445 // some packages has this pkg as dep. return their manifests
446 if parent_manifests.len() > 0 {
447 return Some(parent_manifests);
450 // this pkg is inside this cargo workspace, fallback to workspace root
453 ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
457 // not in this workspace
461 fn is_unique(&self, name: &str) -> bool {
462 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
466 fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
467 let mut rustc = Command::new(toolchain::rustc());
468 rustc.current_dir(cargo_toml.parent()).arg("-vV");
469 tracing::debug!("Discovering host platform by {:?}", rustc);
470 match utf8_stdout(rustc) {
472 let field = "host: ";
473 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
474 if let Some(target) = target {
475 Some(target.to_string())
477 // If we fail to resolve the host platform, it's not the end of the world.
478 tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
483 tracing::warn!("Failed to discover host platform: {}", e);
489 fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
490 let mut cargo_config = Command::new(toolchain::cargo());
492 .current_dir(cargo_toml.parent())
493 .args(&["-Z", "unstable-options", "config", "get", "build.target"])
494 .env("RUSTC_BOOTSTRAP", "1");
495 // if successful we receive `build.target = "target-triple"`
496 tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
497 match utf8_stdout(cargo_config) {
499 .strip_prefix("build.target = \"")
500 .and_then(|stdout| stdout.strip_suffix('"'))
501 .map(ToOwned::to_owned),