Block #[cfg] attributes on inner constants

This commit is contained in:
J Henry Waugh 2020-08-21 23:21:56 -05:00
parent 55870e7b37
commit 65009dd193
3 changed files with 63 additions and 13 deletions

View File

@ -199,7 +199,7 @@ impl Parse for Module {
fn parse(input: ParseStream) -> syn::Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
let mut mod_all: syn::ItemMod = input.parse()?; let mut mod_all: syn::ItemMod = input.parse()?;
let fns: Vec<_>; let fns: Vec<_>;
let consts: Vec<_>; let mut consts: Vec<_> = new_vec![];
let mut submodules: Vec<_> = Vec::new(); let mut submodules: Vec<_> = Vec::new();
if let Some((_, ref mut content)) = mod_all.content { if let Some((_, ref mut content)) = mod_all.content {
// Gather and parse functions. // Gather and parse functions.
@ -223,24 +223,33 @@ impl Parse for Module {
.map(|_| vec) .map(|_| vec)
})?; })?;
// Gather and parse constants definitions. // Gather and parse constants definitions.
consts = content for item in content.iter() {
.iter() match item {
.filter_map(|item| match item {
syn::Item::Const(syn::ItemConst { syn::Item::Const(syn::ItemConst {
vis, vis,
ref expr, ref expr,
ident, ident,
attrs,
.. ..
}) => { }) => {
if let syn::Visibility::Public(_) = vis { // #[cfg] attributes are not allowed on const declarations
Some((ident.to_string(), expr.as_ref().clone())) if let Some(cfg_attr) = attrs.iter().find(|a| {
} else { a.path
None .get_ident()
.map(|i| i.to_string() == "cfg")
.unwrap_or(false)
}) {
return Err(syn::Error::new(
cfg_attr.span(),
"cfg attributes not allowed on this item"));
} }
} if let syn::Visibility::Public(_) = vis {
_ => None, consts.push((ident.to_string(), expr.as_ref().clone()));
}) }
.collect(); },
_ => {},
}
};
// Gather and parse submodule definitions. // Gather and parse submodule definitions.
// //
// They are actually removed from the module's body, because they will need // They are actually removed from the module's body, because they will need
@ -270,7 +279,6 @@ impl Parse for Module {
} }
} }
} else { } else {
consts = new_vec![];
fns = new_vec![]; fns = new_vec![];
} }
Ok(Module { Ok(Module {

View File

@ -0,0 +1,31 @@
use rhai::plugin::*;
#[derive(Clone)]
pub struct Point {
x: f32,
y: f32,
}
#[export_module]
pub mod test_module {
use rhai::FLOAT;
#[cfg(feature = "foo")]
pub const MAGIC: FLOAT = 42.0 as FLOAT;
pub fn test_fn(input: Point) -> bool {
input.x > input.y
}
}
fn main() {
let n = Point {
x: 0.0,
y: 10.0,
};
if test_module::test_fn(n) {
println!("yes");
} else {
println!("no");
}
}

View File

@ -0,0 +1,11 @@
error: cfg attributes not allowed on this item
--> $DIR/module_cfg_const.rs:13:5
|
13 | #[cfg(feature = "foo")]
| ^^^^^^^^^^^^^^^^^^^^^^^
error[E0433]: failed to resolve: use of undeclared type or module `test_module`
--> $DIR/module_cfg_const.rs:26:8
|
26 | if test_module::test_fn(n) {
| ^^^^^^^^^^^ use of undeclared type or module `test_module`