rust-analyzer/crates/project_model/src/cargo_workspace.rs

375 lines
13 KiB
Rust
Raw Normal View History

//! FIXME: write short doc here
use std::{
ffi::OsStr,
ops,
path::{Path, PathBuf},
process::Command,
};
2019-01-10 19:21:14 +00:00
use anyhow::{Context, Result};
2020-08-12 14:22:05 +00:00
use arena::{Arena, Idx};
2020-08-13 14:25:38 +00:00
use base_db::Edition;
use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId};
use paths::{AbsPath, AbsPathBuf};
use rustc_hash::FxHashMap;
2019-01-10 19:21:14 +00:00
use crate::cfg_flag::CfgFlag;
/// `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.
///
/// 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,
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]
}
}
2020-07-02 14:06:00 +00:00
#[derive(Default, Clone, Debug, PartialEq, Eq)]
2020-04-01 16:51:16 +00:00
pub struct CargoConfig {
2019-12-13 10:16:34 +00:00
/// Do not activate the `default` feature.
pub no_default_features: bool,
/// Activate all available features
pub all_features: bool,
/// List of features to activate.
/// This will be ignored if `cargo_all_features` is true.
pub features: Vec<String>,
/// Runs cargo check on launch to figure out the correct values of OUT_DIR
pub load_out_dirs_from_check: bool,
2020-04-27 22:15:54 +00:00
/// rustc target
2020-05-05 16:01:54 +00:00
pub target: Option<String>,
2020-11-13 16:38:26 +00:00
/// Don't load sysroot crates (`std`, `core` & friends). Might be useful
/// when debugging isolated issues.
pub no_sysroot: bool,
/// rustc private crate source
pub rustc_source: Option<AbsPathBuf>,
2019-12-13 10:16:34 +00:00
}
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
#[derive(Debug, Clone, Eq, PartialEq)]
2020-03-19 16:53:31 +00:00
pub struct PackageData {
pub version: String,
2020-03-19 16:53:31 +00:00
pub name: String,
pub manifest: AbsPathBuf,
2020-03-19 16:53:31 +00:00
pub targets: Vec<Target>,
pub is_member: bool,
pub dependencies: Vec<PackageDependency>,
pub edition: Edition,
pub features: Vec<String>,
pub cfgs: Vec<CfgFlag>,
pub out_dir: Option<AbsPathBuf>,
pub proc_macro_dylib_path: Option<AbsPathBuf>,
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,
2019-01-10 19:21:14 +00:00
}
#[derive(Debug, Clone, Eq, PartialEq)]
2020-03-19 16:53:31 +00:00
pub struct TargetData {
pub package: Package,
pub name: String,
pub root: AbsPathBuf,
2020-03-19 16:53:31 +00:00
pub kind: TargetKind,
pub is_proc_macro: bool,
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,
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,
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
}
}
2020-03-19 16:53:31 +00:00
impl PackageData {
pub fn root(&self) -> &AbsPath {
2020-03-19 16:53:31 +00:00
self.manifest.parent().unwrap()
2019-11-24 10:33:12 +00:00
}
2019-01-10 19:21:14 +00:00
}
impl CargoWorkspace {
2019-12-13 10:16:34 +00:00
pub fn from_cargo_metadata(
2020-07-05 09:15:35 +00:00
cargo_toml: &AbsPath,
2020-11-13 16:38:26 +00:00
config: &CargoConfig,
2019-12-13 10:16:34 +00:00
) -> Result<CargoWorkspace> {
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());
2020-11-13 16:38:26 +00:00
if config.all_features {
2019-12-13 10:16:34 +00:00
meta.features(CargoOpt::AllFeatures);
} else {
2020-11-13 16:38:26 +00:00
if config.no_default_features {
// FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
// https://github.com/oli-obk/cargo_metadata/issues/79
meta.features(CargoOpt::NoDefaultFeatures);
}
2020-11-13 16:38:26 +00:00
if !config.features.is_empty() {
meta.features(CargoOpt::SomeFeatures(config.features.clone()));
}
2019-12-13 10:16:34 +00:00
}
if let Some(parent) = cargo_toml.parent() {
2020-07-05 09:15:35 +00:00
meta.current_dir(parent.to_path_buf());
}
2020-11-13 16:38:26 +00:00
if let Some(target) = config.target.as_ref() {
2020-05-09 22:22:26 +00:00
meta.other_options(vec![String::from("--filter-platform"), target.clone()]);
}
let mut meta = meta.exec().with_context(|| {
format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display())
})?;
let mut out_dir_by_id = FxHashMap::default();
2020-05-04 11:29:09 +00:00
let mut cfgs = FxHashMap::default();
2020-03-18 12:56:46 +00:00
let mut proc_macro_dylib_paths = FxHashMap::default();
2020-11-13 16:38:26 +00:00
if config.load_out_dirs_from_check {
let resources = load_extern_resources(cargo_toml, config)?;
2020-03-18 12:56:46 +00:00
out_dir_by_id = resources.out_dirs;
2020-05-04 11:29:09 +00:00
cfgs = resources.cfgs;
2020-03-18 12:56:46 +00:00
proc_macro_dylib_paths = resources.proc_dylib_paths;
}
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));
2019-01-10 19:21:14 +00:00
for meta_pkg in meta.packages {
let cargo_metadata::Package { id, edition, name, manifest_path, version, .. } =
meta_pkg;
let is_member = ws_members.contains(&id);
let edition = edition
.parse::<Edition>()
.with_context(|| format!("Failed to parse edition {}", edition))?;
2019-01-10 19:21:14 +00:00
let pkg = packages.alloc(PackageData {
name,
version: version.to_string(),
manifest: AbsPathBuf::assert(manifest_path),
2019-01-10 19:21:14 +00:00
targets: Vec::new(),
is_member,
edition,
2019-01-10 19:21:14 +00:00
dependencies: Vec::new(),
2019-10-02 18:02:53 +00:00
features: Vec::new(),
2020-05-04 11:29:09 +00:00
cfgs: cfgs.get(&id).cloned().unwrap_or_default(),
out_dir: out_dir_by_id.get(&id).cloned(),
2020-03-18 12:56:46 +00:00
proc_macro_dylib_path: proc_macro_dylib_paths.get(&id).cloned(),
2019-01-10 19:21:14 +00:00
});
let pkg_data = &mut packages[pkg];
pkg_by_id.insert(id, pkg);
2019-01-10 19:21:14 +00:00
for meta_tgt in meta_pkg.targets {
2020-02-18 13:32:19 +00:00
let is_proc_macro = meta_tgt.kind.as_slice() == ["proc-macro"];
2019-01-10 19:21:14 +00:00
let tgt = targets.alloc(TargetData {
2020-03-19 16:53:31 +00:00
package: pkg,
2019-06-03 14:21:08 +00:00
name: meta_tgt.name,
root: AbsPathBuf::assert(meta_tgt.src_path.clone()),
2019-01-10 19:21:14 +00:00
kind: TargetKind::new(meta_tgt.kind.as_slice()),
2019-11-24 10:33:12 +00:00
is_proc_macro,
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 {
2020-01-28 09:08:17 +00:00
let source = match pkg_by_id.get(&node.id) {
Some(&src) => src,
2020-01-30 17:01:38 +00:00
// FIXME: replace this and a similar branch below with `.unwrap`, once
// https://github.com/rust-lang/cargo/issues/7841
// is fixed and hits stable (around 1.43-is probably?).
2020-01-28 09:08:17 +00:00
None => {
log::error!("Node id do not match in cargo metadata, ignoring {}", node.id);
continue;
}
};
node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
2019-01-10 19:21:14 +00:00
for dep_node in node.deps {
2020-01-28 09:08:17 +00:00
let pkg = match pkg_by_id.get(&dep_node.pkg) {
Some(&pkg) => pkg,
None => {
log::error!(
"Dep node id do not match in cargo metadata, ignoring {}",
dep_node.pkg
);
continue;
}
};
let dep = PackageDependency { name: dep_node.name, pkg };
2019-01-10 19:21:14 +00:00
packages[source].dependencies.push(dep);
}
2019-10-02 18:02:53 +00:00
packages[source].features.extend(node.features);
2019-01-10 19:21:14 +00:00
}
let workspace_root = AbsPathBuf::assert(meta.workspace_root);
Ok(CargoWorkspace { packages, targets, workspace_root: workspace_root })
2019-01-10 19:21:14 +00:00
}
2019-08-06 08:54:51 +00:00
pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
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_map(|pkg| self[pkg].targets.iter().find(|&&it| &self[it].root == root))
2020-03-19 16:53:31 +00:00
.next()
.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 package_flag(&self, package: &PackageData) -> String {
if self.is_unique(&*package.name) {
package.name.clone()
} else {
format!("{}:{}", package.name, package.version)
}
}
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
}
2020-03-18 12:56:46 +00:00
#[derive(Debug, Clone, Default)]
2020-11-02 15:31:38 +00:00
pub(crate) struct ExternResources {
out_dirs: FxHashMap<PackageId, AbsPathBuf>,
proc_dylib_paths: FxHashMap<PackageId, AbsPathBuf>,
cfgs: FxHashMap<PackageId, Vec<CfgFlag>>,
2020-03-18 12:56:46 +00:00
}
2020-11-02 15:31:38 +00:00
pub(crate) fn load_extern_resources(
2020-03-31 16:43:22 +00:00
cargo_toml: &Path,
2020-04-01 16:51:16 +00:00
cargo_features: &CargoConfig,
2020-03-31 16:43:22 +00:00
) -> Result<ExternResources> {
2020-08-12 14:52:28 +00:00
let mut cmd = Command::new(toolchain::cargo());
2020-03-31 16:43:22 +00:00
cmd.args(&["check", "--message-format=json", "--manifest-path"]).arg(cargo_toml);
if let Some(target) = &cargo_features.target {
cmd.args(&["--target", target]);
}
if cargo_features.all_features {
2020-03-31 16:43:22 +00:00
cmd.arg("--all-features");
} else {
if cargo_features.no_default_features {
// FIXME: `NoDefaultFeatures` is mutual exclusive with `SomeFeatures`
// https://github.com/oli-obk/cargo_metadata/issues/79
cmd.arg("--no-default-features");
}
if !cargo_features.features.is_empty() {
cmd.arg("--features");
cmd.arg(cargo_features.features.join(" "));
}
}
2020-03-31 16:43:22 +00:00
let output = cmd.output()?;
let mut res = ExternResources::default();
2020-05-09 22:22:26 +00:00
for message in cargo_metadata::Message::parse_stream(output.stdout.as_slice()) {
2020-04-01 16:51:16 +00:00
if let Ok(message) = message {
2020-03-31 16:43:22 +00:00
match message {
2020-05-04 11:29:09 +00:00
Message::BuildScriptExecuted(BuildScript { package_id, out_dir, cfgs, .. }) => {
let cfgs = {
let mut acc = Vec::new();
for cfg in cfgs {
match cfg.parse::<CfgFlag>() {
Ok(it) => acc.push(it),
Err(err) => {
anyhow::bail!("invalid cfg from cargo-metadata: {}", err)
}
};
}
acc
};
// cargo_metadata crate returns default (empty) path for
// older cargos, which is not absolute, so work around that.
if out_dir != PathBuf::default() {
let out_dir = AbsPathBuf::assert(out_dir);
res.out_dirs.insert(package_id.clone(), out_dir);
res.cfgs.insert(package_id, cfgs);
}
2020-03-31 16:43:22 +00:00
}
Message::CompilerArtifact(message) => {
if message.target.kind.contains(&"proc-macro".to_string()) {
let package_id = message.package_id;
// Skip rmeta file
2020-04-19 19:15:49 +00:00
if let Some(filename) = message.filenames.iter().find(|name| is_dylib(name))
2020-03-31 16:43:22 +00:00
{
let filename = AbsPathBuf::assert(filename.clone());
res.proc_dylib_paths.insert(package_id, filename);
2020-03-31 16:43:22 +00:00
}
2020-03-18 12:56:46 +00:00
}
}
2020-03-31 16:43:22 +00:00
Message::CompilerMessage(_) => (),
Message::Unknown => (),
2020-05-09 22:22:26 +00:00
Message::BuildFinished(_) => {}
Message::TextLine(_) => {}
2020-03-18 12:56:46 +00:00
}
}
}
2020-03-31 16:43:22 +00:00
Ok(res)
}
2020-03-26 20:26:34 +00:00
// FIXME: File a better way to know if it is a dylib
fn is_dylib(path: &Path) -> bool {
2020-03-27 04:15:38 +00:00
match path.extension().and_then(OsStr::to_str).map(|it| it.to_string().to_lowercase()) {
None => false,
Some(ext) => matches!(ext.as_str(), "dll" | "dylib" | "so"),
2020-03-26 20:26:34 +00:00
}
}