Merge pull request #32 from jhwgh1968/plugins

Split function register macro, add Engine register support
This commit is contained in:
Stephen Chung 2020-08-13 13:07:02 +08:00 committed by GitHub
commit bb334eecc7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 213 additions and 65 deletions

View File

@ -229,8 +229,10 @@ impl ExportedFn {
} }
} }
pub fn generate_with_params(mut self, pub fn generate_with_params(
mut params: ExportedFnParams) -> proc_macro2::TokenStream { mut self,
mut params: ExportedFnParams,
) -> proc_macro2::TokenStream {
self.params = params; self.params = params;
self.generate() self.generate()
} }
@ -241,11 +243,12 @@ impl ExportedFn {
} else { } else {
self.name().to_string() self.name().to_string()
}; };
let name: syn::Ident = syn::Ident::new(&format!("rhai_fn_{}", name_str), let name: syn::Ident =
self.name().span()); syn::Ident::new(&format!("rhai_fn_{}", name_str), self.name().span());
let impl_block = self.generate_impl("Token"); let impl_block = self.generate_impl("Token");
let callable_block = self.generate_callable("Token"); let callable_block = self.generate_callable("Token");
let input_types_block = self.generate_input_types("Token"); let input_types_block = self.generate_input_types("Token");
let dyn_result_fn_block = self.generate_dynamic_fn();
quote! { quote! {
#[allow(unused)] #[allow(unused)]
pub mod #name { pub mod #name {
@ -254,6 +257,54 @@ impl ExportedFn {
#impl_block #impl_block
#callable_block #callable_block
#input_types_block #input_types_block
#dyn_result_fn_block
}
}
}
pub fn generate_dynamic_fn(&self) -> proc_macro2::TokenStream {
let name: syn::Ident = if let Some(ref name) = self.params.name {
syn::Ident::new(name, self.name().span())
} else {
self.name().clone()
};
let mut dynamic_signature = self.signature.clone();
dynamic_signature.ident =
syn::Ident::new("dynamic_result_fn", proc_macro2::Span::call_site());
dynamic_signature.output = syn::parse2::<syn::ReturnType>(quote! {
-> Result<Dynamic, EvalBox>
})
.unwrap();
let arguments: Vec<syn::Ident> = dynamic_signature
.inputs
.iter()
.filter_map(|fnarg| {
if let syn::FnArg::Typed(syn::PatType { ref pat, .. }) = fnarg {
if let syn::Pat::Ident(ref ident) = pat.as_ref() {
Some(ident.ident.clone())
} else {
None
}
} else {
None
}
})
.collect();
if !self.params.return_raw {
quote! {
type EvalBox = Box<EvalAltResult>;
pub #dynamic_signature {
Ok(Dynamic::from(super::#name(#(#arguments),*)))
}
}
} else {
quote! {
type EvalBox = Box<EvalAltResult>;
pub #dynamic_signature {
super::#name(#(#arguments),*)
}
} }
} }
} }
@ -740,6 +791,10 @@ mod generate_tests {
pub fn token_input_types() -> Box<[std::any::TypeId]> { pub fn token_input_types() -> Box<[std::any::TypeId]> {
Token().input_types() Token().input_types()
} }
type EvalBox = Box<EvalAltResult>;
pub fn dynamic_result_fn() -> Result<Dynamic, EvalBox> {
Ok(Dynamic::from(super::do_nothing()))
}
} }
}; };
@ -784,6 +839,10 @@ mod generate_tests {
pub fn token_input_types() -> Box<[std::any::TypeId]> { pub fn token_input_types() -> Box<[std::any::TypeId]> {
Token().input_types() Token().input_types()
} }
type EvalBox = Box<EvalAltResult>;
pub fn dynamic_result_fn(x: usize) -> Result<Dynamic, EvalBox> {
Ok(Dynamic::from(super::do_something(x)))
}
} }
}; };
@ -863,6 +922,10 @@ mod generate_tests {
pub fn token_input_types() -> Box<[std::any::TypeId]> { pub fn token_input_types() -> Box<[std::any::TypeId]> {
Token().input_types() Token().input_types()
} }
type EvalBox = Box<EvalAltResult>;
pub fn dynamic_result_fn(x: usize, y: usize) -> Result<Dynamic, EvalBox> {
Ok(Dynamic::from(super::add_together(x, y)))
}
} }
}; };
@ -909,6 +972,10 @@ mod generate_tests {
pub fn token_input_types() -> Box<[std::any::TypeId]> { pub fn token_input_types() -> Box<[std::any::TypeId]> {
Token().input_types() Token().input_types()
} }
type EvalBox = Box<EvalAltResult>;
pub fn dynamic_result_fn(x: &mut usize, y: usize) -> Result<Dynamic, EvalBox> {
Ok(Dynamic::from(super::increment(x, y)))
}
} }
}; };
@ -954,6 +1021,10 @@ mod generate_tests {
pub fn token_input_types() -> Box<[std::any::TypeId]> { pub fn token_input_types() -> Box<[std::any::TypeId]> {
Token().input_types() Token().input_types()
} }
type EvalBox = Box<EvalAltResult>;
pub fn dynamic_result_fn(message: &str) -> Result<Dynamic, EvalBox> {
Ok(Dynamic::from(super::special_print(message)))
}
} }
}; };

View File

@ -35,7 +35,7 @@
//! } //! }
//! ``` //! ```
//! //!
//! # Exporting a Function to Rhai //! # Exporting a Function to a Rhai Module
//! //!
//! ``` //! ```
//! use rhai::{EvalAltResult, FLOAT, Module, RegisterFn}; //! use rhai::{EvalAltResult, FLOAT, Module, RegisterFn};
@ -52,7 +52,7 @@
//! 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", distance_function); //! rhai::set_exported_fn!(m, "euclidean_distance", 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));
@ -66,12 +66,39 @@
//! } //! }
//! ``` //! ```
//! //!
//! # Exporting a Function to an Engine
//!
//! ```
//! use rhai::{EvalAltResult, FLOAT, Module, RegisterFn};
//! use rhai::plugin::*;
//! use rhai::module_resolvers::*;
//!
//! #[rhai::export_fn]
//! 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()
//! }
//!
//! fn main() -> Result<(), Box<EvalAltResult>> {
//!
//! let mut engine = Engine::new();
//! engine.register_fn("get_mystic_number", || { 42 as FLOAT });
//! rhai::register_exported_fn!(engine, "euclidean_distance", distance_function);
//!
//! assert_eq!(engine.eval::<FLOAT>(
//! r#"let m = get_mystic_number();
//! let x = euclidean_distance(0.0, 1.0, 0.0, m);
//! x"#)?, 41.0);
//! Ok(())
//! }
//! ```
//!
use quote::{quote, quote_spanned, ToTokens}; use quote::{quote, ToTokens};
use syn::{parse::Parser, parse_macro_input, spanned::Spanned}; use syn::parse_macro_input;
mod function; mod function;
mod module; mod module;
mod register;
mod rhai_module; mod rhai_module;
#[proc_macro_attribute] #[proc_macro_attribute]
@ -118,47 +145,30 @@ pub fn exported_module(module_path: proc_macro::TokenStream) -> proc_macro::Toke
#[proc_macro] #[proc_macro]
pub fn register_exported_fn(args: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn register_exported_fn(args: proc_macro::TokenStream) -> proc_macro::TokenStream {
let parser = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_separated_nonempty; let (engine_expr, export_name, rust_modpath) = match crate::register::parse_register_macro(args)
let args = parser.parse(args).unwrap(); {
let arg_span = args.span(); Ok(triple) => triple,
let items: Vec<syn::Expr> = args.into_iter().collect(); Err(e) => return e.to_compile_error().into(),
if items.len() != 3 {
return proc_macro::TokenStream::from(
syn::Error::new(arg_span, "this macro requires three arguments").to_compile_error(),
);
}
let rhai_module = &items[0];
let export_name = match &items[1] {
syn::Expr::Lit(litstr) => quote_spanned!(items[1].span()=>
#litstr.to_string()),
expr => quote! { #expr },
};
let rust_modpath = if let syn::Expr::Path(ref path) = &items[2] {
&path.path
} else {
return proc_macro::TokenStream::from(
syn::Error::new(items[2].span(), "third argument must be a function name")
.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,
});
g
}; };
let gen_mod_path = crate::register::generated_module_path(&rust_modpath);
let tokens = quote! { let tokens = quote! {
#rhai_module.set_fn(#export_name, rhai::FnAccess::Public, #engine_expr.register_result_fn(&(#export_name), #gen_mod_path::dynamic_result_fn);
#gen_mod_path::token_input_types().as_ref(), };
#gen_mod_path::token_callable()); proc_macro::TokenStream::from(tokens)
}
#[proc_macro]
pub fn set_exported_fn(args: proc_macro::TokenStream) -> proc_macro::TokenStream {
let (module_expr, export_name, rust_modpath) = match crate::register::parse_register_macro(args)
{
Ok(triple) => triple,
Err(e) => return e.to_compile_error().into(),
};
let gen_mod_path = crate::register::generated_module_path(&rust_modpath);
let tokens = quote! {
#module_expr.set_fn(#export_name, rhai::FnAccess::Public,
#gen_mod_path::token_input_types().as_ref(),
#gen_mod_path::token_callable());
}; };
proc_macro::TokenStream::from(tokens) proc_macro::TokenStream::from(tokens)
} }

49
codegen/src/register.rs Normal file
View File

@ -0,0 +1,49 @@
use quote::{quote, quote_spanned};
use syn::{parse::Parser, spanned::Spanned};
pub(crate) fn generated_module_path(
fn_path: &syn::Path,
) -> syn::punctuated::Punctuated<syn::PathSegment, syn::Token![::]> {
let mut g = fn_path.clone().segments;
g.pop();
let ident = syn::Ident::new(
&format!("rhai_fn_{}", fn_path.segments.last().unwrap().ident),
fn_path.span(),
);
g.push_value(syn::PathSegment {
ident,
arguments: syn::PathArguments::None,
});
g
}
type RegisterMacroInput = (syn::Expr, proc_macro2::TokenStream, syn::Path);
pub fn parse_register_macro(
args: proc_macro::TokenStream,
) -> Result<RegisterMacroInput, syn::Error> {
let parser = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_separated_nonempty;
let args = parser.parse(args).unwrap();
let arg_span = args.span();
let mut items: Vec<syn::Expr> = args.into_iter().collect();
if items.len() != 3 {
return Err(syn::Error::new(
arg_span,
"this macro requires three arguments",
));
}
let export_name = match &items[1] {
syn::Expr::Lit(litstr) => quote_spanned!(items[1].span()=>
#litstr.to_string()),
expr => quote! { #expr },
};
let rust_modpath = if let syn::Expr::Path(ref path) = &items[2] {
path.path.clone()
} else {
return Err(syn::Error::new(
items[2].span(),
"third argument must be a function name",
));
};
let module = items.remove(0);
Ok((module, export_name, rust_modpath))
}

View File

@ -16,7 +16,7 @@ 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!( rhai::set_exported_fn!(
m, m,
"euclidean_distance".to_string(), "euclidean_distance".to_string(),
raw_fn::distance_function raw_fn::distance_function
@ -50,7 +50,7 @@ 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::set_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));
@ -82,7 +82,7 @@ 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::set_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));
@ -138,9 +138,9 @@ mod mut_opaque_ref {
fn mut_opaque_ref_test() -> Result<(), Box<EvalAltResult>> { fn mut_opaque_ref_test() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
let mut m = Module::new(); let mut m = Module::new();
rhai::register_exported_fn!(m, "new_message", mut_opaque_ref::new_message); rhai::set_exported_fn!(m, "new_message", mut_opaque_ref::new_message);
rhai::register_exported_fn!(m, "new_os_message", mut_opaque_ref::new_os_message); rhai::set_exported_fn!(m, "new_os_message", mut_opaque_ref::new_os_message);
rhai::register_exported_fn!(m, "write_out_message", mut_opaque_ref::write_out_message); rhai::set_exported_fn!(m, "write_out_message", mut_opaque_ref::write_out_message);
let mut r = StaticModuleResolver::new(); let mut r = StaticModuleResolver::new();
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));
@ -174,7 +174,7 @@ fn rename_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, "add_two_floats", rename_fn::add_float); rhai::set_exported_fn!(m, "add_two_floats", rename_fn::add_float);
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));
@ -211,8 +211,8 @@ fn duplicate_fn_rename_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_two_floats", duplicate_fn_rename::add_float); rhai::set_exported_fn!(m, "add_two_floats", duplicate_fn_rename::add_float);
rhai::register_exported_fn!(m, "add_two_ints", duplicate_fn_rename::add_int); rhai::set_exported_fn!(m, "add_two_ints", duplicate_fn_rename::add_int);
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));
@ -224,7 +224,7 @@ fn duplicate_fn_rename_test() -> Result<(), Box<EvalAltResult>> {
let ix = 42; let ix = 42;
let iy = math::add_two_ints(ix, 1); let iy = math::add_two_ints(ix, 1);
[fy, iy] [fy, iy]
"# "#,
)?; )?;
assert_eq!(&output_array[0].as_float().unwrap(), &43.0); assert_eq!(&output_array[0].as_float().unwrap(), &43.0);
assert_eq!(&output_array[1].as_int().unwrap(), &43); assert_eq!(&output_array[1].as_int().unwrap(), &43);
@ -253,7 +253,7 @@ fn raw_returning_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!( rhai::set_exported_fn!(
m, m,
"euclidean_distance".to_string(), "euclidean_distance".to_string(),
raw_returning_fn::distance_function raw_returning_fn::distance_function

View File

@ -70,10 +70,7 @@ mod module;
mod optimize; mod optimize;
pub mod packages; pub mod packages;
mod parser; mod parser;
#[cfg(not(feature = "no_module"))]
pub mod plugin; pub mod plugin;
#[cfg(feature = "no_module")]
mod plugin;
mod result; mod result;
mod scope; mod scope;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]

View File

@ -11,8 +11,12 @@ pub use crate::{
ImmutableString, ImmutableString,
Module, Module,
Position, Position,
RegisterResultFn,
}; };
#[cfg(features = "no_module")]
pub use rhai_codegen::{export_fn, register_exported_fn};
#[cfg(not(features = "no_module"))]
pub use rhai_codegen::*; pub use rhai_codegen::*;
#[cfg(features = "sync")] #[cfg(features = "sync")]

17
tests/macro_register.rs Normal file
View File

@ -0,0 +1,17 @@
use rhai::plugin::*;
use rhai::{Engine, EvalAltResult, INT};
#[export_fn]
pub fn add_together(x: INT, y: INT) -> INT {
x + y
}
#[test]
fn test_exported_fn_register() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
register_exported_fn!(engine, "add_two", add_together);
assert_eq!(engine.eval::<INT>("let a = 1; add_two(a, 41)")?, 42);
Ok(())
}

View File

@ -33,9 +33,9 @@ macro_rules! register_in_bulk {
$( $(
{ {
let type_str = stringify!($type_names); let type_str = stringify!($type_names);
register_exported_fn!($mod_name, set_exported_fn!($mod_name,
format!(concat!(stringify!($op_name), "_{}"), type_str), format!(concat!(stringify!($op_name), "_{}"), type_str),
crate::$op_name::$type_names::op); crate::$op_name::$type_names::op);
} }
)* )*
} }

View File

@ -22,7 +22,7 @@ fn test_plugins_package() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
let mut m = exported_module!(special_array_package); let mut m = exported_module!(special_array_package);
register_exported_fn!(m, "greet", make_greeting); set_exported_fn!(m, "greet", make_greeting);
engine.load_package(m); engine.load_package(m);