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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! This is a derive procedural macro that will let you add custom derive
//! and attributes over structs, enums and unions. This derive will add two impl on the
//! type. The `as_string()` method returns a json serialized string representation of the type
//! with any meta information annotated with `structype_meta("key"=val)` attribute,
//! while the `print_fields()` method will print the same to STDOUT.
//! This macro will panic at compile time if annotated over tuple and unit structs.
//!
//! ## Example:
//! ```
//! use structype_derive::StrucType;
//! #[derive(StrucType)]
//! // #[structype_meta("labelover_ride=name")] This will panic the macro
//! struct UserStruct {
//!     #[structype_meta(override_name="Primary ID", order="1")]
//!     id: i64,
//!     #[structype_meta(override_name="name", order="0")]
//!     username: String,
//!     org: String,
//!     details: Details,
//! }
//!
//! #[derive(StrucType)]
//! struct Details {
//!     user_attributes: std::collections::HashMap<String, String>,
//! }
//!
//! fn print_struct_fields() {
//!     UserStruct::print_fields();
//!     let data = UserStruct::as_string();
//!     println!("{}", data);
//!     Details::print_fields();
//!     let data = Details::as_string();
//!     println!("{}", data);
//! }
//! ```
//! The above will generate and return a json serialized string representation where the key is
//! the struct's field name and the value is a `HashMap<String, String>` of `structype_meta`'s key-val. If the `structype_meta` is
//! absent, the field's associated value would be an empty `{}`.
//!
//! # Output:
//! ```json
//! [
//!     {
//!         "field_name": "id",
//!         "meta": {
//!             "order": "1",
//!             "override_name": "Primary ID"
//!         }
//!     },
//!     {
//!         "field_name": "username",
//!         "meta": {
//!             "override_name": "name",
//!             "order": "0"
//!         }
//!     },
//!     {
//!         "field_name": "org",
//!         "meta": {}
//!     },
//!     {
//!         "field_name": "details",
//!         "meta": {}
//!     }
//! ]
//! ```
//!
//! If this serialized string needs to be deserialized into a struct, use the same type used here
//!
//! ## cargo.toml:
//!
//! ```toml
//! structype = "3.0.0"
//! ```
//!
//! ## Example:
//!
//! ```rust
//! use structype::TypeMapVec;
//! use structype_derive::StrucType;
//!
//! #[derive(StrucType)]
//! struct UserStruct {
//!     #[structype_meta(override_name="Primary ID", order="1")]
//!     id: i64,
//! }
//!
//! fn print_struct_fields() {
//!     UserStruct::print_fields();
//!     let data: TypeMapVec = serde_json::from_str(&UserStruct::as_string()).unwrap();
//!     println!("Deserialized: {:?}", data);
//! }
//!
//! ```
//!

use proc_macro::{self, TokenStream};
use quote::quote;
use std::collections::HashMap;
use structype::{TypeMap, TypeMapVec};
use syn::{parse_macro_input, DataEnum, DataUnion, DeriveInput, FieldsNamed};

#[proc_macro_derive(StrucType, attributes(structype_meta))]
pub fn structmap(input: TokenStream) -> TokenStream {
    let ast: DeriveInput = parse_macro_input!(input);
    let name = &ast.ident;
    let top_attr = &ast.attrs;
    for attr in top_attr.iter() {
        let meta = attr.parse_meta();
        match meta {
            _ => panic!("Cannot apply attribute outside a type. Applicable only inside the type on type fields."),
        }
    }

    let description = match &ast.data {
        syn::Data::Struct(s) => {
            match &s.fields {
                syn::Fields::Named(FieldsNamed { named, .. }) => {
                    let mut structype_map: TypeMapVec = Vec::new();
                    let iters = named.iter().map(|f| (&f.ident, &f.attrs));
                    for (if_ident, attrs) in iters {
                        if let Some(ident) = if_ident {
                            if !attrs.is_empty() {
                                let mut record = TypeMap {
                                    field_name: ident.to_string(),
                                    meta: HashMap::new(),
                                };
                                for attr in attrs.iter() {
                                    let meta = attr.parse_meta().unwrap();
                                    match meta {
                                        syn::Meta::List(metalist) => {
                                            let pairs = metalist
                                                .nested
                                                .into_pairs()
                                                .map(|pair| pair.into_value());
                                            for pair in pairs {
                                                match pair {
                                                syn::NestedMeta::Meta(meta) => match meta {
                                                    syn::Meta::Path(_) => {panic!(r#"invalid. Use the format structype_meta(label="foo", ord="10")"#)}
                                                    syn::Meta::List(_) => {panic!(r#"invalid. Use the format structype_meta(label="foo", ord="10")"#)}
                                                    syn::Meta::NameValue(meta_nameval) => {
                                                        let path = meta_nameval.path;
                                                        match meta_nameval.lit {
                                                            syn::Lit::Str(str_lit) => {

                                                                record.meta.insert(path.get_ident().unwrap().to_string(), str_lit.value());
                                                            }
                                                            _ => {panic!("Only string type is supported now")}
                                                        }
                                                    }
                                                }
                                                syn::NestedMeta::Lit(_) => {panic!("Lit is not applicable. Annotate as key-value")}
                                            }
                                            }
                                            structype_map.push(record.clone());
                                        }

                                        _ => panic!(
                                            r#"Not applicable. Present a list of key-value attributes like structype_meta(label="foo", ord="10")"#
                                        ),
                                        // syn::Meta::Path(_) => {}
                                    }
                                }
                            } else {
                                let val = TypeMap {
                                    field_name: ident.to_string(),
                                    meta: HashMap::new(),
                                };
                                structype_map.push(val);
                            }
                        }
                    }
                    serde_json::to_string(&structype_map).unwrap()
                }
                syn::Fields::Unnamed(_) => panic!("Not applicable to Tuple structs"),

                syn::Fields::Unit => panic!("Not applicable to Unit structs"),
            }
        }
        // Enums parsing starts here
        syn::Data::Enum(DataEnum { variants, .. }) => {
            let mut structype_map: TypeMapVec = Vec::new();
            let iters = variants.iter().map(|f| (&f.ident, &f.attrs));
            for (if_ident, attrs) in iters {
                if !attrs.is_empty() {
                    let mut record = TypeMap {
                        field_name: if_ident.to_string(),
                        meta: HashMap::new(),
                    };
                    for attr in attrs.iter() {
                        let meta = attr.parse_meta().unwrap();
                        match meta {
                            syn::Meta::List(metalist) => {
                                let pairs =
                                    metalist.nested.into_pairs().map(|pair| pair.into_value());
                                for pair in pairs {
                                    match pair {
                                        syn::NestedMeta::Meta(meta) => match meta {
                                            syn::Meta::Path(_) => {
                                                panic!(r#"invalid. Add as key="value#""#)
                                            }
                                            syn::Meta::List(_) => {
                                                panic!(r#"invalid. Add as key="value#""#)
                                            }
                                            syn::Meta::NameValue(meta_nameval) => {
                                                let path = meta_nameval.path;
                                                match meta_nameval.lit {
                                                    syn::Lit::Str(str_lit) => {
                                                        record.meta.insert(
                                                            path.get_ident().unwrap().to_string(),
                                                            str_lit.value(),
                                                        );
                                                    }
                                                    _ => {
                                                        panic!("Only string type is supported now")
                                                    }
                                                }
                                            }
                                        },
                                        syn::NestedMeta::Lit(_) => {
                                            panic!("Lit is not applicable. Annotate as key-value")
                                        }
                                    }
                                }
                                structype_map.push(record.clone());
                            }

                            _ => panic!(
                                r#"Not applicable. Present a list of key-value attributes like structype_meta(label="foo", ord="10")"#
                            ),
                            // syn::Meta::Path(_) => {}
                        }
                    }
                } else {
                    let val = TypeMap {
                        field_name: if_ident.to_string(),
                        meta: HashMap::new(),
                    };
                    structype_map.push(val);
                }
            }
            serde_json::to_string(&structype_map).unwrap()
        }
        syn::Data::Union(DataUnion {
            fields: FieldsNamed { named, .. },
            ..
        }) => {
            let mut structype_map: TypeMapVec = Vec::new();
            let iters = named.iter().map(|f| (&f.ident, &f.attrs));
            for (if_ident, attrs) in iters {
                if let Some(ident) = if_ident {
                    if !attrs.is_empty() {
                        let mut record = TypeMap {
                            field_name: ident.to_string(),
                            meta: HashMap::new(),
                        };
                        for attr in attrs.iter() {
                            let meta = attr.parse_meta().unwrap();
                            match meta {
                                syn::Meta::List(metalist) => {
                                    let pairs =
                                        metalist.nested.into_pairs().map(|pair| pair.into_value());
                                    for pair in pairs {
                                        match pair {
                                            syn::NestedMeta::Meta(meta) => match meta {
                                                syn::Meta::Path(_) => panic!(
                                                    r#"invalid. Use the format structype_meta(label="foo", ord="10")"#
                                                ),
                                                syn::Meta::List(_) => panic!(
                                                    r#"invalid. Use the format structype_meta(label="foo", ord="10")"#
                                                ),
                                                syn::Meta::NameValue(meta_nameval) => {
                                                    let path = meta_nameval.path;
                                                    match meta_nameval.lit {
                                                        syn::Lit::Str(str_lit) => {
                                                            record.meta.insert(
                                                                path.get_ident()
                                                                    .unwrap()
                                                                    .to_string(),
                                                                str_lit.value(),
                                                            );
                                                        }
                                                        _ => panic!(
                                                            "Only string type is supported now"
                                                        ),
                                                    }
                                                }
                                            },
                                            syn::NestedMeta::Lit(_) => panic!(
                                                r#"Literal is not applicable. Annotate as key-value like structype_meta(label="foo#", ord="10")"#
                                            ),
                                        }
                                    }
                                    structype_map.push(record.clone());
                                }

                                _ => panic!(
                                    r#"Not applicable. Present a list of key-value attributes like structype_meta(label="foo", ord="10")"#
                                ),
                            }
                        }
                    } else {
                        let val = TypeMap {
                            field_name: ident.to_string(),
                            meta: HashMap::new(),
                        };
                        structype_map.push(val);
                    }
                }
            }
            serde_json::to_string(&structype_map).unwrap()
        }
    };

    let output = quote! {
    impl #name {
        pub fn print_fields() {
        println!("{}", #description);
        }

        pub fn as_string() -> String {
            return #description.to_string()
        }
    }
    };

    output.into()
}