Read default cfgs from rustc

This commit is contained in:
uHOOCCOOHu 2019-10-03 02:02:53 +08:00
parent e0100e63ae
commit 1067a1c5f6
No known key found for this signature in database
GPG key ID: CED392DE0C483D00
8 changed files with 76 additions and 14 deletions

1
Cargo.lock generated
View file

@ -1032,6 +1032,7 @@ dependencies = [
"lsp-server 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"lsp-types 0.61.0 (registry+https://github.com/rust-lang/crates.io-index)",
"parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
"ra_cfg 0.1.0",
"ra_db 0.1.0",
"ra_ide_api 0.1.0",
"ra_prof 0.1.0",

View file

@ -7,7 +7,7 @@ use rustc_hash::FxHashMap;
use crossbeam_channel::{unbounded, Receiver};
use ra_db::{CrateGraph, FileId, SourceRootId};
use ra_ide_api::{AnalysisChange, AnalysisHost, FeatureFlags};
use ra_project_model::{PackageRoot, ProjectWorkspace};
use ra_project_model::{get_rustc_cfg_options, PackageRoot, ProjectWorkspace};
use ra_vfs::{RootEntry, Vfs, VfsChange, VfsTask, Watch};
use ra_vfs_glob::RustPackageFilterBuilder;
@ -41,7 +41,13 @@ pub fn load_cargo(root: &Path) -> Result<(AnalysisHost, FxHashMap<SourceRootId,
sender,
Watch(false),
);
let (crate_graph, _crate_names) = ws.to_crate_graph(&mut |path: &Path| {
// FIXME: cfg options?
let default_cfg_options =
get_rustc_cfg_options().atom("test".into()).atom("debug_assertion".into());
let (crate_graph, _crate_names) =
ws.to_crate_graph(&default_cfg_options, &mut |path: &Path| {
let vfs_file = vfs.load(path);
log::debug!("vfs file {:?} -> {:?}", path, vfs_file);
vfs_file.map(vfs_file_to_id)

View file

@ -1,4 +1,6 @@
//! ra_cfg defines conditional compiling options, `cfg` attibute parser and evaluator
use std::iter::IntoIterator;
use ra_syntax::SmolStr;
use rustc_hash::FxHashSet;
@ -44,6 +46,14 @@ impl CfgOptions {
self
}
/// Shortcut to set features
pub fn features(mut self, iter: impl IntoIterator<Item = SmolStr>) -> CfgOptions {
for feat in iter {
self = self.key_value("feature".into(), feat);
}
self
}
pub fn remove_atom(mut self, name: &SmolStr) -> CfgOptions {
self.atoms.remove(name);
self

View file

@ -19,6 +19,7 @@ jod-thread = "0.1.0"
ra_vfs = "0.4.0"
ra_syntax = { path = "../ra_syntax" }
ra_db = { path = "../ra_db" }
ra_cfg = { path = "../ra_cfg" }
ra_text_edit = { path = "../ra_text_edit" }
ra_ide_api = { path = "../ra_ide_api" }
lsp-server = "0.2.0"

View file

@ -13,7 +13,7 @@ use ra_ide_api::{
Analysis, AnalysisChange, AnalysisHost, CrateGraph, FeatureFlags, FileId, LibraryData,
SourceRootId,
};
use ra_project_model::ProjectWorkspace;
use ra_project_model::{get_rustc_cfg_options, ProjectWorkspace};
use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsRoot, VfsTask, Watch};
use ra_vfs_glob::{Glob, RustPackageFilterBuilder};
use relative_path::RelativePathBuf;
@ -97,6 +97,10 @@ impl WorldState {
change.set_debug_root_path(SourceRootId(r.0), vfs_root_path.display().to_string());
}
// FIXME: Read default cfgs from config
let default_cfg_options =
get_rustc_cfg_options().atom("test".into()).atom("debug_assertion".into());
// Create crate graph from all the workspaces
let mut crate_graph = CrateGraph::default();
let mut load = |path: &std::path::Path| {
@ -104,7 +108,7 @@ impl WorldState {
vfs_file.map(|f| FileId(f.0))
};
for ws in workspaces.iter() {
let (graph, crate_names) = ws.to_crate_graph(&mut load);
let (graph, crate_names) = ws.to_crate_graph(&default_cfg_options, &mut load);
let shift = crate_graph.extend(graph);
for (crate_id, name) in crate_names {
change.set_debug_crate_name(crate_id.shift(shift), name)

View file

@ -39,6 +39,7 @@ struct PackageData {
is_member: bool,
dependencies: Vec<PackageDependency>,
edition: Edition,
features: Vec<String>,
}
#[derive(Debug, Clone)]
@ -91,6 +92,9 @@ impl Package {
pub fn edition(self, ws: &CargoWorkspace) -> Edition {
ws.packages[self].edition
}
pub fn features(self, ws: &CargoWorkspace) -> &[String] {
&ws.packages[self].features
}
pub fn targets<'a>(self, ws: &'a CargoWorkspace) -> impl Iterator<Item = Target> + 'a {
ws.packages[self].targets.iter().cloned()
}
@ -144,6 +148,7 @@ impl CargoWorkspace {
is_member,
edition: Edition::from_string(&meta_pkg.edition),
dependencies: Vec::new(),
features: Vec::new(),
});
let pkg_data = &mut packages[pkg];
pkg_by_id.insert(meta_pkg.id.clone(), pkg);
@ -164,6 +169,7 @@ impl CargoWorkspace {
let dep = PackageDependency { name: dep_node.name, pkg: pkg_by_id[&dep_node.pkg] };
packages[source].dependencies.push(dep);
}
packages[source].features.extend(node.features);
}
Ok(CargoWorkspace { packages, targets, workspace_root: meta.workspace_root })

View file

@ -19,6 +19,8 @@ pub struct Crate {
pub(crate) root_module: PathBuf,
pub(crate) edition: Edition,
pub(crate) deps: Vec<Dep>,
#[serde(default)]
pub(crate) features: Vec<String>,
}
#[derive(Clone, Copy, Debug, Deserialize)]

View file

@ -9,6 +9,7 @@ use std::{
fs::File,
io::BufReader,
path::{Path, PathBuf},
process::Command,
};
use ra_cfg::CfgOptions;
@ -118,6 +119,7 @@ impl ProjectWorkspace {
pub fn to_crate_graph(
&self,
default_cfg_options: &CfgOptions,
load: &mut dyn FnMut(&Path) -> Option<FileId>,
) -> (CrateGraph, FxHashMap<CrateId, String>) {
let mut crate_graph = CrateGraph::default();
@ -134,7 +136,9 @@ impl ProjectWorkspace {
};
// FIXME: cfg options
// Default to enable test for workspace crates.
let cfg_options = CfgOptions::default().atom("test".into());
let cfg_options = default_cfg_options
.clone()
.features(krate.features.iter().map(Into::into));
crates.insert(
crate_id,
crate_graph.add_crate_root(file_id, edition, cfg_options),
@ -164,9 +168,8 @@ impl ProjectWorkspace {
let mut sysroot_crates = FxHashMap::default();
for krate in sysroot.crates() {
if let Some(file_id) = load(krate.root(&sysroot)) {
// FIXME: cfg options
// Crates from sysroot have `cfg(test)` disabled
let cfg_options = CfgOptions::default();
let cfg_options = default_cfg_options.clone().remove_atom(&"test".into());
let crate_id =
crate_graph.add_crate_root(file_id, Edition::Edition2018, cfg_options);
sysroot_crates.insert(krate, crate_id);
@ -197,9 +200,9 @@ impl ProjectWorkspace {
let root = tgt.root(&cargo);
if let Some(file_id) = load(root) {
let edition = pkg.edition(&cargo);
// FIXME: cfg options
// Default to enable test for workspace crates.
let cfg_options = CfgOptions::default().atom("test".into());
let cfg_options = default_cfg_options
.clone()
.features(pkg.features(&cargo).iter().map(Into::into));
let crate_id =
crate_graph.add_crate_root(file_id, edition, cfg_options);
names.insert(crate_id, pkg.name(&cargo).to_string());
@ -301,3 +304,32 @@ fn find_cargo_toml(path: &Path) -> Result<PathBuf> {
}
Err(format!("can't find Cargo.toml at {}", path.display()))?
}
pub fn get_rustc_cfg_options() -> CfgOptions {
let mut cfg_options = CfgOptions::default();
match (|| -> Result<_> {
// `cfg(test)` ans `cfg(debug_assertion)` is handled outside, so we suppress them here.
let output = Command::new("rustc").args(&["--print", "cfg", "-O"]).output()?;
if !output.status.success() {
Err("failed to get rustc cfgs")?;
}
Ok(String::from_utf8(output.stdout)?)
})() {
Ok(rustc_cfgs) => {
for line in rustc_cfgs.lines() {
match line.find('=') {
None => cfg_options = cfg_options.atom(line.into()),
Some(pos) => {
let key = &line[..pos];
let value = line[pos + 1..].trim_matches('"');
cfg_options = cfg_options.key_value(key.into(), value.into());
}
}
}
}
Err(e) => log::error!("failed to get rustc cfgs: {}", e),
}
cfg_options
}