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] [dependencies]
num-traits = { version = "0.2.11", default-features = false } num-traits = { version = "0.2.11", default-features = false }
smallvec = { version = "1.4.1", default-features = false } smallvec = { version = "1.4.1", default-features = false }
rhai_codegen = { version = "0.1", path = "codegen" }
[features] [features]
#default = ["unchecked", "sync", "no_optimize", "no_float", "only_i32", "no_index", "no_object", "no_function", "no_module"] #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 default_features = false
optional = true optional = true
[dependencies.rhai_codegen]
version = "0.1"
path = "codegen"
[target.'cfg(target_arch = "wasm32")'.dependencies] [target.'cfg(target_arch = "wasm32")'.dependencies]
instant= { version = "0.1.4", features = ["wasm-bindgen"] } # WASM implementation of std::time::Instant instant= { version = "0.1.4", features = ["wasm-bindgen"] } # WASM implementation of std::time::Instant

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -13,7 +13,12 @@ pub fn test_fn(input: &NonClonable) -> bool {
} }
fn main() { 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) { if test_fn(n) {
println!("yes"); println!("yes");
} else { } else {

View File

@ -13,7 +13,12 @@ pub fn test_fn(input: NonClonable) -> bool {
} }
fn main() { 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) { if test_fn(n) {
println!("yes"); println!("yes");
} else { } else {

View File

@ -13,7 +13,12 @@ pub fn test_fn(a: u32, b: NonClonable) -> bool {
} }
fn main() { 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) { if test_fn(10, n) {
println!("yes"); println!("yes");
} else { } else {

View File

@ -14,7 +14,12 @@ pub fn test_fn(input: &mut Clonable) -> &mut bool {
} }
fn main() { 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) { if test_fn(n) {
println!("yes"); println!("yes");
} else { } else {

View File

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

View File

@ -9,11 +9,16 @@ struct Clonable {
} }
#[export_fn] #[export_fn]
pub fn test_fn(input: Clonable) -> & 'static str { pub fn test_fn(input: Clonable) -> &'static str {
"yes" "yes"
} }
fn main() { 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)); println!("{}", test_fn(n));
} }

View File

@ -14,7 +14,12 @@ pub fn test_fn(input: Clonable, factor: &bool) -> bool {
} }
fn main() { 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) { if test_fn(n, &true) {
println!("yes"); println!("yes");
} else { } else {