rust-analyzer/crates/project-model/src/cargo_workspace.rs

545 lines
19 KiB
Rust
Raw Normal View History

2021-05-22 13:53:47 +00:00
//! See [`CargoWorkspace`].
2021-03-02 12:27:29 +00:00
use std::path::PathBuf;
2022-08-18 21:41:17 +00:00
use std::str::from_utf8;
use std::{ops, process::Command};
2019-01-10 19:21:14 +00:00
use anyhow::Context;
2020-08-13 14:25:38 +00:00
use base_db::Edition;
2021-01-22 11:11:01 +00:00
use cargo_metadata::{CargoOpt, MetadataCommand};
2021-01-14 15:47:42 +00:00
use la_arena::{Arena, Idx};
use paths::{AbsPath, AbsPathBuf};
use rustc_hash::{FxHashMap, FxHashSet};
use serde::Deserialize;
use serde_json::from_value;
2019-01-10 19:21:14 +00:00
2022-10-22 21:02:59 +00:00
use crate::{utf8_stdout, InvocationLocation, ManifestPath};
use crate::{CfgOverrides, InvocationStrategy};
2021-05-22 13:53:47 +00:00
/// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
2019-01-10 19:21:14 +00:00
/// workspace. It pretty closely mirrors `cargo metadata` output.
///
2022-08-01 11:47:09 +00:00
/// Note that internally, rust-analyzer uses a different structure:
2019-01-10 19:21:14 +00:00
/// `CrateGraph`. `CrateGraph` is lower-level: it knows only about the crates,
2019-02-11 16:18:27 +00:00
/// while this knows about `Packages` & `Targets`: purely cargo-related
2019-01-10 19:21:14 +00:00
/// concepts.
///
/// We use absolute paths here, `cargo metadata` guarantees to always produce
/// abs paths.
#[derive(Debug, Clone, Eq, PartialEq)]
2019-01-10 19:21:14 +00:00
pub struct CargoWorkspace {
2020-03-19 15:00:11 +00:00
packages: Arena<PackageData>,
targets: Arena<TargetData>,
workspace_root: AbsPathBuf,
target_directory: AbsPathBuf,
2019-01-10 19:21:14 +00:00
}
2020-03-19 16:53:31 +00:00
impl ops::Index<Package> for CargoWorkspace {
type Output = PackageData;
fn index(&self, index: Package) -> &PackageData {
&self.packages[index]
}
}
impl ops::Index<Target> for CargoWorkspace {
type Output = TargetData;
fn index(&self, index: Target) -> &TargetData {
&self.targets[index]
}
}
/// Describes how to set the rustc source directory.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RustLibSource {
/// Explicit path for the rustc source directory.
Path(AbsPathBuf),
/// Try to automatically detect where the rustc source directory is.
Discover,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CargoFeatures {
All,
Selected {
/// List of features to activate.
features: Vec<String>,
/// Do not activate the `default` feature.
no_default_features: bool,
},
}
2019-12-13 10:16:34 +00:00
impl Default for CargoFeatures {
fn default() -> Self {
CargoFeatures::Selected { features: vec![], no_default_features: false }
}
}
2019-12-13 10:16:34 +00:00
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct CargoConfig {
2019-12-13 10:16:34 +00:00
/// List of features to activate.
pub features: CargoFeatures,
2020-04-27 22:15:54 +00:00
/// rustc target
2020-05-05 16:01:54 +00:00
pub target: Option<String>,
2022-10-01 18:47:31 +00:00
/// Sysroot loading behavior
pub sysroot: Option<RustLibSource>,
pub sysroot_src: Option<AbsPathBuf>,
/// rustc private crate source
pub rustc_source: Option<RustLibSource>,
2023-05-26 20:12:22 +00:00
pub cfg_overrides: CfgOverrides,
/// Invoke `cargo check` through the RUSTC_WRAPPER.
pub wrap_rustc_in_build_scripts: bool,
/// The command to run instead of `cargo check` for building build scripts.
pub run_build_script_command: Option<Vec<String>>,
/// Extra args to pass to the cargo command.
pub extra_args: Vec<String>,
/// Extra env vars to set when invoking the cargo command
2022-08-18 21:41:17 +00:00
pub extra_env: FxHashMap<String, String>,
pub invocation_strategy: InvocationStrategy,
2022-10-22 21:02:59 +00:00
pub invocation_location: InvocationLocation,
/// Optional path to use instead of `target` when building
pub target_dir: Option<PathBuf>,
}
2020-03-19 15:00:11 +00:00
pub type Package = Idx<PackageData>;
2019-01-10 19:21:14 +00:00
2020-03-19 15:00:11 +00:00
pub type Target = Idx<TargetData>;
2019-01-10 19:21:14 +00:00
/// Information associated with a cargo crate
#[derive(Debug, Clone, Eq, PartialEq)]
2020-03-19 16:53:31 +00:00
pub struct PackageData {
/// Version given in the `Cargo.toml`
pub version: semver::Version,
/// Name as given in the `Cargo.toml`
2020-03-19 16:53:31 +00:00
pub name: String,
2021-11-22 17:44:46 +00:00
/// Repository as given in the `Cargo.toml`
pub repository: Option<String>,
/// Path containing the `Cargo.toml`
pub manifest: ManifestPath,
/// Targets provided by the crate (lib, bin, example, test, ...)
2020-03-19 16:53:31 +00:00
pub targets: Vec<Target>,
2021-09-07 15:29:58 +00:00
/// Does this package come from the local filesystem (and is editable)?
pub is_local: bool,
/// Whether this package is a member of the workspace
pub is_member: bool,
/// List of packages this package depends on
2020-03-19 16:53:31 +00:00
pub dependencies: Vec<PackageDependency>,
/// Rust edition for this package
2020-03-19 16:53:31 +00:00
pub edition: Edition,
2021-01-21 11:12:19 +00:00
/// Features provided by the crate, mapped to the features required by that feature.
pub features: FxHashMap<String, Vec<String>>,
/// List of features enabled on this package
pub active_features: Vec<String>,
2021-11-22 17:44:46 +00:00
/// String representation of package id
2021-01-28 15:33:02 +00:00
pub id: String,
2021-11-22 17:44:46 +00:00
/// The contents of [package.metadata.rust-analyzer]
pub metadata: RustAnalyzerPackageMetaData,
}
#[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
pub struct RustAnalyzerPackageMetaData {
pub rustc_private: bool,
2019-01-10 19:21:14 +00:00
}
#[derive(Debug, Clone, Eq, PartialEq)]
2019-01-10 19:21:14 +00:00
pub struct PackageDependency {
pub pkg: Package,
2019-02-09 09:51:06 +00:00
pub name: String,
2021-05-12 12:16:51 +00:00
pub kind: DepKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2021-05-12 12:16:51 +00:00
pub enum DepKind {
/// Available to the library, binary, and dev targets in the package (but not the build script).
Normal,
/// Available only to test and bench targets (and the library target, when built with `cfg(test)`).
Dev,
/// Available only to the build script target.
Build,
}
impl DepKind {
fn iter(list: &[cargo_metadata::DepKindInfo]) -> impl Iterator<Item = Self> {
let mut dep_kinds = [None; 3];
if list.is_empty() {
dep_kinds[0] = Some(Self::Normal);
}
2021-05-12 12:16:51 +00:00
for info in list {
match info.kind {
cargo_metadata::DependencyKind::Normal => dep_kinds[0] = Some(Self::Normal),
cargo_metadata::DependencyKind::Development => dep_kinds[1] = Some(Self::Dev),
cargo_metadata::DependencyKind::Build => dep_kinds[2] = Some(Self::Build),
2021-05-12 12:16:51 +00:00
cargo_metadata::DependencyKind::Unknown => continue,
}
2021-05-12 12:16:51 +00:00
}
dep_kinds.into_iter().flatten()
2021-05-12 12:16:51 +00:00
}
2019-01-10 19:21:14 +00:00
}
/// Information associated with a package's target
#[derive(Debug, Clone, Eq, PartialEq)]
2020-03-19 16:53:31 +00:00
pub struct TargetData {
/// Package that provided this target
2020-03-19 16:53:31 +00:00
pub package: Package,
/// Name as given in the `Cargo.toml` or generated from the file name
2020-03-19 16:53:31 +00:00
pub name: String,
/// Path to the main source file of the target
pub root: AbsPathBuf,
/// Kind of target
2020-03-19 16:53:31 +00:00
pub kind: TargetKind,
/// Is this target a proc-macro
2020-03-19 16:53:31 +00:00
pub is_proc_macro: bool,
/// Required features of the target without which it won't build
pub required_features: Vec<String>,
2019-01-10 19:21:14 +00:00
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetKind {
Bin,
2019-11-24 10:33:12 +00:00
/// Any kind of Cargo lib crate-type (dylib, rlib, proc-macro, ...).
2019-01-10 19:21:14 +00:00
Lib,
Example,
Test,
Bench,
2021-05-12 12:16:51 +00:00
BuildScript,
2019-01-10 19:21:14 +00:00
Other,
}
impl TargetKind {
fn new(kinds: &[String]) -> TargetKind {
for kind in kinds {
return match kind.as_str() {
"bin" => TargetKind::Bin,
"test" => TargetKind::Test,
"bench" => TargetKind::Bench,
"example" => TargetKind::Example,
2021-05-12 12:16:51 +00:00
"custom-build" => TargetKind::BuildScript,
2019-11-24 10:33:12 +00:00
"proc-macro" => TargetKind::Lib,
2019-01-10 19:21:14 +00:00
_ if kind.contains("lib") => TargetKind::Lib,
_ => continue,
};
}
TargetKind::Other
}
}
// Deserialize helper for the cargo metadata
#[derive(Deserialize, Default)]
struct PackageMetadata {
#[serde(rename = "rust-analyzer")]
rust_analyzer: Option<RustAnalyzerPackageMetaData>,
}
2019-01-10 19:21:14 +00:00
impl CargoWorkspace {
pub fn fetch_metadata(
cargo_toml: &ManifestPath,
current_dir: &AbsPath,
2020-11-13 16:38:26 +00:00
config: &CargoConfig,
progress: &dyn Fn(String),
) -> anyhow::Result<cargo_metadata::Metadata> {
let targets = find_list_of_build_targets(config, cargo_toml);
2021-07-19 18:21:41 +00:00
let mut meta = MetadataCommand::new();
2020-08-12 14:52:28 +00:00
meta.cargo_path(toolchain::cargo());
2020-07-05 09:15:35 +00:00
meta.manifest_path(cargo_toml.to_path_buf());
match &config.features {
CargoFeatures::All => {
meta.features(CargoOpt::AllFeatures);
}
CargoFeatures::Selected { features, no_default_features } => {
if *no_default_features {
meta.features(CargoOpt::NoDefaultFeatures);
}
if !features.is_empty() {
meta.features(CargoOpt::SomeFeatures(features.clone()));
}
}
2019-12-13 10:16:34 +00:00
}
meta.current_dir(current_dir.as_os_str());
2021-07-19 18:21:41 +00:00
let mut other_options = vec![];
// cargo metadata only supports a subset of flags of what cargo usually accepts, and usually
// the only relevant flags for metadata here are unstable ones, so we pass those along
// but nothing else
let mut extra_args = config.extra_args.iter();
while let Some(arg) = extra_args.next() {
if arg == "-Z" {
if let Some(arg) = extra_args.next() {
other_options.push("-Z".to_owned());
other_options.push(arg.to_owned());
}
}
}
if !targets.is_empty() {
2023-04-24 08:13:29 +00:00
other_options.append(
&mut targets
.into_iter()
.flat_map(|target| ["--filter-platform".to_owned().to_string(), target])
2023-04-24 08:13:29 +00:00
.collect(),
);
}
2023-04-24 08:13:29 +00:00
meta.other_options(other_options);
// FIXME: Fetching metadata is a slow process, as it might require
// calling crates.io. We should be reporting progress here, but it's
// unclear whether cargo itself supports it.
progress("metadata".to_string());
2022-09-19 15:31:08 +00:00
(|| -> Result<cargo_metadata::Metadata, cargo_metadata::Error> {
let mut command = meta.cargo_command();
command.envs(&config.extra_env);
2022-08-18 21:41:17 +00:00
let output = command.output()?;
if !output.status.success() {
return Err(cargo_metadata::Error::CargoMetadata {
stderr: String::from_utf8(output.stderr)?,
});
}
let stdout = from_utf8(&output.stdout)?
.lines()
.find(|line| line.starts_with('{'))
.ok_or(cargo_metadata::Error::NoJson)?;
cargo_metadata::MetadataCommand::parse(stdout)
2022-09-19 15:31:08 +00:00
})()
.with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))
}
pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
2019-01-10 19:21:14 +00:00
let mut pkg_by_id = FxHashMap::default();
let mut packages = Arena::default();
let mut targets = Arena::default();
let ws_members = &meta.workspace_members;
meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
2022-10-19 19:17:11 +00:00
for meta_pkg in meta.packages {
let cargo_metadata::Package {
2021-11-22 17:44:46 +00:00
name,
version,
2022-10-19 19:17:11 +00:00
id,
source,
targets: meta_targets,
features,
manifest_path,
2021-11-22 17:44:46 +00:00
repository,
2022-10-19 19:17:11 +00:00
edition,
metadata,
2021-11-22 17:44:46 +00:00
..
} = meta_pkg;
2022-10-19 19:17:11 +00:00
let meta = from_value::<PackageMetadata>(metadata).unwrap_or_default();
2022-07-03 07:08:10 +00:00
let edition = match edition {
cargo_metadata::Edition::E2015 => Edition::Edition2015,
cargo_metadata::Edition::E2018 => Edition::Edition2018,
cargo_metadata::Edition::E2021 => Edition::Edition2021,
_ => {
tracing::error!("Unsupported edition `{:?}`", edition);
Edition::CURRENT
}
};
// We treat packages without source as "local" packages. That includes all members of
// the current workspace, as well as any path dependency outside the workspace.
2022-10-19 19:17:11 +00:00
let is_local = source.is_none();
let is_member = ws_members.contains(&id);
2021-03-02 12:27:29 +00:00
2019-01-10 19:21:14 +00:00
let pkg = packages.alloc(PackageData {
2021-01-28 15:33:02 +00:00
id: id.repr.clone(),
2022-10-19 19:17:11 +00:00
name,
version,
manifest: AbsPathBuf::assert(manifest_path.into()).try_into().unwrap(),
2019-01-10 19:21:14 +00:00
targets: Vec::new(),
2021-09-07 15:29:58 +00:00
is_local,
is_member,
edition,
2022-10-19 19:17:11 +00:00
repository,
2019-01-10 19:21:14 +00:00
dependencies: Vec::new(),
2022-10-19 19:17:11 +00:00
features: features.into_iter().collect(),
2021-01-21 11:12:19 +00:00
active_features: Vec::new(),
metadata: meta.rust_analyzer.unwrap_or_default(),
2019-01-10 19:21:14 +00:00
});
let pkg_data = &mut packages[pkg];
pkg_by_id.insert(id, pkg);
2022-10-19 19:17:11 +00:00
for meta_tgt in meta_targets {
let cargo_metadata::Target { name, kind, required_features, src_path, .. } =
meta_tgt;
2019-01-10 19:21:14 +00:00
let tgt = targets.alloc(TargetData {
2020-03-19 16:53:31 +00:00
package: pkg,
2022-10-19 19:17:11 +00:00
name,
root: AbsPathBuf::assert(src_path.into()),
kind: TargetKind::new(&kind),
is_proc_macro: &*kind == ["proc-macro"],
required_features,
2019-01-10 19:21:14 +00:00
});
pkg_data.targets.push(tgt);
}
}
let resolve = meta.resolve.expect("metadata executed with deps");
for mut node in resolve.nodes {
2022-09-19 15:31:08 +00:00
let &source = pkg_by_id.get(&node.id).unwrap();
node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
2022-09-19 15:31:08 +00:00
let dependencies = node
.deps
.iter()
2022-09-19 15:31:08 +00:00
.flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)));
for (dep_node, kind) in dependencies {
let &pkg = pkg_by_id.get(&dep_node.pkg).unwrap();
let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
2019-01-10 19:21:14 +00:00
packages[source].dependencies.push(dep);
}
2021-01-21 11:12:19 +00:00
packages[source].active_features.extend(node.features);
2019-01-10 19:21:14 +00:00
}
2021-03-02 12:27:29 +00:00
let workspace_root =
AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
2021-01-28 15:33:02 +00:00
let target_directory =
AbsPathBuf::assert(PathBuf::from(meta.target_directory.into_os_string()));
CargoWorkspace { packages, targets, workspace_root, target_directory }
}
pub fn packages(&self) -> impl Iterator<Item = Package> + ExactSizeIterator + '_ {
2019-01-10 19:21:14 +00:00
self.packages.iter().map(|(id, _pkg)| id)
}
pub fn target_by_root(&self, root: &AbsPath) -> Option<Target> {
2020-03-19 16:53:31 +00:00
self.packages()
.filter(|&pkg| self[pkg].is_member)
.find_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
2020-03-19 16:53:31 +00:00
.copied()
2019-01-10 19:21:14 +00:00
}
2020-01-10 21:41:52 +00:00
2020-06-24 13:52:07 +00:00
pub fn workspace_root(&self) -> &AbsPath {
2020-01-10 21:41:52 +00:00
&self.workspace_root
}
pub fn target_directory(&self) -> &AbsPath {
&self.target_directory
}
pub fn package_flag(&self, package: &PackageData) -> String {
if self.is_unique(&package.name) {
package.name.clone()
} else {
format!("{}:{}", package.name, package.version)
}
}
2021-10-13 22:16:42 +00:00
pub fn parent_manifests(&self, manifest_path: &ManifestPath) -> Option<Vec<ManifestPath>> {
let mut found = false;
let parent_manifests = self
.packages()
.filter_map(|pkg| {
if !found && &self[pkg].manifest == manifest_path {
found = true
}
self[pkg].dependencies.iter().find_map(|dep| {
2022-09-19 15:31:08 +00:00
(&self[dep.pkg].manifest == manifest_path).then(|| self[pkg].manifest.clone())
2021-10-13 22:16:42 +00:00
})
})
.collect::<Vec<ManifestPath>>();
// some packages has this pkg as dep. return their manifests
if parent_manifests.len() > 0 {
return Some(parent_manifests);
}
// this pkg is inside this cargo workspace, fallback to workspace root
if found {
return Some(vec![
ManifestPath::try_from(self.workspace_root().join("Cargo.toml")).ok()?
]);
}
// not in this workspace
None
}
/// Returns the union of the features of all member crates in this workspace.
pub fn workspace_features(&self) -> FxHashSet<String> {
self.packages()
.filter_map(|package| {
let package = &self[package];
if package.is_member {
Some(package.features.keys().cloned())
} else {
None
}
})
.flatten()
.collect()
}
fn is_unique(&self, name: &str) -> bool {
self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
}
2019-01-10 19:21:14 +00:00
}
fn find_list_of_build_targets(config: &CargoConfig, cargo_toml: &ManifestPath) -> Vec<String> {
if let Some(target) = &config.target {
return [target.into()].to_vec();
}
let build_targets = cargo_config_build_target(cargo_toml, &config.extra_env);
if !build_targets.is_empty() {
return build_targets;
}
rustc_discover_host_triple(cargo_toml, &config.extra_env).into_iter().collect()
}
2022-09-19 15:31:08 +00:00
fn rustc_discover_host_triple(
cargo_toml: &ManifestPath,
extra_env: &FxHashMap<String, String>,
) -> Option<String> {
let mut rustc = Command::new(toolchain::rustc());
2022-09-19 15:31:08 +00:00
rustc.envs(extra_env);
rustc.current_dir(cargo_toml.parent()).arg("-vV");
2021-08-15 12:46:13 +00:00
tracing::debug!("Discovering host platform by {:?}", rustc);
match utf8_stdout(rustc) {
Ok(stdout) => {
let field = "host: ";
let target = stdout.lines().find_map(|l| l.strip_prefix(field));
if let Some(target) = target {
Some(target.to_string())
} else {
// If we fail to resolve the host platform, it's not the end of the world.
2021-08-15 12:46:13 +00:00
tracing::info!("rustc -vV did not report host platform, got:\n{}", stdout);
None
}
}
Err(e) => {
2021-08-15 12:46:13 +00:00
tracing::warn!("Failed to discover host platform: {}", e);
None
}
}
}
2022-09-19 15:31:08 +00:00
fn cargo_config_build_target(
cargo_toml: &ManifestPath,
extra_env: &FxHashMap<String, String>,
) -> Vec<String> {
let mut cargo_config = Command::new(toolchain::cargo());
2022-09-19 15:31:08 +00:00
cargo_config.envs(extra_env);
cargo_config
.current_dir(cargo_toml.parent())
2022-12-30 08:05:03 +00:00
.args(["-Z", "unstable-options", "config", "get", "build.target"])
.env("RUSTC_BOOTSTRAP", "1");
// if successful we receive `build.target = "target-triple"`
// or `build.target = ["<target 1>", ..]`
2021-08-15 12:46:13 +00:00
tracing::debug!("Discovering cargo config target by {:?}", cargo_config);
utf8_stdout(cargo_config).map(parse_output_cargo_config_build_target).unwrap_or_default()
}
fn parse_output_cargo_config_build_target(stdout: String) -> Vec<String> {
let trimmed = stdout.trim_start_matches("build.target = ").trim_matches('"');
if !trimmed.starts_with('[') {
return [trimmed.to_string()].to_vec();
}
let res = serde_json::from_str(trimmed);
if let Err(e) = &res {
tracing::warn!("Failed to parse `build.target` as an array of target: {}`", e);
}
res.unwrap_or_default()
}