Use procedural macros to define events

The construction of an EventHandler object should not be directly done
by the client. Instead, it is easier to use procedural macro to
automatize the process, hence exposing a nice and simple interface. Such
use of procedural macros requires to crate an additional crate.
This commit is contained in:
Rodolphe Breard 2019-01-06 15:41:30 +01:00
parent ccda4b1517
commit 789455668c
17 changed files with 1190 additions and 76 deletions

View file

@ -0,0 +1,21 @@
extern crate proc_macro;
use proc_macro::TokenStream;
use syn::{parse_macro_input, ItemFn};
use quote::quote;
#[proc_macro_attribute]
pub fn event(attr: TokenStream, input: TokenStream) -> TokenStream {
let attr = attr.to_string();
let item = parse_macro_input!(input as ItemFn);
let fn_name = &item.ident;
let fn_params = &item.decl.inputs;
let fn_body = &item.block;
let fn_output = &item.decl.output;
let output = quote! {
fn #fn_name() -> EventHandler {
EventHandler::new(#attr.to_string(), |#fn_params| #fn_output #fn_body)
}
};
output.into()
}