Add cast to type for constants to avoid mis-typing.

This commit is contained in:
Stephen Chung 2020-09-13 22:36:24 +08:00 committed by J Henry Waugh
parent 848bdf3f01
commit 6dc5a81d53
3 changed files with 6 additions and 5 deletions

View File

@ -140,12 +140,13 @@ impl Parse for Module {
ref expr, ref expr,
ident, ident,
attrs, attrs,
ty,
.. ..
}) => { }) => {
// #[cfg] attributes are not allowed on const declarations // #[cfg] attributes are not allowed on const declarations
crate::attrs::deny_cfg_attr(&attrs)?; crate::attrs::deny_cfg_attr(&attrs)?;
if let syn::Visibility::Public(_) = vis { if let syn::Visibility::Public(_) = vis {
consts.push((ident.to_string(), expr.as_ref().clone())); consts.push((ident.to_string(), ty.clone(), expr.as_ref().clone()));
} }
} }
_ => {} _ => {}

View File

@ -6,7 +6,7 @@ use crate::attrs::ExportScope;
use crate::function::ExportedFn; use crate::function::ExportedFn;
use crate::module::Module; use crate::module::Module;
pub(crate) type ExportedConst = (String, syn::Expr); pub(crate) type ExportedConst = (String, Box<syn::Type>, syn::Expr);
pub(crate) fn generate_body( pub(crate) fn generate_body(
fns: &mut [ExportedFn], fns: &mut [ExportedFn],
@ -20,11 +20,11 @@ pub(crate) fn generate_body(
let mut set_mod_blocks: Vec<syn::ExprBlock> = Vec::new(); let mut set_mod_blocks: Vec<syn::ExprBlock> = Vec::new();
let str_type_path = syn::parse2::<syn::Path>(quote! { str }).unwrap(); let str_type_path = syn::parse2::<syn::Path>(quote! { str }).unwrap();
for (const_name, const_expr) in consts { for (const_name, const_type, const_expr) in consts {
let const_literal = syn::LitStr::new(&const_name, proc_macro2::Span::call_site()); let const_literal = syn::LitStr::new(&const_name, proc_macro2::Span::call_site());
set_const_stmts.push( set_const_stmts.push(
syn::parse2::<syn::Stmt>(quote! { syn::parse2::<syn::Stmt>(quote! {
m.set_var(#const_literal, #const_expr); m.set_var(#const_literal, (#const_expr) as #const_type);
}) })
.unwrap(), .unwrap(),
); );

View File

@ -11,7 +11,7 @@ mod test {
pub mod special_array_package { pub mod special_array_package {
use rhai::{Array, INT}; use rhai::{Array, INT};
pub const MYSTIC_NUMBER: INT = 42 as INT; pub const MYSTIC_NUMBER: INT = 42;
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
pub mod feature { pub mod feature {