Skip to content

Commit 7f3a9ca

Browse files
committed
Replace manual cfg parsing with cfg-expr crate
1 parent e8baebb commit 7f3a9ca

2 files changed

Lines changed: 32 additions & 22 deletions

File tree

rule-preprocessor/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ version = "0.1.0"
44
edition = "2024"
55

66
[dependencies]
7+
cfg-expr = "0.17"
78
libcc2rs = { path = "../libcc2rs" }
89
rules = { path = "../rules" }
910
ra_ap_syntax = "0.0.266"

rule-preprocessor/src/syntactic.rs

Lines changed: 31 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,11 @@ impl SyntacticAnalysis {
103103
file_ir.insert(name, RuleIr::Type(ir));
104104
}
105105
} else if fn_name.starts_with('f') {
106-
file_ir.insert(
107-
fn_name.clone(),
108-
RuleIr::Fn(FnIrBuilder::new(&fn_item).build(path)),
109-
);
106+
let builder = FnIrBuilder::new(&fn_item);
107+
if !builder.matches_host_arch() {
108+
continue;
109+
}
110+
file_ir.insert(fn_name.clone(), RuleIr::Fn(builder.build(path)));
110111
}
111112
}
112113

@@ -253,29 +254,37 @@ impl<'a> FnIrBuilder<'a> {
253254
Self { fn_item }
254255
}
255256

256-
fn get_target_os(&self) -> Option<String> {
257+
fn get_cfg(&self) -> Option<cfg_expr::Expression> {
257258
use ast::HasAttrs;
258-
for attr in self.fn_item.attrs() {
259+
self.fn_item.attrs().find_map(|attr| {
259260
let meta_text = attr.meta()?.syntax().text().to_string();
260-
let syn::Meta::List(list) = syn::parse_str(&meta_text).ok()? else {
261-
continue;
261+
let syn::Meta::List(list) = syn::parse_str::<syn::Meta>(&meta_text).ok()? else {
262+
return None;
262263
};
263264
if !list.path.is_ident("cfg") {
264-
continue;
265-
}
266-
let mut found = None;
267-
let _ = list.parse_nested_meta(|nested| {
268-
if nested.path.is_ident("target_os") {
269-
let lit: syn::LitStr = nested.value()?.parse()?;
270-
found = Some(lit.value());
271-
}
272-
Ok(())
273-
});
274-
if found.is_some() {
275-
return found;
265+
return None;
276266
}
277-
}
278-
None
267+
cfg_expr::Expression::parse(&list.tokens.to_string()).ok()
268+
})
269+
}
270+
271+
fn matches_host_arch(&self) -> bool {
272+
use cfg_expr::expr::{Predicate, TargetPredicate};
273+
let Some(expr) = self.get_cfg() else {
274+
return true;
275+
};
276+
expr.eval(|pred| match pred {
277+
Predicate::Target(TargetPredicate::Arch(a)) => a.as_str() == std::env::consts::ARCH,
278+
_ => true,
279+
})
280+
}
281+
282+
fn get_target_os(&self) -> Option<String> {
283+
use cfg_expr::expr::{Predicate, TargetPredicate};
284+
self.get_cfg()?.predicates().find_map(|p| match p {
285+
Predicate::Target(TargetPredicate::Os(o)) => Some(o.as_str().to_string()),
286+
_ => None,
287+
})
279288
}
280289

281290
fn params(&self) -> Vec<ParamInfo> {

0 commit comments

Comments
 (0)