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
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
//! This crate provides Sai's component derive macros:
//!
//! ```ignore
//! use sai::{Component};
//! #[derive(Component)]
//! struct FooComponent {
//!     #[injected]
//!     bar: Injected<BarComponent>
//! }
//! ```
//!
//! Please refer the Component Trait doc to understand details.

/// Outer What is this?

extern crate proc_macro;
use proc_macro::TokenStream;
#[macro_use]
extern crate syn;
use syn::{DeriveInput, Data, Field};
use syn::Meta::{Path};
use syn::export::{TokenStream2};
#[macro_use]
extern crate quote;

mod symbol;
use symbol::*;


/// Dervive Macro for defining a component
#[proc_macro_derive(Component, attributes(injected, lifecycle))]
pub fn derive_component(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    // println!("{}", ast.attrs);
    let ident = &ast.ident;

    let fields = parse_struct_data(&ast.data);

    let fields_tokens = build_struct_fields(&fields);

    let depends_on_tokens = build_depends_on(&fields);

    let impl_lifecycle_tokens = build_impl_component_lifecycle(&ast);

    let tokens = quote!{
        impl sai::Component for #ident {
            fn build(registry: &sai::ComponentRepository) -> #ident {
                return #ident {
                    #fields_tokens
                }

            }

            // Used during topology sort to calculate DAG
            fn meta() -> sai::ComponentMeta<std::boxed::Box<#ident>> {

                return sai::ComponentMeta {
                    type_id: std::any::TypeId::of::<sai::Injected<#ident>>(),
                    depends_on: #depends_on_tokens,
                    build: std::boxed::Box::new(
                        |repo: &sai::ComponentRepository| std::boxed::Box::new(#ident::build(repo))
                    )
                }
            }
        }

        #impl_lifecycle_tokens
    };

    return tokens.into();
}

fn build_struct_fields (fields: &Vec<ComponentField>) -> TokenStream2 {

    let x: Vec<TokenStream2> = fields
        .into_iter()
        .map(|f| {
            let ident = &f.ident;
            let ty = &f.ty; // expecting Injected<Bluh>
            if f.injected {
                let error_msg_type_not_found = format!("Unable to find type {} in component repository", quote!{#ty});
                let error_msg_cast_failure = format!("Found {} in component repository. But unable to downcast it", quote!{#ty});

                return quote! {
                    #ident: {
                        let comp: &sai::Injected::<dyn sai::Component> = registry.get_by_typeid(std::any::TypeId::of::<#ty>()).expect(#error_msg_type_not_found);
                        let dep: #ty = comp.clone().downcast().expect(#error_msg_cast_failure);
                        dep
                    }
                }
            } else {
                return quote! {
                    #ident: Default::default()
                }
            }
        })
        .collect();


    quote!{
        #(#x),*
    }
}

fn build_depends_on(fields: &Vec<ComponentField>) -> TokenStream2 {

    let x: Vec<TokenStream2> = fields
        .into_iter()
        .filter(|f| f.injected)
        .map(|f| {
            let ty = &f.ty;
            return quote! {
                std::any::TypeId::of::<#ty>()
            }
        })
        .collect();

    quote! {
        vec![ #(#x),* ]
    }
}

fn build_impl_component_lifecycle(ast: &DeriveInput) -> TokenStream2 {
    let ident = &ast.ident;

    if is_lifecycle_mode(ast) {
        return quote! {}
    } else {
        return quote! {
            impl sai::ComponentLifecycle for #ident {}
        }
    }
}

fn is_lifecycle_mode(ast: &DeriveInput) -> bool {
    return ast
        .attrs
        .iter()
        .map(|attr| attr.path == LIFECYCLE)
        .any(|i| i);
}


struct ComponentField {
    injected: bool,
    ident: syn::Ident,
    ty: syn::Type
}

fn parse_struct_data (data: &Data) -> Vec<ComponentField> {

    let s = match data {
        Data::Struct(s) => s,
        _ => panic!("Component macro can only be used on struct enum")
    };


    let fields = match &s.fields {
        syn::Fields::Named(f) => f,
        syn::Fields::Unit => return Vec::new(),
        _ => panic!("Component marco can not be used on tuple struct")
    };
    let fields = &fields.named;

    return fields
        .iter()
        .map(parse_struct_field)
        .collect::<Vec<ComponentField>>();
}

fn parse_struct_field (field: &Field) -> ComponentField {

    let ty = field.ty.clone();
    let ident = field.ident.clone().unwrap();
    let attrs = &field.attrs;

    let injected = attrs
        .iter()
        .map(|attr| is_injected_attribute(attr))
        .any(|i| match i {
            Ok(v) => v,
            Err(_) => false // TODO: improve error handling
        });


    return ComponentField {
        injected,
        ident,
        ty
    }
}

fn is_injected_attribute(attr: &syn::Attribute) -> Result<bool, ()> {
    if attr.path != INJECTED {
        return Ok(false)
    }

    match attr.parse_meta() {
        Ok(Path(_)) => Ok(true), // Only expect #[injected]
        Ok(_) => Err(()), // TODO: improve error handling
        Err(_) => Err(()) // TODO: improve error handling
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}