Skip to content

Commit 1067a1c

Browse files
committed
Read default cfgs from rustc
1 parent e0100e6 commit 1067a1c

File tree

8 files changed

+76
-14
lines changed

8 files changed

+76
-14
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/ra_batch/src/lib.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_hash::FxHashMap;
77
use crossbeam_channel::{unbounded, Receiver};
88
use ra_db::{CrateGraph, FileId, SourceRootId};
99
use ra_ide_api::{AnalysisChange, AnalysisHost, FeatureFlags};
10-
use ra_project_model::{PackageRoot, ProjectWorkspace};
10+
use ra_project_model::{get_rustc_cfg_options, PackageRoot, ProjectWorkspace};
1111
use ra_vfs::{RootEntry, Vfs, VfsChange, VfsTask, Watch};
1212
use ra_vfs_glob::RustPackageFilterBuilder;
1313

@@ -41,11 +41,17 @@ pub fn load_cargo(root: &Path) -> Result<(AnalysisHost, FxHashMap<SourceRootId,
4141
sender,
4242
Watch(false),
4343
);
44-
let (crate_graph, _crate_names) = ws.to_crate_graph(&mut |path: &Path| {
45-
let vfs_file = vfs.load(path);
46-
log::debug!("vfs file {:?} -> {:?}", path, vfs_file);
47-
vfs_file.map(vfs_file_to_id)
48-
});
44+
45+
// FIXME: cfg options?
46+
let default_cfg_options =
47+
get_rustc_cfg_options().atom("test".into()).atom("debug_assertion".into());
48+
49+
let (crate_graph, _crate_names) =
50+
ws.to_crate_graph(&default_cfg_options, &mut |path: &Path| {
51+
let vfs_file = vfs.load(path);
52+
log::debug!("vfs file {:?} -> {:?}", path, vfs_file);
53+
vfs_file.map(vfs_file_to_id)
54+
});
4955
log::debug!("crate graph: {:?}", crate_graph);
5056

5157
let source_roots = roots

crates/ra_cfg/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
//! ra_cfg defines conditional compiling options, `cfg` attibute parser and evaluator
2+
use std::iter::IntoIterator;
3+
24
use ra_syntax::SmolStr;
35
use rustc_hash::FxHashSet;
46

@@ -44,6 +46,14 @@ impl CfgOptions {
4446
self
4547
}
4648

49+
/// Shortcut to set features
50+
pub fn features(mut self, iter: impl IntoIterator<Item = SmolStr>) -> CfgOptions {
51+
for feat in iter {
52+
self = self.key_value("feature".into(), feat);
53+
}
54+
self
55+
}
56+
4757
pub fn remove_atom(mut self, name: &SmolStr) -> CfgOptions {
4858
self.atoms.remove(name);
4959
self

crates/ra_lsp_server/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ jod-thread = "0.1.0"
1919
ra_vfs = "0.4.0"
2020
ra_syntax = { path = "../ra_syntax" }
2121
ra_db = { path = "../ra_db" }
22+
ra_cfg = { path = "../ra_cfg" }
2223
ra_text_edit = { path = "../ra_text_edit" }
2324
ra_ide_api = { path = "../ra_ide_api" }
2425
lsp-server = "0.2.0"

crates/ra_lsp_server/src/world.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use ra_ide_api::{
1313
Analysis, AnalysisChange, AnalysisHost, CrateGraph, FeatureFlags, FileId, LibraryData,
1414
SourceRootId,
1515
};
16-
use ra_project_model::ProjectWorkspace;
16+
use ra_project_model::{get_rustc_cfg_options, ProjectWorkspace};
1717
use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsRoot, VfsTask, Watch};
1818
use ra_vfs_glob::{Glob, RustPackageFilterBuilder};
1919
use relative_path::RelativePathBuf;
@@ -97,14 +97,18 @@ impl WorldState {
9797
change.set_debug_root_path(SourceRootId(r.0), vfs_root_path.display().to_string());
9898
}
9999

100+
// FIXME: Read default cfgs from config
101+
let default_cfg_options =
102+
get_rustc_cfg_options().atom("test".into()).atom("debug_assertion".into());
103+
100104
// Create crate graph from all the workspaces
101105
let mut crate_graph = CrateGraph::default();
102106
let mut load = |path: &std::path::Path| {
103107
let vfs_file = vfs.load(path);
104108
vfs_file.map(|f| FileId(f.0))
105109
};
106110
for ws in workspaces.iter() {
107-
let (graph, crate_names) = ws.to_crate_graph(&mut load);
111+
let (graph, crate_names) = ws.to_crate_graph(&default_cfg_options, &mut load);
108112
let shift = crate_graph.extend(graph);
109113
for (crate_id, name) in crate_names {
110114
change.set_debug_crate_name(crate_id.shift(shift), name)

crates/ra_project_model/src/cargo_workspace.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ struct PackageData {
3939
is_member: bool,
4040
dependencies: Vec<PackageDependency>,
4141
edition: Edition,
42+
features: Vec<String>,
4243
}
4344

4445
#[derive(Debug, Clone)]
@@ -91,6 +92,9 @@ impl Package {
9192
pub fn edition(self, ws: &CargoWorkspace) -> Edition {
9293
ws.packages[self].edition
9394
}
95+
pub fn features(self, ws: &CargoWorkspace) -> &[String] {
96+
&ws.packages[self].features
97+
}
9498
pub fn targets<'a>(self, ws: &'a CargoWorkspace) -> impl Iterator<Item = Target> + 'a {
9599
ws.packages[self].targets.iter().cloned()
96100
}
@@ -144,6 +148,7 @@ impl CargoWorkspace {
144148
is_member,
145149
edition: Edition::from_string(&meta_pkg.edition),
146150
dependencies: Vec::new(),
151+
features: Vec::new(),
147152
});
148153
let pkg_data = &mut packages[pkg];
149154
pkg_by_id.insert(meta_pkg.id.clone(), pkg);
@@ -164,6 +169,7 @@ impl CargoWorkspace {
164169
let dep = PackageDependency { name: dep_node.name, pkg: pkg_by_id[&dep_node.pkg] };
165170
packages[source].dependencies.push(dep);
166171
}
172+
packages[source].features.extend(node.features);
167173
}
168174

169175
Ok(CargoWorkspace { packages, targets, workspace_root: meta.workspace_root })

crates/ra_project_model/src/json_project.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ pub struct Crate {
1919
pub(crate) root_module: PathBuf,
2020
pub(crate) edition: Edition,
2121
pub(crate) deps: Vec<Dep>,
22+
#[serde(default)]
23+
pub(crate) features: Vec<String>,
2224
}
2325

2426
#[derive(Clone, Copy, Debug, Deserialize)]

crates/ra_project_model/src/lib.rs

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use std::{
99
fs::File,
1010
io::BufReader,
1111
path::{Path, PathBuf},
12+
process::Command,
1213
};
1314

1415
use ra_cfg::CfgOptions;
@@ -118,6 +119,7 @@ impl ProjectWorkspace {
118119

119120
pub fn to_crate_graph(
120121
&self,
122+
default_cfg_options: &CfgOptions,
121123
load: &mut dyn FnMut(&Path) -> Option<FileId>,
122124
) -> (CrateGraph, FxHashMap<CrateId, String>) {
123125
let mut crate_graph = CrateGraph::default();
@@ -134,7 +136,9 @@ impl ProjectWorkspace {
134136
};
135137
// FIXME: cfg options
136138
// Default to enable test for workspace crates.
137-
let cfg_options = CfgOptions::default().atom("test".into());
139+
let cfg_options = default_cfg_options
140+
.clone()
141+
.features(krate.features.iter().map(Into::into));
138142
crates.insert(
139143
crate_id,
140144
crate_graph.add_crate_root(file_id, edition, cfg_options),
@@ -164,9 +168,8 @@ impl ProjectWorkspace {
164168
let mut sysroot_crates = FxHashMap::default();
165169
for krate in sysroot.crates() {
166170
if let Some(file_id) = load(krate.root(&sysroot)) {
167-
// FIXME: cfg options
168171
// Crates from sysroot have `cfg(test)` disabled
169-
let cfg_options = CfgOptions::default();
172+
let cfg_options = default_cfg_options.clone().remove_atom(&"test".into());
170173
let crate_id =
171174
crate_graph.add_crate_root(file_id, Edition::Edition2018, cfg_options);
172175
sysroot_crates.insert(krate, crate_id);
@@ -197,9 +200,9 @@ impl ProjectWorkspace {
197200
let root = tgt.root(&cargo);
198201
if let Some(file_id) = load(root) {
199202
let edition = pkg.edition(&cargo);
200-
// FIXME: cfg options
201-
// Default to enable test for workspace crates.
202-
let cfg_options = CfgOptions::default().atom("test".into());
203+
let cfg_options = default_cfg_options
204+
.clone()
205+
.features(pkg.features(&cargo).iter().map(Into::into));
203206
let crate_id =
204207
crate_graph.add_crate_root(file_id, edition, cfg_options);
205208
names.insert(crate_id, pkg.name(&cargo).to_string());
@@ -301,3 +304,32 @@ fn find_cargo_toml(path: &Path) -> Result<PathBuf> {
301304
}
302305
Err(format!("can't find Cargo.toml at {}", path.display()))?
303306
}
307+
308+
pub fn get_rustc_cfg_options() -> CfgOptions {
309+
let mut cfg_options = CfgOptions::default();
310+
311+
match (|| -> Result<_> {
312+
// `cfg(test)` ans `cfg(debug_assertion)` is handled outside, so we suppress them here.
313+
let output = Command::new("rustc").args(&["--print", "cfg", "-O"]).output()?;
314+
if !output.status.success() {
315+
Err("failed to get rustc cfgs")?;
316+
}
317+
Ok(String::from_utf8(output.stdout)?)
318+
})() {
319+
Ok(rustc_cfgs) => {
320+
for line in rustc_cfgs.lines() {
321+
match line.find('=') {
322+
None => cfg_options = cfg_options.atom(line.into()),
323+
Some(pos) => {
324+
let key = &line[..pos];
325+
let value = line[pos + 1..].trim_matches('"');
326+
cfg_options = cfg_options.key_value(key.into(), value.into());
327+
}
328+
}
329+
}
330+
}
331+
Err(e) => log::error!("failed to get rustc cfgs: {}", e),
332+
}
333+
334+
cfg_options
335+
}

0 commit comments

Comments
 (0)