-//! FIXME: write short doc here
+//! See [`CargoWorkspace`].
+use std::convert::TryInto;
+use std::iter;
use std::path::PathBuf;
-use std::{convert::TryInto, ops, process::Command, sync::Arc};
+use std::{ops, process::Command};
use anyhow::{Context, Result};
use base_db::Edition;
use la_arena::{Arena, Idx};
use paths::{AbsPath, AbsPathBuf};
use rustc_hash::FxHashMap;
+use serde::Deserialize;
+use serde_json::from_value;
-use crate::build_data::BuildDataConfig;
-use crate::utf8_stdout;
+use crate::CfgOverrides;
+use crate::{utf8_stdout, ManifestPath};
-/// `CargoWorkspace` represents the logical structure of, well, a Cargo
+/// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
/// workspace. It pretty closely mirrors `cargo metadata` output.
///
/// Note that internally, rust analyzer uses a different structure:
packages: Arena<PackageData>,
targets: Arena<TargetData>,
workspace_root: AbsPathBuf,
- build_data_config: BuildDataConfig,
}
impl ops::Index<Package> for CargoWorkspace {
/// rustc private crate source
pub rustc_source: Option<RustcSource>,
+
+ /// crates to disable `#[cfg(test)]` on
+ pub unset_test_crates: Vec<String>,
+
+ pub wrap_rustc_in_build_scripts: bool,
+}
+
+impl CargoConfig {
+ pub fn cfg_overrides(&self) -> CfgOverrides {
+ self.unset_test_crates
+ .iter()
+ .cloned()
+ .zip(iter::repeat_with(|| {
+ cfg::CfgDiff::new(Vec::new(), vec![cfg::CfgAtom::Flag("test".into())]).unwrap()
+ }))
+ .collect()
+ }
}
pub type Package = Idx<PackageData>;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageData {
/// Version given in the `Cargo.toml`
- pub version: String,
+ pub version: semver::Version,
/// Name as given in the `Cargo.toml`
pub name: String,
/// Path containing the `Cargo.toml`
- pub manifest: AbsPathBuf,
+ pub manifest: ManifestPath,
/// Targets provided by the crate (lib, bin, example, test, ...)
pub targets: Vec<Target>,
/// Is this package a member of the current workspace
pub active_features: Vec<String>,
// String representation of package id
pub id: String,
+ // The contents of [package.metadata.rust-analyzer]
+ pub metadata: RustAnalyzerPackageMetaData,
+}
+
+#[derive(Deserialize, Default, Debug, Clone, Eq, PartialEq)]
+pub struct RustAnalyzerPackageMetaData {
+ pub rustc_private: bool,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageDependency {
pub pkg: Package,
pub name: String,
+ pub kind: DepKind,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord)]
+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 = Vec::new();
+ if list.is_empty() {
+ dep_kinds.push(Self::Normal);
+ }
+ for info in list {
+ let kind = match info.kind {
+ cargo_metadata::DependencyKind::Normal => Self::Normal,
+ cargo_metadata::DependencyKind::Development => Self::Dev,
+ cargo_metadata::DependencyKind::Build => Self::Build,
+ cargo_metadata::DependencyKind::Unknown => continue,
+ };
+ dep_kinds.push(kind);
+ }
+ dep_kinds.sort_unstable();
+ dep_kinds.dedup();
+ dep_kinds.into_iter()
+ }
}
/// Information associated with a package's target
Example,
Test,
Bench,
+ BuildScript,
Other,
}
"test" => TargetKind::Test,
"bench" => TargetKind::Bench,
"example" => TargetKind::Example,
+ "custom-build" => TargetKind::BuildScript,
"proc-macro" => TargetKind::Lib,
_ if kind.contains("lib") => TargetKind::Lib,
_ => continue,
}
}
-impl PackageData {
- pub fn root(&self) -> &AbsPath {
- self.manifest.parent().unwrap()
- }
+#[derive(Deserialize, Default)]
+// Deserialise helper for the cargo metadata
+struct PackageMetadata {
+ #[serde(rename = "rust-analyzer")]
+ rust_analyzer: Option<RustAnalyzerPackageMetaData>,
}
impl CargoWorkspace {
- pub fn from_cargo_metadata(
- cargo_toml: &AbsPath,
+ pub fn fetch_metadata(
+ cargo_toml: &ManifestPath,
config: &CargoConfig,
progress: &dyn Fn(String),
- ) -> Result<CargoWorkspace> {
+ ) -> Result<cargo_metadata::Metadata> {
+ let target = config
+ .target
+ .clone()
+ .or_else(|| cargo_config_build_target(cargo_toml))
+ .or_else(|| rustc_discover_host_triple(cargo_toml));
+
let mut meta = MetadataCommand::new();
meta.cargo_path(toolchain::cargo());
meta.manifest_path(cargo_toml.to_path_buf());
meta.features(CargoOpt::SomeFeatures(config.features.clone()));
}
}
- if let Some(parent) = cargo_toml.parent() {
- meta.current_dir(parent.to_path_buf());
- }
- let target = if let Some(target) = config.target.as_ref() {
- Some(target.clone())
- } else {
- // cargo metadata defaults to giving information for _all_ targets.
- // In the absence of a preference from the user, we use the host platform.
- let mut rustc = Command::new(toolchain::rustc());
- rustc.current_dir(cargo_toml.parent().unwrap()).arg("-vV");
- log::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.
- log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
- None
- }
- }
- Err(e) => {
- log::warn!("Failed to discover host platform: {}", e);
- None
- }
- }
- };
+ meta.current_dir(cargo_toml.parent().as_os_str());
+
if let Some(target) = target {
meta.other_options(vec![String::from("--filter-platform"), target]);
}
- // FIXME: Currently MetadataCommand is not based on parse_stream,
- // So we just report it as a whole
+ // 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());
- let mut meta = meta.exec().with_context(|| {
- let cwd: Option<AbsPathBuf> =
- std::env::current_dir().ok().and_then(|p| p.try_into().ok());
-
- let workdir = cargo_toml
- .parent()
- .map(|p| p.to_path_buf())
- .or(cwd)
- .map(|dir| dir.to_string_lossy().to_string())
- .unwrap_or_else(|| "<failed to get path>".into());
-
- format!(
- "Failed to run `cargo metadata --manifest-path {}` in `{}`",
- cargo_toml.display(),
- workdir
- )
+
+ let meta = meta.exec().with_context(|| {
+ format!("Failed to run `cargo metadata --manifest-path {}`", cargo_toml.display(),)
})?;
+ Ok(meta)
+ }
+
+ pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
let mut pkg_by_id = FxHashMap::default();
let mut packages = Arena::default();
let mut targets = Arena::default();
meta.packages.sort_by(|a, b| a.id.cmp(&b.id));
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))?;
+ let cargo_metadata::Package {
+ id, edition, name, manifest_path, version, metadata, ..
+ } = meta_pkg;
+ let meta = from_value::<PackageMetadata>(metadata.clone()).unwrap_or_default();
+ let is_member = ws_members.contains(id);
+ let edition = edition.parse::<Edition>().unwrap_or_else(|err| {
+ log::error!("Failed to parse edition {}", err);
+ Edition::CURRENT
+ });
let pkg = packages.alloc(PackageData {
id: id.repr.clone(),
name: name.clone(),
- version: version.to_string(),
- manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)),
+ version: version.clone(),
+ manifest: AbsPathBuf::assert(PathBuf::from(&manifest_path)).try_into().unwrap(),
targets: Vec::new(),
is_member,
edition,
dependencies: Vec::new(),
features: meta_pkg.features.clone().into_iter().collect(),
active_features: Vec::new(),
+ metadata: meta.rust_analyzer.unwrap_or_default(),
});
let pkg_data = &mut packages[pkg];
pkg_by_id.insert(id, pkg);
}
};
node.deps.sort_by(|a, b| a.pkg.cmp(&b.pkg));
- for dep_node in node.deps {
+ for (dep_node, kind) in node
+ .deps
+ .iter()
+ .flat_map(|dep| DepKind::iter(&dep.dep_kinds).map(move |kind| (dep, kind)))
+ {
let pkg = match pkg_by_id.get(&dep_node.pkg) {
Some(&pkg) => pkg,
None => {
continue;
}
};
- let dep = PackageDependency { name: dep_node.name, pkg };
+ let dep = PackageDependency { name: dep_node.name.clone(), pkg, kind };
packages[source].dependencies.push(dep);
}
packages[source].active_features.extend(node.features);
let workspace_root =
AbsPathBuf::assert(PathBuf::from(meta.workspace_root.into_os_string()));
- let build_data_config = BuildDataConfig::new(
- cargo_toml.to_path_buf(),
- config.clone(),
- Arc::new(meta.packages.clone()),
- );
- Ok(CargoWorkspace { packages, targets, workspace_root, build_data_config })
+ CargoWorkspace { packages, targets, workspace_root }
+ }
+
+ pub fn from_cargo_metadata3(
+ cargo_toml: &ManifestPath,
+ config: &CargoConfig,
+ progress: &dyn Fn(String),
+ ) -> Result<CargoWorkspace> {
+ let meta = CargoWorkspace::fetch_metadata(cargo_toml, config, progress)?;
+ Ok(CargoWorkspace::new(meta))
}
pub fn packages<'a>(&'a self) -> impl Iterator<Item = Package> + ExactSizeIterator + 'a {
}
}
- pub(crate) fn build_data_config(&self) -> &BuildDataConfig {
- &self.build_data_config
- }
-
fn is_unique(&self, name: &str) -> bool {
self.packages.iter().filter(|(_, v)| v.name == name).count() == 1
}
}
+
+fn rustc_discover_host_triple(cargo_toml: &ManifestPath) -> Option<String> {
+ let mut rustc = Command::new(toolchain::rustc());
+ rustc.current_dir(cargo_toml.parent()).arg("-vV");
+ log::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.
+ log::info!("rustc -vV did not report host platform, got:\n{}", stdout);
+ None
+ }
+ }
+ Err(e) => {
+ log::warn!("Failed to discover host platform: {}", e);
+ None
+ }
+ }
+}
+
+fn cargo_config_build_target(cargo_toml: &ManifestPath) -> Option<String> {
+ let mut cargo_config = Command::new(toolchain::cargo());
+ cargo_config
+ .current_dir(cargo_toml.parent())
+ .args(&["-Z", "unstable-options", "config", "get", "build.target"])
+ .env("RUSTC_BOOTSTRAP", "1");
+ // if successful we receive `build.target = "target-triple"`
+ log::debug!("Discovering cargo config target by {:?}", cargo_config);
+ match utf8_stdout(cargo_config) {
+ Ok(stdout) => stdout
+ .strip_prefix("build.target = \"")
+ .and_then(|stdout| stdout.strip_suffix('"'))
+ .map(ToOwned::to_owned),
+ Err(_) => None,
+ }
+}