This commit is contained in:
Stephen Chung 2020-08-02 15:39:08 +08:00
parent 11f2b04152
commit 73cda2d4f9
15 changed files with 409 additions and 246 deletions

View File

@ -19,6 +19,7 @@ categories = [ "no-std", "embedded", "wasm", "parser-implementations" ]
[dependencies]
num-traits = { version = "0.2.11", default-features = false }
smallvec = { version = "1.4.1", default-features = false }
rhai_codegen = { version = "0.1", path = "codegen" }
[features]
#default = ["unchecked", "sync", "no_optimize", "no_float", "only_i32", "no_index", "no_object", "no_function", "no_module"]
@ -80,10 +81,6 @@ version = "0.2.1"
default_features = false
optional = true
[dependencies.rhai_codegen]
version = "0.1"
path = "codegen"
[target.'cfg(target_arch = "wasm32")'.dependencies]
instant= { version = "0.1.4", features = ["wasm-bindgen"] } # WASM implementation of std::time::Instant

View File

@ -2,7 +2,7 @@
name = "rhai_codegen"
version = "0.1.0"
edition = "2018"
authors = ["Stephen Chung", "jhwgh1968"]
authors = ["jhwgh1968", "Stephen Chung"]
description = "Proceducral macro support package for Rhai, a scripting language for Rust"
homepage = "https://github.com/jonathandturner/rhai"
repository = "https://github.com/jonathandturner/rhai"
@ -12,7 +12,7 @@ license = "MIT OR Apache-2.0"
proc-macro = true
[dev-dependencies]
rhai = { version = "*", path = ".." }
rhai = { path = ".." }
trybuild = "1"
[dependencies]

View File

@ -19,29 +19,36 @@ impl Parse for ExportedFn {
// Determine if the function is public.
let is_public = match fn_all.vis {
syn::Visibility::Public(_) => true,
_ => false
_ => false,
};
// Determine whether function generates a special calling convention for a mutable
// reciever.
let mut_receiver = {
if let Some(first_arg) = fn_all.sig.inputs.first() {
match first_arg {
syn::FnArg::Receiver(syn::Receiver { reference: Some(_), ..}) => true,
syn::FnArg::Typed(syn::PatType { ref ty, .. }) => {
match ty.as_ref() {
syn::FnArg::Receiver(syn::Receiver {
reference: Some(_), ..
}) => true,
syn::FnArg::Typed(syn::PatType { ref ty, .. }) => match ty.as_ref() {
&syn::Type::Reference(syn::TypeReference {
mutability: Some(_), .. }) => true,
&syn::Type::Reference(syn::TypeReference { mutability: None,
ref elem, .. }) => {
match elem.as_ref() {
mutability: Some(_),
..
}) => true,
&syn::Type::Reference(syn::TypeReference {
mutability: None,
ref elem,
..
}) => match elem.as_ref() {
&syn::Type::Path(ref p) if p.path == str_type_path => false,
_ => return Err(syn::Error::new(ty.span(),
_ => {
return Err(syn::Error::new(
ty.span(),
"references from Rhai in this position \
must be mutable")),
must be mutable",
))
}
},
_ => false,
}
},
_ => false,
}
@ -57,31 +64,46 @@ impl Parse for ExportedFn {
_ => panic!("internal error: receiver argument outside of first position!?"),
};
let is_ok = match ty.as_ref() {
&syn::Type::Reference(syn::TypeReference { mutability: Some(_), .. }) => false,
&syn::Type::Reference(syn::TypeReference { mutability: None,
ref elem, .. }) => {
match elem.as_ref() {
&syn::Type::Reference(syn::TypeReference {
mutability: Some(_),
..
}) => false,
&syn::Type::Reference(syn::TypeReference {
mutability: None,
ref elem,
..
}) => match elem.as_ref() {
&syn::Type::Path(ref p) if p.path == str_type_path => true,
_ => false,
}
},
&syn::Type::Verbatim(_) => false,
_ => true,
};
if !is_ok {
return Err(syn::Error::new(ty.span(), "this type in this position passes from \
Rhai by value"));
return Err(syn::Error::new(
ty.span(),
"this type in this position passes from \
Rhai by value",
));
}
}
// No returning references or pointers.
if let syn::ReturnType::Type(_, ref rtype) = fn_all.sig.output {
match rtype.as_ref() {
&syn::Type::Ptr(_) => return Err(syn::Error::new(fn_all.sig.output.span(),
"cannot return a pointer to Rhai")),
&syn::Type::Reference(_) => return Err(syn::Error::new(fn_all.sig.output.span(),
"cannot return a reference to Rhai")),
_ => {},
&syn::Type::Ptr(_) => {
return Err(syn::Error::new(
fn_all.sig.output.span(),
"cannot return a pointer to Rhai",
))
}
&syn::Type::Reference(_) => {
return Err(syn::Error::new(
fn_all.sig.output.span(),
"cannot return a reference to Rhai",
))
}
_ => {}
}
}
Ok(ExportedFn {
@ -127,8 +149,10 @@ impl ExportedFn {
}
pub fn generate(self) -> proc_macro2::TokenStream {
let name: syn::Ident = syn::Ident::new(&format!("rhai_fn__{}", self.name().to_string()),
self.name().span());
let name: syn::Ident = syn::Ident::new(
&format!("rhai_fn__{}", self.name().to_string()),
self.name().span(),
);
let impl_block = self.generate_impl("Token");
quote! {
#[allow(unused)]
@ -159,20 +183,27 @@ impl ExportedFn {
syn::FnArg::Typed(pattern) => {
let arg_type: &syn::Type = {
match pattern.ty.as_ref() {
&syn::Type::Reference(
syn::TypeReference { ref elem, .. }) => elem.as_ref(),
&syn::Type::Reference(syn::TypeReference { ref elem, .. }) => {
elem.as_ref()
}
ref p => p,
}
};
let downcast_span = quote_spanned!(
arg_type.span()=> args[0usize].downcast_mut::<#arg_type>().unwrap());
unpack_stmts.push(syn::parse2::<syn::Stmt>(quote! {
unpack_stmts.push(
syn::parse2::<syn::Stmt>(quote! {
let #var: &mut _ = #downcast_span;
}).unwrap());
input_type_exprs.push(syn::parse2::<syn::Expr>(quote_spanned!(
})
.unwrap(),
);
input_type_exprs.push(
syn::parse2::<syn::Expr>(quote_spanned!(
arg_type.span()=> std::any::TypeId::of::<#arg_type>()
)).unwrap());
},
))
.unwrap(),
);
}
syn::FnArg::Receiver(_) => todo!("true self parameters not implemented yet"),
}
unpack_exprs.push(syn::parse2::<syn::Expr>(quote! { #var }).unwrap());
@ -192,39 +223,49 @@ impl ExportedFn {
syn::FnArg::Typed(pattern) => {
let arg_type: &syn::Type = pattern.ty.as_ref();
let downcast_span = match pattern.ty.as_ref() {
&syn::Type::Reference(syn::TypeReference { mutability: None,
ref elem, .. }) => {
match elem.as_ref() {
&syn::Type::Reference(syn::TypeReference {
mutability: None,
ref elem,
..
}) => match elem.as_ref() {
&syn::Type::Path(ref p) if p.path == str_type_path => {
is_str_ref = true;
quote_spanned!(arg_type.span()=>
args[#i]
.downcast_clone::<rhai::ImmutableString>()
.unwrap())
},
_ => panic!("internal error: why wasn't this found earlier!?"),
}
_ => panic!("internal error: why wasn't this found earlier!?"),
},
_ => {
is_str_ref = false;
quote_spanned!(arg_type.span()=>
args[#i].downcast_clone::<#arg_type>().unwrap())
},
}
};
unpack_stmts.push(syn::parse2::<syn::Stmt>(quote! {
unpack_stmts.push(
syn::parse2::<syn::Stmt>(quote! {
let #var = #downcast_span;
}).unwrap());
})
.unwrap(),
);
if !is_str_ref {
input_type_exprs.push(syn::parse2::<syn::Expr>(quote_spanned!(
input_type_exprs.push(
syn::parse2::<syn::Expr>(quote_spanned!(
arg_type.span()=> std::any::TypeId::of::<#arg_type>()
)).unwrap());
))
.unwrap(),
);
} else {
input_type_exprs.push(syn::parse2::<syn::Expr>(quote_spanned!(
input_type_exprs.push(
syn::parse2::<syn::Expr>(quote_spanned!(
arg_type.span()=> std::any::TypeId::of::<rhai::ImmutableString>()
)).unwrap());
))
.unwrap(),
);
}
}
},
syn::FnArg::Receiver(_) => panic!("internal error: how did this happen!?"),
}
if !is_str_ref {
@ -302,8 +343,10 @@ mod function_tests {
assert!(item_fn.is_public());
assert!(item_fn.return_type().is_none());
assert_eq!(item_fn.arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { x: usize }).unwrap());
assert_eq!(
item_fn.arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { x: usize }).unwrap()
);
}
#[test]
@ -319,10 +362,14 @@ mod function_tests {
assert!(item_fn.is_public());
assert!(item_fn.return_type().is_none());
assert_eq!(item_fn.arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { x: usize }).unwrap());
assert_eq!(item_fn.arg_list().skip(1).next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { y: f32 }).unwrap());
assert_eq!(
item_fn.arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { x: usize }).unwrap()
);
assert_eq!(
item_fn.arg_list().skip(1).next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { y: f32 }).unwrap()
);
}
#[test]
@ -336,7 +383,8 @@ mod function_tests {
assert!(!item_fn.mutable_receiver());
assert!(item_fn.is_public());
assert_eq!(item_fn.arg_list().count(), 0);
assert_eq!(item_fn.return_type().unwrap(),
assert_eq!(
item_fn.return_type().unwrap(),
&syn::Type::Path(syn::TypePath {
qself: None,
path: syn::parse2::<syn::Path>(quote! { usize }).unwrap()
@ -351,8 +399,7 @@ mod function_tests {
};
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!(format!("{}", err),
"cannot return a reference to Rhai");
assert_eq!(format!("{}", err), "cannot return a reference to Rhai");
}
#[test]
@ -362,8 +409,7 @@ mod function_tests {
};
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!(format!("{}", err),
"cannot return a pointer to Rhai");
assert_eq!(format!("{}", err), "cannot return a pointer to Rhai");
}
#[test]
@ -373,8 +419,10 @@ mod function_tests {
};
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!(format!("{}", err),
"references from Rhai in this position must be mutable");
assert_eq!(
format!("{}", err),
"references from Rhai in this position must be mutable"
);
}
#[test]
@ -384,8 +432,10 @@ mod function_tests {
};
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!(format!("{}", err),
"this type in this position passes from Rhai by value");
assert_eq!(
format!("{}", err),
"this type in this position passes from Rhai by value"
);
}
#[test]
@ -395,8 +445,10 @@ mod function_tests {
};
let err = syn::parse2::<ExportedFn>(input_tokens).unwrap_err();
assert_eq!(format!("{}", err),
"this type in this position passes from Rhai by value");
assert_eq!(
format!("{}", err),
"this type in this position passes from Rhai by value"
);
}
#[test]
@ -412,8 +464,10 @@ mod function_tests {
assert!(item_fn.is_public());
assert!(item_fn.return_type().is_none());
assert_eq!(item_fn.arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { message: &str }).unwrap());
assert_eq!(
item_fn.arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { message: &str }).unwrap()
);
}
#[test]
@ -429,10 +483,14 @@ mod function_tests {
assert!(item_fn.is_public());
assert!(item_fn.return_type().is_none());
assert_eq!(item_fn.arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { level: usize }).unwrap());
assert_eq!(item_fn.arg_list().skip(1).next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { message: &str }).unwrap());
assert_eq!(
item_fn.arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { level: usize }).unwrap()
);
assert_eq!(
item_fn.arg_list().skip(1).next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { message: &str }).unwrap()
);
}
#[test]
@ -490,7 +548,9 @@ mod generate_tests {
let expected = expected.to_string();
if &actual != &expected {
let mut counter = 0;
let iter = actual.chars().zip(expected.chars())
let iter = actual
.chars()
.zip(expected.chars())
.inspect(|_| counter += 1)
.skip_while(|(a, e)| *a == *e);
let (actual_diff, expected_diff) = {

View File

@ -75,8 +75,10 @@ mod module;
mod rhai_module;
#[proc_macro_attribute]
pub fn export_fn(_args: proc_macro::TokenStream,
input: proc_macro::TokenStream) -> proc_macro::TokenStream {
pub fn export_fn(
_args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let mut output = proc_macro2::TokenStream::from(input.clone());
let function_def = parse_macro_input!(input as function::ExportedFn);
output.extend(function_def.generate());
@ -84,8 +86,10 @@ pub fn export_fn(_args: proc_macro::TokenStream,
}
#[proc_macro_attribute]
pub fn export_module(_args: proc_macro::TokenStream,
input: proc_macro::TokenStream) -> proc_macro::TokenStream {
pub fn export_module(
_args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let module_def = parse_macro_input!(input as module::Module);
let tokens = module_def.generate();
proc_macro::TokenStream::from(tokens)
@ -108,8 +112,8 @@ pub fn register_exported_fn(args: proc_macro::TokenStream) -> proc_macro::TokenS
let items: Vec<syn::Expr> = args.into_iter().collect();
if items.len() != 3 {
return proc_macro::TokenStream::from(
syn::Error::new(arg_span, "this macro requires three arguments")
.to_compile_error());
syn::Error::new(arg_span, "this macro requires three arguments").to_compile_error(),
);
}
let rhai_module = &items[0];
let export_name = match &items[1] {
@ -122,15 +126,20 @@ pub fn register_exported_fn(args: proc_macro::TokenStream) -> proc_macro::TokenS
} else {
return proc_macro::TokenStream::from(
syn::Error::new(items[2].span(), "third argument must be a function name")
.to_compile_error());
.to_compile_error(),
);
};
let gen_mod_path: syn::punctuated::Punctuated<syn::PathSegment, _> = {
let mut g = rust_modpath.clone().segments;
g.pop();
let ident = syn::Ident::new(&format!("rhai_fn__{}",
rust_modpath.segments.last().unwrap().ident),
items[2].span());
g.push_value(syn::PathSegment { ident, arguments: syn::PathArguments::None });
let ident = syn::Ident::new(
&format!("rhai_fn__{}", rust_modpath.segments.last().unwrap().ident),
items[2].span(),
);
g.push_value(syn::PathSegment {
ident,
arguments: syn::PathArguments::None,
});
g
};
let tokens = quote! {

View File

@ -17,36 +17,39 @@ impl Parse for Module {
let fns: Vec<_>;
let consts: Vec<_>;
if let Some((_, ref content)) = mod_all.content {
fns = content.iter()
.filter_map(|item| {
match item {
fns = content
.iter()
.filter_map(|item| match item {
syn::Item::Fn(f) => {
if let syn::Visibility::Public(_) = f.vis {
Some(f)
} else {
None
}
},
_ => None,
}
_ => None,
})
.try_fold(Vec::new(), |mut vec, itemfn| {
syn::parse2::<ExportedFn>(itemfn.to_token_stream())
.map(|f| vec.push(f))
.map(|_| vec)
})?;
consts = content.iter()
.filter_map(|item| {
match item {
syn::Item::Const(syn::ItemConst {vis, ref expr, ident, ..}) => {
consts = content
.iter()
.filter_map(|item| match item {
syn::Item::Const(syn::ItemConst {
vis,
ref expr,
ident,
..
}) => {
if let syn::Visibility::Public(_) = vis {
Some((ident.to_string(), expr.as_ref().clone()))
} else {
None
}
},
_ => None,
}
_ => None,
})
.collect();
} else {
@ -87,7 +90,6 @@ mod module_tests {
#[test]
fn empty_module() {
let input_tokens: TokenStream = quote! {
pub mod empty { }
};
@ -99,7 +101,6 @@ mod module_tests {
#[test]
fn one_factory_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod one_fn {
pub fn get_mystic_number() -> INT {
@ -113,13 +114,14 @@ mod module_tests {
assert_eq!(item_mod.fns.len(), 1);
assert_eq!(item_mod.fns[0].name().to_string(), "get_mystic_number");
assert_eq!(item_mod.fns[0].arg_count(), 0);
assert_eq!(item_mod.fns[0].return_type().unwrap(),
&syn::parse2::<syn::Type>(quote! { INT }).unwrap());
assert_eq!(
item_mod.fns[0].return_type().unwrap(),
&syn::parse2::<syn::Type>(quote! { INT }).unwrap()
);
}
#[test]
fn one_single_arg_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod one_fn {
pub fn add_one_to(x: INT) -> INT {
@ -133,15 +135,18 @@ mod module_tests {
assert_eq!(item_mod.fns.len(), 1);
assert_eq!(item_mod.fns[0].name().to_string(), "add_one_to");
assert_eq!(item_mod.fns[0].arg_count(), 1);
assert_eq!(item_mod.fns[0].arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { x: INT }).unwrap());
assert_eq!(item_mod.fns[0].return_type().unwrap(),
&syn::parse2::<syn::Type>(quote! { INT }).unwrap());
assert_eq!(
item_mod.fns[0].arg_list().next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { x: INT }).unwrap()
);
assert_eq!(
item_mod.fns[0].return_type().unwrap(),
&syn::parse2::<syn::Type>(quote! { INT }).unwrap()
);
}
#[test]
fn one_double_arg_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod one_fn {
pub fn add_together(x: INT, y: INT) -> INT {
@ -156,18 +161,23 @@ mod module_tests {
assert_eq!(item_mod.fns.len(), 1);
assert_eq!(item_mod.fns[0].name().to_string(), "add_together");
assert_eq!(item_mod.fns[0].arg_count(), 2);
assert_eq!(args.next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { x: INT }).unwrap());
assert_eq!(args.next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { y: INT }).unwrap());
assert_eq!(
args.next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { x: INT }).unwrap()
);
assert_eq!(
args.next().unwrap(),
&syn::parse2::<syn::FnArg>(quote! { y: INT }).unwrap()
);
assert!(args.next().is_none());
assert_eq!(item_mod.fns[0].return_type().unwrap(),
&syn::parse2::<syn::Type>(quote! { INT }).unwrap());
assert_eq!(
item_mod.fns[0].return_type().unwrap(),
&syn::parse2::<syn::Type>(quote! { INT }).unwrap()
);
}
#[test]
fn one_constant_module() {
let input_tokens: TokenStream = quote! {
pub mod one_constant {
pub const MYSTIC_NUMBER: INT = 42;
@ -178,12 +188,14 @@ mod module_tests {
assert!(item_mod.fns.is_empty());
assert_eq!(item_mod.consts.len(), 1);
assert_eq!(&item_mod.consts[0].0, "MYSTIC_NUMBER");
assert_eq!(item_mod.consts[0].1, syn::parse2::<syn::Expr>(quote! { 42 }).unwrap());
assert_eq!(
item_mod.consts[0].1,
syn::parse2::<syn::Expr>(quote! { 42 }).unwrap()
);
}
#[test]
fn one_private_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod one_fn {
fn get_mystic_number() -> INT {
@ -199,7 +211,6 @@ mod module_tests {
#[test]
fn one_private_constant_module() {
let input_tokens: TokenStream = quote! {
pub mod one_constant {
const MYSTIC_NUMBER: INT = 42;
@ -224,7 +235,9 @@ mod generate_tests {
let expected = expected.to_string();
if &actual != &expected {
let mut counter = 0;
let iter = actual.chars().zip(expected.chars())
let iter = actual
.chars()
.zip(expected.chars())
.inspect(|_| counter += 1)
.skip_while(|(a, e)| *a == *e);
let (actual_diff, expected_diff) = {
@ -265,7 +278,6 @@ mod generate_tests {
#[test]
fn one_factory_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod one_fn {
pub fn get_mystic_number() -> INT {
@ -320,7 +332,6 @@ mod generate_tests {
#[test]
fn one_single_arg_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod one_fn {
pub fn add_one_to(x: INT) -> INT {
@ -376,7 +387,6 @@ mod generate_tests {
#[test]
fn one_double_arg_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod one_fn {
pub fn add_together(x: INT, y: INT) -> INT {
@ -435,7 +445,6 @@ mod generate_tests {
#[test]
fn one_constant_module() {
let input_tokens: TokenStream = quote! {
pub mod one_constant {
pub const MYSTIC_NUMBER: INT = 42;
@ -462,7 +471,6 @@ mod generate_tests {
#[test]
fn one_constant_module_imports_preserved() {
let input_tokens: TokenStream = quote! {
pub mod one_constant {
pub use rhai::INT;
@ -491,7 +499,6 @@ mod generate_tests {
#[test]
fn one_private_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod one_fn {
fn get_mystic_number() -> INT {
@ -521,7 +528,6 @@ mod generate_tests {
#[test]
fn one_private_constant_module() {
let input_tokens: TokenStream = quote! {
pub mod one_constant {
const MYSTIC_NUMBER: INT = 42;
@ -547,7 +553,6 @@ mod generate_tests {
#[test]
fn one_str_arg_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod str_fn {
pub fn print_out_to(x: &str) {
@ -604,7 +609,6 @@ mod generate_tests {
#[test]
fn one_mut_ref_fn_module() {
let input_tokens: TokenStream = quote! {
pub mod ref_fn {
pub fn increment(x: &mut FLOAT) {

View File

@ -6,7 +6,7 @@ pub(crate) type ExportedConst = (String, syn::Expr);
pub(crate) fn generate_body(
fns: &Vec<ExportedFn>,
consts: &Vec<ExportedConst>
consts: &Vec<ExportedConst>,
) -> proc_macro2::TokenStream {
let mut set_fn_stmts: Vec<syn::Stmt> = Vec::new();
let mut set_const_stmts: Vec<syn::Stmt> = Vec::new();
@ -14,51 +14,67 @@ pub(crate) fn generate_body(
for (const_name, const_expr) in consts {
let const_literal = syn::LitStr::new(&const_name, proc_macro2::Span::call_site());
set_const_stmts.push(syn::parse2::<syn::Stmt>(quote! {
set_const_stmts.push(
syn::parse2::<syn::Stmt>(quote! {
m.set_var(#const_literal, #const_expr);
}).unwrap());
})
.unwrap(),
);
}
// NB: these are token streams, because reparsing messes up "> >" vs ">>"
let mut gen_fn_tokens: Vec<proc_macro2::TokenStream> = Vec::new();
for function in fns {
let fn_token_name = syn::Ident::new(&format!("{}__Token", function.name().to_string()),
function.name().span());
let fn_literal = syn::LitStr::new(&function.name().to_string(),
proc_macro2::Span::call_site());
let fn_input_types: Vec<syn::Expr> = function.arg_list()
let fn_token_name = syn::Ident::new(
&format!("{}__Token", function.name().to_string()),
function.name().span(),
);
let fn_literal =
syn::LitStr::new(&function.name().to_string(), proc_macro2::Span::call_site());
let fn_input_types: Vec<syn::Expr> = function
.arg_list()
.map(|fnarg| match fnarg {
syn::FnArg::Receiver(_) => panic!("internal error: receiver fn outside impl!?"),
syn::FnArg::Typed(syn::PatType { ref ty, .. }) => {
let arg_type = match ty.as_ref() {
&syn::Type::Reference(syn::TypeReference { mutability: None,
ref elem, .. }) => {
match elem.as_ref() {
&syn::Type::Path(ref p) if p.path == str_type_path =>
&syn::Type::Reference(syn::TypeReference {
mutability: None,
ref elem,
..
}) => match elem.as_ref() {
&syn::Type::Path(ref p) if p.path == str_type_path => {
syn::parse2::<syn::Type>(quote! {
rhai::ImmutableString }).unwrap(),
_ => panic!("internal error: non-string shared reference!?"),
rhai::ImmutableString })
.unwrap()
}
_ => panic!("internal error: non-string shared reference!?"),
},
&syn::Type::Reference(syn::TypeReference { mutability: Some(_),
ref elem, .. }) => {
match elem.as_ref() {
&syn::Type::Reference(syn::TypeReference {
mutability: Some(_),
ref elem,
..
}) => match elem.as_ref() {
&syn::Type::Path(ref p) => syn::parse2::<syn::Type>(quote! {
#p }).unwrap(),
#p })
.unwrap(),
_ => panic!("internal error: non-string shared reference!?"),
}
},
t => t.clone(),
};
syn::parse2::<syn::Expr>(quote! {
core::any::TypeId::of::<#arg_type>()}).unwrap()
},
}).collect();
core::any::TypeId::of::<#arg_type>()})
.unwrap()
}
})
.collect();
set_fn_stmts.push(syn::parse2::<syn::Stmt>(quote! {
set_fn_stmts.push(
syn::parse2::<syn::Stmt>(quote! {
m.set_fn(#fn_literal, FnAccess::Public, &[#(#fn_input_types),*],
rhai::plugin::CallableFunction::from_plugin(#fn_token_name()));
}).unwrap());
})
.unwrap(),
);
gen_fn_tokens.push(quote! {
#[allow(non_camel_case_types)]
@ -79,7 +95,8 @@ pub(crate) fn generate_body(
m
}
}
}).unwrap();
})
.unwrap();
let (_, generate_call_content) = generate_fncall.content.take().unwrap();

View File

@ -1,10 +1,10 @@
use rhai::{EvalAltResult, FLOAT, INT, Module, RegisterFn};
use rhai::plugin::*;
use rhai::module_resolvers::*;
use rhai::plugin::*;
use rhai::{EvalAltResult, Module, RegisterFn, FLOAT, INT};
pub mod raw_fn {
use rhai::FLOAT;
use rhai::export_fn;
use rhai::FLOAT;
#[export_fn]
pub fn distance_function(x1: FLOAT, y1: FLOAT, x2: FLOAT, y2: FLOAT) -> FLOAT {
@ -15,22 +15,30 @@ pub mod raw_fn {
#[test]
fn raw_fn_test() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.register_fn("get_mystic_number", || { 42 as FLOAT });
engine.register_fn("get_mystic_number", || 42 as FLOAT);
let mut m = Module::new();
rhai::register_exported_fn!(m, "euclidean_distance".to_string(), raw_fn::distance_function);
rhai::register_exported_fn!(
m,
"euclidean_distance".to_string(),
raw_fn::distance_function
);
let mut r = StaticModuleResolver::new();
r.insert("Math::Advanced".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<FLOAT>(
assert_eq!(
engine.eval::<FLOAT>(
r#"import "Math::Advanced" as math;
let x = math::euclidean_distance(0.0, 1.0, 0.0, get_mystic_number()); x"#)?, 41.0);
let x = math::euclidean_distance(0.0, 1.0, 0.0, get_mystic_number()); x"#
)?,
41.0
);
Ok(())
}
mod raw_fn_mut {
use rhai::FLOAT;
use rhai::export_fn;
use rhai::FLOAT;
#[export_fn]
pub fn add_in_place(f1: &mut FLOAT, f2: FLOAT) {
@ -41,18 +49,22 @@ mod raw_fn_mut {
#[test]
fn raw_fn_mut_test() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.register_fn("get_mystic_number", || { 42 as FLOAT });
engine.register_fn("get_mystic_number", || 42 as FLOAT);
let mut m = Module::new();
rhai::register_exported_fn!(m, "add_in_place", raw_fn_mut::add_in_place);
let mut r = StaticModuleResolver::new();
r.insert("Math::Advanced".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<FLOAT>(
assert_eq!(
engine.eval::<FLOAT>(
r#"import "Math::Advanced" as math;
let x = get_mystic_number();
math::add_in_place(x, 1.0);
x"#)?, 43.0);
x"#
)?,
43.0
);
Ok(())
}
@ -69,29 +81,33 @@ mod raw_fn_str {
#[test]
fn raw_fn_str_test() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.register_fn("get_mystic_number", || { 42 as FLOAT });
engine.register_fn("get_mystic_number", || 42 as FLOAT);
let mut m = Module::new();
rhai::register_exported_fn!(m, "write_out_str", raw_fn_str::write_out_str);
let mut r = StaticModuleResolver::new();
r.insert("Host::IO".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<bool>(
assert_eq!(
engine.eval::<bool>(
r#"import "Host::IO" as io;
let x = io::write_out_str("hello world!");
x"#)?, true);
x"#
)?,
true
);
Ok(())
}
mod mut_opaque_ref {
use rhai::INT;
use rhai::export_fn;
use rhai::INT;
#[derive(Clone)]
pub struct StatusMessage {
os_code: Option<INT>,
message: String,
is_ok: bool
is_ok: bool,
}
#[export_fn]
@ -130,12 +146,16 @@ fn mut_opaque_ref_test() -> Result<(), Box<EvalAltResult>> {
r.insert("Host::Msg".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<bool>(
assert_eq!(
engine.eval::<bool>(
r#"import "Host::Msg" as msg;
let message1 = msg::new_message(true, "it worked");
let ok1 = msg::write_out_message(message1);
let message2 = msg::new_os_message(true, 0);
let ok2 = msg::write_out_message(message2);
ok1 && ok2"#)?, true);
ok1 && ok2"#
)?,
true
);
Ok(())
}

View File

@ -1,6 +1,6 @@
use rhai::{EvalAltResult, FLOAT, INT, RegisterFn};
use rhai::plugin::*;
use rhai::module_resolvers::*;
use rhai::plugin::*;
use rhai::{EvalAltResult, RegisterFn, FLOAT, INT};
pub mod empty_module {
use rhai::export_module;
@ -17,8 +17,10 @@ fn empty_module_test() -> Result<(), Box<EvalAltResult>> {
r.insert("Module::Empty".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<INT>(
r#"import "Module::Empty" as m; 42"#)?, 42);
assert_eq!(
engine.eval::<INT>(r#"import "Module::Empty" as m; 42"#)?,
42
);
Ok(())
}
@ -42,10 +44,14 @@ fn one_fn_module_test() -> Result<(), Box<EvalAltResult>> {
r.insert("Math::Advanced".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<FLOAT>(
assert_eq!(
engine.eval::<FLOAT>(
r#"import "Math::Advanced" as math;
let m = math::get_mystic_number();
m"#)?, 42.0);
m"#
)?,
42.0
);
Ok(())
}
@ -72,11 +78,15 @@ fn one_fn_and_const_module_test() -> Result<(), Box<EvalAltResult>> {
r.insert("Math::Advanced".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<FLOAT>(
assert_eq!(
engine.eval::<FLOAT>(
r#"import "Math::Advanced" as math;
let m = math::MYSTIC_NUMBER;
let x = math::euclidean_distance(0.0, 1.0, 0.0, m);
x"#)?, 41.0);
x"#
)?,
41.0
);
Ok(())
}
@ -100,27 +110,31 @@ fn raw_fn_str_module_test() -> Result<(), Box<EvalAltResult>> {
r.insert("Host::IO".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<bool>(
assert_eq!(
engine.eval::<bool>(
r#"import "Host::IO" as io;
let x = io::write_out_str("hello world!");
x"#)?, true);
x"#
)?,
true
);
Ok(())
}
pub mod mut_opaque_ref_module {
use rhai::INT;
use rhai::export_module;
use rhai::INT;
#[derive(Clone)]
pub struct StatusMessage {
os_code: Option<INT>,
message: String,
is_ok: bool
is_ok: bool,
}
#[export_module]
pub mod host_msg {
use super::{INT, StatusMessage};
use super::{StatusMessage, INT};
pub fn new_message(is_ok: bool, message: &str) -> StatusMessage {
StatusMessage {
@ -153,13 +167,17 @@ fn mut_opaque_ref_test() -> Result<(), Box<EvalAltResult>> {
r.insert("Host::Msg".to_string(), m);
engine.set_module_resolver(Some(r));
assert_eq!(engine.eval::<bool>(
assert_eq!(
engine.eval::<bool>(
r#"import "Host::Msg" as msg;
let success = "it worked";
let message1 = msg::new_message(true, success);
let ok1 = msg::write_out_message(message1);
let message2 = msg::new_os_message(true, 0);
let ok2 = msg::write_out_message(message2);
ok1 && ok2"#)?, true);
ok1 && ok2"#
)?,
true
);
Ok(())
}

View File

@ -13,7 +13,12 @@ pub fn test_fn(input: &NonClonable) -> bool {
}
fn main() {
let n = NonClonable { a: 0.0, b: 10, c: 'a', d: true };
let n = NonClonable {
a: 0.0,
b: 10,
c: 'a',
d: true,
};
if test_fn(n) {
println!("yes");
} else {

View File

@ -13,7 +13,12 @@ pub fn test_fn(input: NonClonable) -> bool {
}
fn main() {
let n = NonClonable { a: 0.0, b: 10, c: 'a', d: true };
let n = NonClonable {
a: 0.0,
b: 10,
c: 'a',
d: true,
};
if test_fn(n) {
println!("yes");
} else {

View File

@ -13,7 +13,12 @@ pub fn test_fn(a: u32, b: NonClonable) -> bool {
}
fn main() {
let n = NonClonable { a: 0.0, b: 10, c: 'a', d: true };
let n = NonClonable {
a: 0.0,
b: 10,
c: 'a',
d: true,
};
if test_fn(10, n) {
println!("yes");
} else {

View File

@ -14,7 +14,12 @@ pub fn test_fn(input: &mut Clonable) -> &mut bool {
}
fn main() {
let n = Clonable { a: 0.0, b: 10, c: 'a', d: true };
let n = Clonable {
a: 0.0,
b: 10,
c: 'a',
d: true,
};
if test_fn(n) {
println!("yes");
} else {

View File

@ -14,6 +14,14 @@ pub fn test_fn(input: Clonable) -> *const str {
}
fn main() {
let n = Clonable { a: 0.0, b: 10, c: 'a', d: true };
println!("{}", unsafe { let ptr = test_fn(n); *ptr });
let n = Clonable {
a: 0.0,
b: 10,
c: 'a',
d: true,
};
println!("{}", unsafe {
let ptr = test_fn(n);
*ptr
});
}

View File

@ -14,6 +14,11 @@ pub fn test_fn(input: Clonable) -> & 'static str {
}
fn main() {
let n = Clonable { a: 0.0, b: 10, c: 'a', d: true };
let n = Clonable {
a: 0.0,
b: 10,
c: 'a',
d: true,
};
println!("{}", test_fn(n));
}

View File

@ -14,7 +14,12 @@ pub fn test_fn(input: Clonable, factor: &bool) -> bool {
}
fn main() {
let n = Clonable { a: 0.0, b: 10, c: 'a', d: true };
let n = Clonable {
a: 0.0,
b: 10,
c: 'a',
d: true,
};
if test_fn(n, &true) {
println!("yes");
} else {