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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, DeriveInput, Field, Ident, Lit, Meta, NestedMeta, Type};

fn is_duplicated(f: &Field) -> bool {
    f.attrs
        .iter()
        .filter(|attr| attr.path.is_ident("jomini"))
        .map(|attr| attr.parse_meta().unwrap())
        .filter_map(|meta| match meta {
            Meta::List(x) => Some(x),
            _ => None,
        })
        .flat_map(|x| x.nested)
        .filter_map(|x| match x {
            NestedMeta::Meta(m) => Some(m.path().clone()),
            _ => None,
        })
        .filter(|p| p.is_ident("duplicated"))
        .any(|_| true)
}

enum DefaultFallback {
    Path(Ident),
    Yes,
    No,
}

fn can_default(f: &Field) -> DefaultFallback {
    if let Type::Path(x) = ungroup(&f.ty) {
        for segment in x.path.segments.iter() {
            if segment.ident == Ident::new("Option", segment.ident.span()) {
                return DefaultFallback::Yes;
            }
        }
    }

    let defattr = f
        .attrs
        .iter()
        .filter(|attr| attr.path.is_ident("jomini"))
        .map(|attr| attr.parse_meta().unwrap())
        .filter_map(|meta| match meta {
            Meta::List(x) => Some(x),
            _ => None,
        })
        .flat_map(|x| x.nested)
        .filter_map(|x| match x {
            NestedMeta::Meta(m) => Some(m),
            _ => None,
        })
        .find(|m| m.path().is_ident("default"));

    defattr
        .map(|meta| match meta {
            Meta::NameValue(mnv) => {
                if let Lit::Str(lit) = mnv.lit {
                    DefaultFallback::Path(lit.parse().unwrap())
                } else {
                    panic!("expected default function to be a string");
                }
            }
            _ => DefaultFallback::Yes,
        })
        .unwrap_or(DefaultFallback::No)
}

fn can_deserialize_with(f: &Field) -> Option<Ident> {
    let defattr = f
        .attrs
        .iter()
        .filter(|attr| attr.path.is_ident("jomini"))
        .map(|attr| attr.parse_meta().unwrap())
        .filter_map(|meta| match meta {
            Meta::List(x) => Some(x),
            _ => None,
        })
        .flat_map(|x| x.nested)
        .filter_map(|x| match x {
            NestedMeta::Meta(m) => Some(m),
            _ => None,
        })
        .find(|m| m.path().is_ident("deserialize_with"));

    defattr.map(|meta| match meta {
        Meta::NameValue(mnv) => {
            if let Lit::Str(lit) = mnv.lit {
                lit.parse().unwrap()
            } else {
                panic!("expected deserialize_with function to be a string");
            }
        }
        _ => panic!("expected name value for deserialize_with"),
    })
}

fn alias(f: &Field) -> Option<String> {
    f.attrs
        .iter()
        .filter(|attr| attr.path.is_ident("jomini"))
        .map(|attr| attr.parse_meta().unwrap())
        .filter_map(|meta| match meta {
            Meta::List(x) => Some(x),
            _ => None,
        })
        .flat_map(|x| x.nested)
        .filter_map(|x| match x {
            NestedMeta::Meta(m) => Some(m),
            _ => None,
        })
        .filter(|m| m.path().is_ident("alias"))
        .filter_map(|meta| match meta {
            Meta::NameValue(mnv) => Some(mnv),
            _ => None,
        })
        .filter_map(|mnv| match mnv.lit {
            Lit::Str(s) => Some(s.value()),
            _ => None,
        })
        .next()
}

fn ungroup(mut ty: &Type) -> &Type {
    while let Type::Group(group) = ty {
        ty = &group.elem;
    }
    ty
}

/// Creates a serde compatible `Deserialize` implementation
///
/// ```rust
/// use jomini_derive::JominiDeserialize;
///
/// #[derive(JominiDeserialize)]
/// pub struct Model {
///     #[jomini(default = "default_true")]
///     human: bool,
///     first: Option<u16>,
///     #[jomini(alias = "forth")]
///     fourth: u16,
///     #[jomini(alias = "core", duplicated)]
///     cores: Vec<String>,
///     names: Vec<String>,
/// }
///
/// fn default_true() -> bool {
///     true
/// }
/// ```
///
/// ## The What
///
/// Most rust programmers should be already familiar with serde's `Deserialize` derive macro. If
/// not, [read the serde docs](https://serde.rs/derive.html).
///
/// The `JominiDeserialize` macro produces an implementation for the serde `Deserialize` trait.
///
/// When unadored with field attributes, both `JominiDeserialize` and `Deserialize` would produce
/// extremely similar `Deserialize` implementations. It's a goal for `JominiDeserialize` to be as
/// compatible as possible.
///
/// The value add for `JominiDeserialize` is the `#[jomini(duplicated)]` field attribute, which can
/// decorate a `Vec<T>` field. The `duplicated` attribute will allow multiple instances of the
/// field, no matter how far separated they are in the data, to be aggregated into a single vector.
/// See "The Why" section below for further info.
///
/// In addition to the `duplicated` attribute, several of the most common serde attributes have
/// been implemented:
///
/// - `#[jomini(alias = "abc")]`
/// - `#[jomini(default)]`
/// - `#[jomini(default = "...")]`
/// - `#[jomini(deserialize_with = "...")]`
///
/// ## The Why
///
/// Serde's `Deserialize` implementation will raise an error if a field occurs more than once in
/// the data like shown below:
///
/// ```json
/// {
///    "core": "core1",
///    "nums": [1, 2, 3, 4, 5],
///    "core": "core2"
/// }
/// ```
///
/// The `core` field occurs twice in the JSON and serde will be unable to aggregate that into a
/// `Vec<String>` by itself. See this [serde issue](https://github.com/serde-rs/serde/issues/1859)
/// for more information.
///
/// Initial implementations that used the `Deserialize` derive macro natively required a
/// translation layer that would present the aggregated fields to `serde`. This translation layer
/// could have a heavy cost especially as documents increased in size.
///
/// Thus the need was born to be able to generate a `Deserialize` implementation that could
/// aggregate fields. This is why there is a `JominiDeserialize` derive macro and `duplicated` and
/// field attribute.
///
/// ## When to Use
///
/// `JominiDeserialize` is not intended to replace the `Deserialize` derive macro, as
/// `JominiDeserialize` has an incredibly narrow scope -- to allow efficient deserialization of
/// duplicated and non-consecutive fields. Many field / container attributes are not implemented
/// for `JominiDeserialize`, so when needed opt to use serde's `Deserialize` derive macro.
///
/// Since both macros result in an implementation of the `Deserialize` trait for the given data
/// structure, these macros can be used
#[proc_macro_derive(JominiDeserialize, attributes(jomini))]
pub fn derive(input: TokenStream) -> TokenStream {
    let dinput = parse_macro_input!(input as DeriveInput);
    let struct_ident = dinput.ident;

    let syn_struct = match dinput.data {
        syn::Data::Struct(x) => x,
        _ => panic!("Expected struct"),
    };

    let named_fields = match syn_struct.fields {
        syn::Fields::Named(x) => x,
        _ => panic!("Expected named fields"),
    };

    let builder_init = named_fields.named.iter().map(|f| {
        let name = &f.ident;
        let x = &f.ty;
        if !is_duplicated(f) {
            let field_name_opt = format_ident!("{}_opt", name.as_ref().unwrap());
            quote! { let mut #field_name_opt : ::std::option::Option<#x> = None }
        } else {
            quote! { let mut #name : #x = Default::default() }
        }
    });

    let builder_fields = named_fields.named.iter().map(|f| {
        let name = &f.ident;
        let x = &f.ty;
        let name_str = name
            .as_ref()
            .map(|x| x.to_string())
            .unwrap_or_else(|| String::from("unknown"));
        let match_arm = quote! { __Field::#name };

        if !is_duplicated(f) {
            let field_name_opt = format_ident!("{}_opt", name.as_ref().unwrap());

            let des = if let Some(ident) = can_deserialize_with(f) {
                let fncall = quote! { #ident(__deserializer) };
                quote! {{
                    struct __DeserializeWith {
                        value: #x,
                    }
                    impl<'de> ::serde::Deserialize<'de> for __DeserializeWith {
                        fn deserialize<__D>(
                            __deserializer: __D,
                        ) -> ::std::result::Result<Self, __D::Error>
                        where
                            __D: ::serde::Deserializer<'de>,
                        {
                            Ok(__DeserializeWith { value: #fncall? })
                        }
                    }
                    ::serde::de::MapAccess::next_value::<
                        __DeserializeWith,
                    >(&mut __map).map(|x| x.value)
                }}
            } else {
                quote! { serde::de::MapAccess::next_value::<#x>(&mut __map) }
            };

            quote! {
                #match_arm => match #field_name_opt {
                    None => #field_name_opt = Some(#des?),
                    _ => { return Err(<__A::Error as ::serde::de::Error>::duplicate_field(#name_str)); }
                }
            }
        } else {
            let path = match ungroup(x) {
                syn::Type::Path(ty) => &ty.path,
                _ => panic!("expected path"),
            };
            let seg = match path.segments.last() {
                Some(seg) => seg,
                None => panic!("expected segment"),
            };
            let args = match &seg.arguments {
                syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args,
                _ => panic!("expected brackets"),
            };

            let farg = &args[0];

            quote! {
                #match_arm => { (#name).push(serde::de::MapAccess::next_value::<#farg>(&mut __map)?); }
            }
        }
    });

    let field_extract =  named_fields.named.iter().filter(|x| !is_duplicated(x)).map(|f| {
        let name = &f.ident;
        let field_name_opt = format_ident!("{}_opt", name.as_ref().unwrap());
        let name_str = name
            .as_ref()
            .map(|x| x.to_string())
            .unwrap_or_else(|| String::from("unknown"));

        match can_default(f) {
            DefaultFallback::Yes => quote! {
                let #name = (#field_name_opt).unwrap_or_default();
            },
            DefaultFallback::Path(lit) => quote! {
                let #name = (#field_name_opt).unwrap_or_else(#lit);
            },
            DefaultFallback::No => quote! {
                let #name = (#field_name_opt)
                    .ok_or_else(|| <__A::Error as ::serde::de::Error>::missing_field(#name_str))?;
            }
        }
    });

    let field_constructor = named_fields.named.iter().map(|f| {
        let name = &f.ident;
        quote! { #name }
    });

    let field_enums = named_fields.named.iter().map(|f| {
        let name = &f.ident;
        quote! { #name }
    });

    let field_enum_match = named_fields.named.iter().map(|f| {
        let name = &f.ident;
        let name_str = name
            .as_ref()
            .map(|x| x.to_string())
            .unwrap_or_else(|| String::from("unknown"));
        let match_arm = alias(f).unwrap_or_else(|| name_str.to_string());
        let field_ident = quote! { __Field::#name };
        quote! {
            #match_arm => Ok(#field_ident)
        }
    });

    let expecting = format!("struct {}", struct_ident.to_string());
    let struct_ident_str = struct_ident.to_string();

    let field_names: Vec<_> = named_fields
        .named
        .iter()
        .map(|field| {
            field
                .ident
                .as_ref()
                .map(|x| x.to_string())
                .unwrap_or_else(|| String::from("unknown"))
        })
        .collect();

    let output = quote! {
        impl<'de> ::serde::Deserialize<'de> for #struct_ident {
            fn deserialize<__D>(__deserializer: __D) -> ::std::result::Result<Self, __D::Error>
            where __D: ::serde::Deserializer<'de> {
                #[allow(non_camel_case_types)]
                enum __Field {
                    #(#field_enums),* ,
                    __ignore,
                };

                struct __FieldVisitor;
                impl<'de> ::serde::de::Visitor<'de> for __FieldVisitor {
                    type Value = __Field;
                    fn expecting(
                        &self,
                        __formatter: &mut ::std::fmt::Formatter,
                    ) -> ::std::fmt::Result {
                        write!(__formatter, "field identifier")
                    }
                    fn visit_str<__E>(
                        self,
                        __value: &str,
                    ) -> ::std::result::Result<Self::Value, __E>
                    where
                        __E: ::serde::de::Error,
                    {
                        match __value {
                            #(#field_enum_match),* ,
                            _ => Ok(__Field::__ignore),
                        }
                    }
                }

                impl<'de> serde::Deserialize<'de> for __Field {
                    #[inline]
                    fn deserialize<__D>(
                        __deserializer: __D,
                    ) -> std::result::Result<Self, __D::Error>
                    where
                        __D: ::serde::Deserializer<'de>,
                    {
                        ::serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor)
                    }
                }

                struct __Visitor;

                impl<'de> ::serde::de::Visitor<'de> for __Visitor {
                    type Value = #struct_ident;

                    fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                        write!(formatter, #expecting)
                    }

                    #[inline]
                    fn visit_map<__A>(
                        self,
                        mut __map: __A,
                    ) -> ::std::result::Result<Self::Value, __A::Error>
                    where
                        __A: ::serde::de::MapAccess<'de>,
                    {
                        #(#builder_init);* ;

                        while let Some(__key) = ::serde::de::MapAccess::next_key::<__Field>(&mut __map)? {
                            match __key {
                                #(#builder_fields),*
                                _ => { ::serde::de::MapAccess::next_value::<::serde::de::IgnoredAny>(&mut __map)?; }
                            }
                        }

                        #(#field_extract);* ;

                        Ok(#struct_ident {
                            #(#field_constructor),*
                        })
                    }
                }

                const FIELDS: &'static [&'static str] = &[ #(#field_names),* ];
                ::serde::de::Deserializer::deserialize_struct(
                    __deserializer,
                    #struct_ident_str,
                    FIELDS,
                    __Visitor
                )
            }
        }
    };
    output.into()
}