1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
extern crate game_kernel_ecs;

use game_kernel_ecs::ecs::component::Component;

extern crate proc_macro;

use crate::proc_macro::TokenStream;
use quote::quote;
use syn;

#[proc_macro_derive(Component)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
    // Construct a representation of Rust code as a syntax tree
    // that we can manipulate
    let ast = syn::parse(input).unwrap();

    // Build the trait implementation
    impl_component_macro(&ast)
}

fn impl_component_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let gen = quote! {
        impl Component for #name {
            fn get_name() -> String where Self: Sized{
                stringify!(#name).to_owned()
            }

            fn get_builder() -> fn(args: HashMap<String, Arc<dyn Any + 'static + Send + Sync>>)-> Result<Arc<std::cell::RefCell<dyn Component>>, ComponentCreationError>
            {
                |args|{#name::component_new(args)}
            }

            fn into_any(self: Box<Self>) -> Box<dyn Any>
            {
                self
            }

            fn gk_as_any(&self) -> &dyn Any
            {
                self
            }

            fn gk_as_any_mut(&mut self) -> &mut dyn Any
            {
                self
            }
        }
    };
    gen.into()
}