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
214
215
216
217
218
219
220
#![allow(unused)]
extern crate proc_macro;

use quote::quote;
use syn::{
    Data,
    DataStruct,
    Fields,
    Field,
    Variant,
    FieldsUnnamed,
};
use generic_core::into::*;
use generic_core::value::*;



///////////////////////////////////////////////////////////////////////////////
// INTO-GENERIC ENTRYPOINT
///////////////////////////////////////////////////////////////////////////////

#[proc_macro_derive(IntoGeneric)]
pub fn into_generic_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast = syn::parse::<syn::DeriveInput>(input).expect("syn::parse failed");
    let type_name = ast.ident.clone();
    
    match ast.data.clone() {
        Data::Struct(DataStruct{fields: Fields::Named(named), ..}) => {
            let fields = named.named.into_iter().collect::<Vec<_>>();
            into_generic_struct(&type_name, &fields)
        }
        Data::Struct(DataStruct{fields: Fields::Unnamed(xs), ..}) => {
            into_generic_tuple_struct(&type_name, xs)
        }
        Data::Struct(DataStruct{fields: Fields::Unit, ..}) => {
            unimplemented!("Unit structs not yet supported")
        }
        Data::Enum(xs) => {
            let variants = xs.variants
                .into_iter()
                .collect::<Vec<_>>();
            into_generic_enum(&type_name, &variants)
        }
        Data::Union(_) => {
            unimplemented!("Union types not yet supported")
        }
    }
}


///////////////////////////////////////////////////////////////////////////////
// INTO-GENERIC - TUPLE-STRUCT
///////////////////////////////////////////////////////////////////////////////

fn into_generic_struct(type_name: &proc_macro2::Ident, fields: &[Field]) -> proc_macro::TokenStream {
    let field_conversions = fields
        .iter()
        .map(|field| {
            let field_ident = field.ident
                .clone()
                .expect("missing ident");
            quote! {
                let key = stringify!(#field_ident).to_owned();
                let value = IntoGeneric::into_generic(&self.#field_ident);
                map.insert(key, value);
            }
        })
        .collect::<Vec<_>>();
    let gen = quote! {
        impl IntoGeneric for #type_name {
            fn into_generic(&self) -> Value {
                use generic_core::into::*;
                use generic_core::value::*;

                let mut map: HashMap<String, Value> = std::collections::HashMap::new();
                #(#field_conversions)*
                Value::Struct(Struct {
                    type_name: String::from(stringify!(#type_name)),
                    data: map,
                })
            }
        }
    };
    gen.into()
}


///////////////////////////////////////////////////////////////////////////////
// INTO-GENERIC - TUPLE-STRUCT
///////////////////////////////////////////////////////////////////////////////

fn into_generic_tuple_struct(type_name: &proc_macro2::Ident, fields: FieldsUnnamed) -> proc_macro::TokenStream {
    let field_conversions = fields.unnamed
        .iter()
        .enumerate()
        .map(|(ix, _)| {
            let ix = syn::Index::from(ix);
            quote!{
                let value = IntoGeneric::into_generic(&self.#ix);
                vec.push(value);
            }
        })
        .collect::<Vec<_>>();
    let gen = quote! {
        impl IntoGeneric for #type_name {
            fn into_generic(&self) -> Value {
                use generic_core::into::*;
                use generic_core::value::*;

                let mut vec = Vec::<Value>::new();

                #(#field_conversions)*
                Value::TupleStruct(TupleStruct {
                    type_name: String::from(stringify!(#type_name)),
                    data: vec,
                })
            }
        }
    };
    gen.into()
}


///////////////////////////////////////////////////////////////////////////////
// INTO-GENERIC - ENUMS
///////////////////////////////////////////////////////////////////////////////

fn into_generic_enum(type_name: &proc_macro2::Ident, variants: &[Variant]) -> proc_macro::TokenStream {
    let arms = variants
        .iter()
        .map(|var| {
            let variant_name = &var.ident;
            match var.fields.clone() {
                Fields::Named(xs) => {
                    let (ident_binders, to_generics) = xs.named
                        .iter()
                        .map(|x| {
                            let ident = x.ident.clone().expect("todo - tuple structs");
                            let binder = quote!{
                                ref #ident,
                            };
                            let to_generic = quote!{
                                let key = stringify!(#ident).to_owned();
                                let value = IntoGeneric::into_generic(#ident);
                                map.insert(key, value);
                            };
                            (binder, to_generic)
                        })
                        .unzip::<_, _, Vec<_>, Vec<_>>();
                    quote! {
                        #type_name::#variant_name{#(#ident_binders)*} => {
                            let mut map = std::collections::HashMap::<String, Value>::new();

                            #(#to_generics)*
                            
                            Value::Variant(Variant::StructVariant {
                                type_name: stringify!(#type_name).to_owned(),
                                variant_name: stringify!(#variant_name).to_owned(),
                                data: map,
                            })
                        }
                    }
                },
                Fields::Unnamed(xs) => {
                    let (ident_binders, to_generics) = xs.unnamed
                        .iter()
                        .map(|_| {
                            let ident = format!("id_{}", rand::random::<u16>());
                            let ident = proc_macro2::Ident::new(&ident, proc_macro2::Span::call_site());
                            let binder = quote!{
                                ref #ident,
                            };
                            let to_generic = quote!{
                                let value = IntoGeneric::into_generic(#ident);
                                vec.push(value);
                            };
                            (binder, to_generic)
                        })
                        .unzip::<_, _, Vec<_>, Vec<_>>();
                    quote! {
                        #type_name::#variant_name(#(#ident_binders)*) => {
                            let mut vec = Vec::<Value>::new();

                            #(#to_generics)*
                            
                            Value::Variant(Variant::TupleVariant {
                                type_name: stringify!(#type_name).to_owned(),
                                variant_name: stringify!(#variant_name).to_owned(),
                                data: vec,
                            })
                        }
                    }
                },
                Fields::Unit => {
                    quote! {
                        #type_name::#variant_name => {
                            Value::Variant(Variant::UnitVariant{
                                type_name: stringify!(#type_name).to_owned(),
                                variant_name: stringify!(#variant_name).to_owned(),
                            })
                        }
                    }
                },
            }
        });
    let gen = quote! {
        impl IntoGeneric for #type_name {
            fn into_generic(&self) -> Value {
                use generic_core::into::*;
                use generic_core::value::*;

                match self {
                    #(#arms)*
                }
            }
        }
    };
    gen.into()
}