1 //! See [`CargoWorkspace`].
4 use std::path::PathBuf;
5 use std::str::from_utf8;
6 use std::{ops, process::Command};
8 use anyhow::{Context, Result};
10 use cargo_metadata::{CargoOpt, MetadataCommand};
11 use la_arena::{Arena, Idx};
12 use paths::{AbsPath, AbsPathBuf};
13 use rustc_hash::FxHashMap;
14 use serde::Deserialize;
15 use serde_json::from_value;
17 use crate::{utf8_stdout, InvocationLocation, ManifestPath};
18 use crate::{CfgOverrides, InvocationStrategy};
20 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
21 /// workspace. It pretty closely mirrors `cargo metadata` output.
23 /// Note that internally, rust-analyzer uses a different structure:
24 /// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
25 /// while this knows about `Packages` & `Targets`: purely cargo-related
28 /// We use absolute paths here, `cargo metadata` guarantees to always produce
30 #[derive(Debug, Clone, Eq, PartialEq)]
31 pub struct CargoWorkspace {
32 packages: Arena<PackageData>,
33 targets: Arena<TargetData>,
34 workspace_root: AbsPathBuf,
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 /// Crates to disable `#[cfg(test)]` on.
61 #[derive(Clone, Debug, PartialEq, Eq)]
62 pub enum UnsetTestCrates {
68 impl Default for UnsetTestCrates {
69 fn default() -> Self {
74 #[derive(Clone, Debug, PartialEq, Eq)]
75 pub enum CargoFeatures {
78 /// List of features to activate.
79 features: Vec<String>,
80 /// Do not activate the `default` feature.
81 no_default_features: bool,
85 impl Default for CargoFeatures {
86 fn default() -> Self {
87 CargoFeatures::Selected { features: vec![], no_default_features: false }
91 #[derive(Default, Clone, Debug, PartialEq, Eq)]
92 pub struct CargoConfig {
93 /// List of features to activate.
94 pub features: CargoFeatures,
96 pub target: Option<String>,
97 /// Sysroot loading behavior
98 pub sysroot: Option<RustcSource>,
99 /// rustc private crate source
100 pub rustc_source: Option<RustcSource>,
101 /// crates to disable `#[cfg(test)]` on
102 pub unset_test_crates: UnsetTestCrates,
103 /// Invoke `cargo check` through the RUSTC_WRAPPER.
104 pub wrap_rustc_in_build_scripts: bool,
105 /// The command to run instead of `cargo check` for building build scripts.
106 pub run_build_script_command: Option<Vec<String>>,
107 /// Extra env vars to set when invoking the cargo command
108 pub extra_env: FxHashMap<String, String>,
109 pub invocation_strategy: InvocationStrategy,
110 pub invocation_location: InvocationLocation,
114 pub fn cfg_overrides(&self) -> CfgOverrides {
115 match &self.unset_test_crates {
116 UnsetTestCrates::None => CfgOverrides::Selective(iter::empty().collect()),
117 UnsetTestCrates::Only(unset_test_crates) => CfgOverrides::Selective(
121 .zip(iter::repeat_with(|| {
122 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())])
127 UnsetTestCrates::All => CfgOverrides::Wildcard(
128 cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap(),
134 pub type Package = Idx<PackageData>;
136 pub type Target = Idx<TargetData>;
138 /// Information associated with a cargo crate
139 #[derive(Debug, Clone, Eq, PartialEq)]
140 pub struct PackageData {
141 /// Version given in the `Cargo.toml`
142 pub version: semver::Version,
143 /// Name as given in the `Cargo.toml`
145 /// Repository as given in the `Cargo.toml`
146 pub repository: Option<String>,
147 /// Path containing the `Cargo.toml`
148 pub manifest: ManifestPath,
149 /// Targets provided by the crate (lib, bin, example, test, ...)
150 pub targets: Vec<Target>,
151 /// Does this package come from the local filesystem (and is editable)?
153 /// Whether this package is a member of the workspace
155 /// List of packages this package depends on
156 pub dependencies: Vec<PackageDependency>,
157 /// Rust edition for this package
158 pub edition: Edition,
159 /// Features provided by the crate, mapped to the features required by that feature.
160 pub features: FxHashMap<String, Vec<String>>,
161 /// List of features enabled on this package
162 pub active_features: Vec<String>,
163 /// String representation of package id
165 /// The contents of [package.metadata.rust-analyzer]
166 pub metadata: RustAnalyzerPackageMetaData,
169 #[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
170 pub struct RustAnalyzerPackageMetaData {
171 pub rustc_private: bool,
174 #[derive(Debug, Clone, Eq, PartialEq)]
175 pub struct PackageDependency {
181 #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
183 /// Available to the library, binary, and dev targets in the package (but not the build script).
185 /// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
187 /// Available only to the build script target.
192 fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> + '_ {
193 let mut dep_kinds = Vec::new();
195 dep_kinds.push(Self::Normal);
198 let kind = match info.kind {
199 cargo_metadata::DependencyKind::Normal => Self::Normal,
200 cargo_metadata::DependencyKind::Development => Self::Dev,
201 cargo_metadata::DependencyKind::Build => Self::Build,
202 cargo_metadata::DependencyKind::Unknown => continue,
204 dep_kinds.push(kind);
206 dep_kinds.sort_unstable();
208 dep_kinds.into_iter()
212 /// Information associated with a package's target
213 #[derive(Debug, Clone, Eq, PartialEq)]
214 pub struct TargetData {
215 /// Package that provided this target
216 pub package: Package,
217 /// Name as given in the `Cargo.toml` or generated from the file name
219 /// Path to the main source file of the target
220 pub root: AbsPathBuf,
222 pub kind: TargetKind,
223 /// Is this target a proc-macro
224 pub is_proc_macro: bool,
225 /// Required features of the target without which it won't build
226 pub required_features: Vec<String>,
229 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
230 pub enum TargetKind {
232 /// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
242 fn new(kinds: &[String]) -> TargetKind {
244 return match kind.as_str() {
245 "bin" => TargetKind::Bin,
246 "test" => TargetKind::Test,
247 "bench" => TargetKind::Bench,
248 "example" => TargetKind::Example,
249 "custom-build" => TargetKind::BuildScript,
250 "proc-macro" => TargetKind::Lib,
251 _ if kind.contains("lib") => TargetKind::Lib,
259 // Deserialize helper for the cargo metadata
260 #[derive(Deserialize, Default)]
261 struct PackageMetadata {
262 #[serde(rename = "rust-analyzer")]
263 rust_analyzer: Option<RustAnalyzerPackageMetaData>,
266 impl CargoWorkspace {
267 pub fn fetch_metadata(
268 cargo_toml: &ManifestPath,
269 current_dir: &AbsPath,
270 config: &CargoConfig,
271 progress: &dyn Fn(String),
272 ) -> Result<cargo_metadata::Metadata> {
276 .or_else(|| cargo_config_build_target(cargo_toml, &config.extra_env))
277 .or_else(|| rustc_discover_host_triple(cargo_toml, &config.extra_env));
279 let mut meta = MetadataCommand::new();
280 meta.cargo_path(toolchain::cargo());
281 meta.manifest_path(cargo_toml.to_path_buf());
282 match &config.features {
283 CargoFeatures::All => {
284 meta.features(CargoOpt::AllFeatures);
286 CargoFeatures::Selected { features, no_default_features } => {
287 if *no_default_features {
288 meta.features(CargoOpt::NoDefaultFeatures);
290 if !features.is_empty() {
291 meta.features(CargoOpt::SomeFeatures(features.clone()));
295 meta.current_dir(current_dir.as_os_str());
297 if let Some(target) = target {
298 meta.other_options(vec![String::from("--filter-platform"), target]);
301 // FIXME: Fetching metadata is a slow process, as it might require
302 // calling crates.io. We should be reporting progress here, but it's
303 // unclear whether cargo itself supports it.
304 progress("metadata".to_string());
306 (|| -> Result<cargo_metadata::Metadata, cargo_metadata::Error> {
307 let mut command = meta.cargo_command();
308 command.envs(&config.extra_env);
309 let output = command.output()?;
310 if !output.status.success() {
311 return Err(cargo_metadata::Error::CargoMetadata {
312 stderr: String::from_utf8(output.stderr)?,
315 let stdout = from_utf8(&output.stdout)?
317 .find(|line| line.starts_with('{'))
318 .ok_or(cargo_metadata::Error::NoJson)?;
319 cargo_metadata::MetadataCommand::parse(stdout)
321 .with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))
324 pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
325 let mut pkg_by_id = FxHashMap::default();
326 let mut packages = Arena::default();
327 let mut targets = Arena::default();
329 let ws_members = &meta.workspace_members;
331 meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
332 for meta_pkg in meta.packages {
333 let cargo_metadata::Package {
338 targets: meta_targets,
346 let meta = from_value::<PackageMetadata>(metadata).unwrap_or_default();
347 let edition = match edition {
348 cargo_metadata::Edition::E2015 => Edition::Edition2015,
349 cargo_metadata::Edition::E2018 => Edition::Edition2018,
350 cargo_metadata::Edition::E2021 => Edition::Edition2021,
352 tracing::error!("Unsupported edition `{:?}`", edition);
356 // We treat packages without source as "local" packages. That includes all members of
357 // the current workspace, as well as any path dependency outside the workspace.
358 let is_local = source.is_none();
359 let is_member = ws_members.contains(&id);
361 let pkg = packages.alloc(PackageData {
365 manifest: AbsPathBuf::assert(manifest_path.into()).try_into().unwrap(),
371 dependencies: Vec::new(),
372 features: features.into_iter().collect(),
373 active_features: Vec::new(),
374 metadata: meta.rust_analyzer.unwrap_or_default(),
376 let pkg_data = &mut packages[pkg];
377 pkg_by_id.insert(id, pkg);
378 for meta_tgt in meta_targets {
379 let cargo_metadata::Target { name, kind, required_features, src_path, .. } =
381 let tgt = targets.alloc(TargetData {
384 root: AbsPathBuf::assert(src_path.into()),
385 kind: TargetKind::new(&kind),
386 is_proc_macro: &*kind == ["proc-macro"],
389 pkg_data.targets.push(tgt);
392 let resolve = meta.resolve.expect("metadata executed with deps");
393 for mut node in resolve.nodes {
394 let &source = pkg_by_id.get(&node.id).unwrap();
395 node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
396 let dependencies = node
399 .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)));
400 for (dep_node, kind) in dependencies {
401 let &pkg = pkg_by_id.get(&dep_node.pkg).unwrap();
402 let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
403 packages[source].dependencies.push(dep);
405 packages[source].active_features.extend(node.features);
409 AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
411 CargoWorkspace { packages, targets, workspace_root }
414 pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
415 self.packages.iter().map(|(id, _pkg)| id)
418 pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
420 .filter(|&pkg| self[pkg].is_member)
421 .find_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
425 pub fn workspace_root(&self) -> &AbsPath {
429 pub fn package_flag(&self, package: &PackageData) -> String {
430 if self.is_unique(&*package.name) {
433 format!("{}:{}", package.name, package.version)
437 pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
438 let mut found = false;
439 let parent_manifests = self
442 if !found && &self[pkg].manifest == manifest_path {
445 self[pkg].dependencies.iter().find_map(|dep| {
446 (&self[dep.pkg].manifest == manifest_path).then(|| self[pkg].manifest.clone())
449 .collect::<Vec<ManifestPath>>();
451 // some packages has this pkg as dep. return their manifests
452 if parent_manifests.len() > 0 {
453 return Some(parent_manifests);
456 // this pkg is inside this cargo workspace, fallback to workspace root
459 ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
463 // not in this workspace
467 fn is_unique(&self, name: &str) -> bool {
468 self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
472 fn rustc_discover_host_triple(
473 cargo_toml: &ManifestPath,
474 extra_env: &FxHashMap<String, String>,
475 ) -> Option<String> {
476 let mut rustc = Command::new(toolchain::rustc());
477 rustc.envs(extra_env);
478 rustc.current_dir(cargo_toml.parent()).arg("-vV");
479 tracing::debug!("Discovering host platform by {:?}", rustc);
480 match utf8_stdout(rustc) {
482 let field = "host: ";
483 let target = stdout.lines().find_map(|l| l.strip_prefix(field));
484 if let Some(target) = target {
485 Some(target.to_string())
487 // If we fail to resolve the host platform, it's not the end of the world.
488 tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
493 tracing::warn!("Failed to discover host platform: {}", e);
499 fn cargo_config_build_target(
500 cargo_toml: &ManifestPath,
501 extra_env: &FxHashMap<String, String>,
502 ) -> Option<String> {
503 let mut cargo_config = Command::new(toolchain::cargo());
504 cargo_config.envs(extra_env);
506 .current_dir(cargo_toml.parent())
507 .args(&["-Z", "unstable-options", "config", "get", "build.target"])
508 .env("RUSTC_BOOTSTRAP", "1");
509 // if successful we receive `build.target = "target-triple"`
510 tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
511 match utf8_stdout(cargo_config) {
513 .strip_prefix("build.target = \"")
514 .and_then(|stdout| stdout.strip_suffix('"'))
515 .map(ToOwned::to_owned),