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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use proc_macro::TokenStream;
use quote::{format_ident, quote};

#[proc_macro_derive(Fillable)]
pub fn fillable_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
    let impl_fillable = impl_fillable_macro(&ast);
    let gen = quote! {
        #impl_fillable
    };
    gen.into()
}

fn impl_fillable_macro(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {
    let name = &ast.ident;
    quote! {
        impl Fillable for #name {
        }
    }
}

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

    // Build the trait implementation
    let gen = quote! {
        impl PartialEq for #name {
            fn eq(&self, other: &Self) -> bool {
                self.id == other.id
            }
        }

        impl std::hash::Hash for #name {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                self.id.hash(state);
            }
        }
    };
    gen.into()
}

/// Implement Filler to fill itself
/// This will implement `Impl Filler<Self, Self> for Self`
#[proc_macro_derive(Filler)]
pub fn filler_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
    let impl_filler_self = impl_filler_self_macro(&ast);
    let gen = quote! {
        #impl_filler_self
    };
    gen.into()
}

fn impl_filler_self_macro(ast: &syn::DeriveInput) -> proc_macro2::TokenStream {
    let name = &ast.ident;
    let fields = get_struct_fields(&ast);
    let list_add_missing_data = list_add_missing_data(&fields);
    let list_never_replace_data = list_never_replace_data(&fields);
    let list_replace_data = list_replace_data(&fields);
    quote! {
        impl Filler<#name, #name> for #name{
            fn add_missing_data(&mut self, source: &#name) {
                if !self.check_mergeable(source) { return }
                #list_add_missing_data
            }
            fn never_replace_data(&mut self, source: &#name) {
                if !self.check_mergeable(source) { return }
                #list_never_replace_data
            }
            fn replace_data(&mut self, source: &#name) {
                // Do not do check here as nested items can
                // never be merged with de default values otherwise.
                //if !self.check_mergeable(source) { return }
                #list_replace_data
            }
        }
    }
}

fn list_add_missing_data(struct_fields: &[&syn::Field]) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (_i, field) in struct_fields.iter().enumerate() {
        let ident = field.ident.as_ref().unwrap();
        parse_gen = quote! {
            #parse_gen
            // Generated example:
            // self.id.add_missing_data(&source.id);
            self.#ident.add_missing_data(&source.#ident);
        };
    }
    parse_gen
}

fn list_never_replace_data(struct_fields: &[&syn::Field]) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (_i, field) in struct_fields.iter().enumerate() {
        let ident = field.ident.as_ref().unwrap();
        parse_gen = quote! {
            #parse_gen
            // Generated example:
            // self.id.never_replace_data(&source.id);
            self.#ident.never_replace_data(&source.#ident);
        };
    }
    parse_gen
}

fn list_replace_data(struct_fields: &[&syn::Field]) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (_i, field) in struct_fields.iter().enumerate() {
        let ident = field.ident.as_ref().unwrap();
        parse_gen = quote! {
            #parse_gen
            // Generated example:
            // self.id.replace_data(&source.id);
            self.#ident.replace_data(&source.#ident);
        };
    }
    parse_gen
}

#[proc_macro_derive(HasUnknown, attributes(unknown_list))]
pub fn has_unknown_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_has_unknown_macro(&ast)
}

fn impl_has_unknown_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let data = get_struct_data(&ast);
    // create a list of all fields in struct and call
    // `print_unknown()` on that data element
    let mut parse_gen = quote! {};
    for (field, _type) in &data {
        parse_gen = quote! {
            #parse_gen
            self.#field.print_unknown(&prefix, unknown_map);
        }
    }
    // `combine_unknown()` on that data element
    let mut parse_gen2 = quote! {};
    for (field, _type) in &data {
        parse_gen2 = quote! {
            #parse_gen2
            self.#field.combine_unknown(&prefix, unknown_combiner);
        }
    }
    // Build impl
    let gen = quote! {
        impl HasUnknown for #name {
            fn print_unknown(&self, prefix: &str, unknown_map: &mut HashMap<String, u32>){
                // update prefix
                let prefix = self.update_unknown_prefix(prefix,stringify!(#name));
                // add list of calls to `print_unknown()` for each field
                #parse_gen
                // print list of everything in `self.unknown` if anything is there
                self.print_unknown_list(&self.unknown, &prefix, unknown_map);
            }
            fn combine_unknown(&self, prefix: &str, unknown_combiner: &mut HashMap<String, Vec<(String, Value)>>){
                // update prefix
                let prefix = self.update_unknown_prefix(prefix,stringify!(#name));
                // add list of calls to `combine_unknown()` for each field
                #parse_gen2
                // print list of everything in `self.unknown` if anything is there
                self.combine_unknown_list(&self.unknown, &prefix, unknown_combiner);
            }
        }
    };
    gen.into()
}

/// Get a list of all the items in the Struct
/// Example
/// ```ignore
/// Point{
///     x: i32,
///     y: i32,
/// }
/// ```
/// Will return `[("x",i32),("y",i32)]` but then as an `(syn::Ident,syn::Type)`
fn get_struct_data(ast: &syn::DeriveInput) -> Vec<(&syn::Ident, &syn::Type)> {
    let mut list = Vec::new();
    match &ast.data {
        syn::Data::Struct(x) => match &x.fields {
            syn::Fields::Named(x) => {
                for field in &x.named {
                    list.push((field.ident.as_ref().unwrap(), &field.ty));
                }
                Some(())
            }
            syn::Fields::Unnamed(_) => None,
            syn::Fields::Unit => None,
        },
        syn::Data::Enum(_x) => None,
        syn::Data::Union(_x) => None,
    };
    list
}

/// Similar to `get_struct_data` but creates a list of `Field`s the contains the whole line.
/// Example
/// ```ignore
/// Point{
///     x: i32,
///     y: i32,
/// }
/// ```
/// Will return `[{ident:x, type:i32,...},{ident:y, type:i32,...}]` but then as an `syn::Field`
fn get_struct_fields(ast: &syn::DeriveInput) -> Vec<&syn::Field> {
    let mut list = Vec::new();
    match &ast.data {
        syn::Data::Struct(x) => match &x.fields {
            syn::Fields::Named(x) => {
                for field in &x.named {
                    list.push(field);
                }
                Some(())
            }
            syn::Fields::Unnamed(_) => None,
            syn::Fields::Unit => None,
        },
        syn::Data::Enum(_x) => None,
        syn::Data::Union(_x) => None,
    };
    list
}

// -------------- DeserializeBestEffort -------------------

#[proc_macro_derive(DeserializeBestEffort, attributes(serde))]
pub fn deserialize_best_effort_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_deserialize_best_effort_macro(&ast)
}

fn impl_deserialize_best_effort_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let data = get_struct_data(&ast);
    let fields = get_struct_fields(&ast);

    let field_enum_and_field_visitor = impl_field_enum_visitor(&fields);
    let struct_visitor = impl_struct_visitor(&data, name);
    let fields_array = get_fields_array(&fields);

    let visitor_name = get_visitor_name(&name);
    // Build impl
    let gen = quote! {
        impl<'de> DeserializeBestEffort<'de> for #name {}
        impl<'de> serde::de::Deserialize<'de> for #name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::de::Deserializer<'de>,
            {
                #field_enum_and_field_visitor

                #struct_visitor

                #fields_array
                deserializer.deserialize_struct(stringify!(#name), FIELDS, #visitor_name)

            }
        }
    };
    gen.into()
}

fn get_alias_attrs(struct_fields: &syn::Field) -> Vec<String> {
    // let mut parse_gen = quote!{};
    let mut lit_list = Vec::new();
    for attr in &struct_fields.attrs {
        // let path_idents = get_alias_attrs_path_ident(&attr);
        let tokens = get_alias_attrs_variables(&attr);
        for val in tokens {
            let mut string_quote = "".to_string();
            if let syn::Lit::Str(string_lit) = val {
                string_quote = string_lit.value();
            }
            if string_quote.is_empty() {
                continue;
            }
            lit_list.push(string_quote);
        }
        // parse_gen = quote!{
        //     #parse_gen
        //     println!("Att: ident: {:?} token: {:?}",
        //         stringify!( #(#path_idents),*),
        //         stringify!( #(#tokens),*),
        //     );
        // };
    }
    lit_list
}

// fn get_alias_attrs_path_ident(attr: &syn::Attribute) -> Vec<&syn::Ident> {
//     let mut list = Vec::new();
//     for path_segment in &attr.path.segments{
//         let ident = &path_segment.ident;
//         list.push(ident);
//     }
//     list
// }

fn get_alias_attrs_variables(attr: &syn::Attribute) -> Vec<syn::Lit> {
    let meta_items = get_serde_meta_items(attr).unwrap();
    let mut lit_list: Vec<syn::Lit> = Vec::new();
    for meta_item in meta_items {
        match meta_item {
            // Parse `#[serde(alias = "foo")]`
            syn::NestedMeta::Meta(syn::Meta::NameValue(m)) if m.path.is_ident("alias") => {
                lit_list.push(m.lit);
            }
            _ => (),
        };
    }
    lit_list
}

// From https://github.com/serde-rs/serde/blob/master/serde_derive/src/internals/attr.rs line 1566
fn get_serde_meta_items(attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>, ()> {
    if !attr.path.is_ident("serde") {
        return Ok(Vec::new());
    }

    match attr.parse_meta() {
        Ok(syn::Meta::List(meta)) => Ok(meta.nested.into_iter().collect()),
        Ok(_other) => {
            // cx.error_spanned_by(other, "expected #[serde(...)]");
            Err(())
        }
        Err(_err) => {
            // cx.syn_error(err);
            Err(())
        }
    }
}

fn get_fields_array(struct_fields: &[&syn::Field]) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    // let mut parse_gen2 = quote!{};
    for (i, field) in struct_fields.iter().enumerate() {
        // parse normal name (name of variable)
        // Ex: `pub name: String,` will add `"name",` to the list
        let ident = field.ident.as_ref().unwrap();
        let field_ident = get_enum_ident(ident, i);
        parse_gen = quote! {
            #parse_gen stringify!(#field_ident),
        };
        // parse alias names (if any)
        // Ex: `#[serde(alias = "type")]` will add `"type",` to the list
        let alias_ident = get_alias_attrs(field);
        for alias in alias_ident {
            parse_gen = quote! {
                #parse_gen stringify!(#alias),
            };
        }
    }
    parse_gen = quote! {
        const FIELDS: &'static [&'static str] = &[#parse_gen];
    };
    parse_gen
}

fn get_field_enum(struct_fields: &[&syn::Field]) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (i, field) in struct_fields.iter().enumerate() {
        let ident = field.ident.as_ref().unwrap();
        let field_ident = get_enum_ident(ident, i);
        parse_gen = quote! {
            #parse_gen
            #field_ident,
        }
    }
    parse_gen = quote! {
        enum Field {
            #parse_gen
            Unknown(String),
        }
    };
    parse_gen
}

fn get_field_enum_match(struct_fields: &[&syn::Field]) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (i, field) in struct_fields.iter().enumerate() {
        let ident = field.ident.as_ref().unwrap();
        let field_enum_ident = get_enum_ident(ident, i);
        parse_gen = quote! {
            #parse_gen
            // "id" => Ok(Field::Id),
            stringify!(#ident) => Ok(Field::#field_enum_ident),
        };
        // from #[serde(alias = "type")]
        let alias_ident = get_alias_attrs(field);

        for alias in alias_ident {
            parse_gen = quote! {
                #parse_gen
                // "type" => Ok(Field::Id),
                #alias => Ok(Field::#field_enum_ident),
            };
        }
    }
    parse_gen = quote! {
        match value {
            // "id" => Ok(Field::Id),
            #parse_gen
            _ => Ok(Field::Unknown(value.to_string())),
        }
    };
    parse_gen
}

fn impl_field_enum_visitor(struct_fields: &[&syn::Field]) -> proc_macro2::TokenStream {
    let field_enum = get_field_enum(&struct_fields);
    let field_enum_match = get_field_enum_match(&struct_fields);

    let parse_gen = quote! {
        // enum Field { Id, Name, Race, Unknown, Special };
        #field_enum

        impl<'de> serde::de::Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
            where
                D: serde::de::Deserializer<'de>,
            {
                struct FieldVisitor;

                impl<'de> serde::de::Visitor<'de> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                        formatter.write_str("Did not expect this... se default is not working.")
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        #field_enum_match
                    }
                }
                // deserialize_any
                deserializer.deserialize_identifier(FieldVisitor)
            }
        }
    };
    parse_gen
}

fn impl_struct_visitor(
    struct_data: &[(&syn::Ident, &syn::Type)],
    name: &syn::Ident,
) -> proc_macro2::TokenStream {
    let visit_seq = get_struct_visit_seq(&struct_data, &name);
    let visit_map = get_struct_visit_map(&struct_data, &name);

    let visitor_name = get_visitor_name(&name);

    let parse_gen = quote! {
        struct #visitor_name;

        impl<'de> serde::de::Visitor<'de> for #visitor_name {
            type Value = #name;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str(&format!("struct {}",stringify!(#visitor_name)))
            }

            #visit_seq

            #visit_map

        }

    };
    parse_gen
}

fn get_struct_visit_seq(
    struct_data: &[(&syn::Ident, &syn::Type)],
    name: &syn::Ident,
) -> proc_macro2::TokenStream {
    let variable_init = set_struct_visit_seq_variable(&struct_data);
    let create_object = set_struct_create_object(&struct_data, &name);

    // This code is not used for structs
    // TODO: Test this code if it works
    let parse_gen = quote! {
        fn visit_seq<V>(self, mut seq: V) -> Result<#name, V::Error>
        where
            V: serde::de::SeqAccess<'de>,
        {
            // not used for struct it seems
            #variable_init
            Ok(#create_object)
        }

    };
    parse_gen
}

fn set_struct_visit_seq_variable(
    struct_data: &[(&syn::Ident, &syn::Type)],
) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (i, (field, type_)) in struct_data.iter().enumerate() {
        parse_gen = quote! {
            #parse_gen
            // Example of generated code:
            //let id = seq.next_element()?
            //    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
            let #field:#type_ = seq.next_element()?
                .ok_or_else(|| de::Error::invalid_length(#i, &self))?;
        };
    }
    parse_gen
}

fn get_struct_visit_map(
    struct_data: &[(&syn::Ident, &syn::Type)],
    name: &syn::Ident,
) -> proc_macro2::TokenStream {
    let variable_init = set_struct_visit_map_variable(&struct_data);
    let enum_match_variable = set_struct_visit_map_enum_match(&struct_data);
    let create_object = set_struct_create_object(&struct_data, &name);

    let parse_gen = quote! {
        fn visit_map<V>(self, mut map: V) -> Result<#name, V::Error>
        where
            V: serde::de::MapAccess<'de>,
        {
            #variable_init
            while let Some(key) = map.next_key()? {
                #enum_match_variable
            }
            Ok(#create_object)
        }

    };
    parse_gen
}

fn set_struct_create_object(
    struct_data: &[(&syn::Ident, &syn::Type)],
    name: &syn::Ident,
) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (field, _type) in struct_data {
        parse_gen = quote! {
            #parse_gen
            //id,
            // similar to `id: id,`
            #field,
        }
    }
    parse_gen = quote! {
        //#[allow(clippy::needless_update)]
        #name{
            #parse_gen
            //..Default::default()
        }
    };
    parse_gen
}

fn set_struct_visit_map_variable(
    struct_data: &[(&syn::Ident, &syn::Type)],
) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (field, type_) in struct_data {
        parse_gen = quote! {
            #parse_gen
            //let mut id:i32 = Default::default();
            let mut #field:#type_ = Default::default();
        }
    }
    parse_gen
}

fn set_struct_visit_map_enum_match(
    struct_data: &[(&syn::Ident, &syn::Type)],
) -> proc_macro2::TokenStream {
    let mut parse_gen = quote! {};
    for (i, (field, _type)) in struct_data.iter().enumerate() {
        let field_ident = get_enum_ident(field, i);
        parse_gen = quote! {
            #parse_gen
            // Example of generated code:
            // Field::Enum_id => {
            //     let next_value = map.next_value().unwrap_or_default();
            //     id.add_data(next_value);
            // }
            Field::#field_ident => {
                let next_value = map.next_value().unwrap_or_default();
                #field.add_data(stringify!(#field), next_value);
            }
        }
    }
    parse_gen = quote! {
        match key {
            #parse_gen
            Field::Unknown(key_name) => {
                let next_value = map.next_value().unwrap_or_default();
                // TODO replace `unknown` with key name (already done?)
                unknown.add_data(&key_name, next_value);
            }
        }
    };
    parse_gen
}

fn get_enum_ident(_ident: &syn::Ident, number: usize) -> syn::Ident {
    format_ident!("Enum{}", number)
}

fn get_visitor_name(ident: &syn::Ident) -> syn::Ident {
    format_ident!("Struct{}Visitor", ident)
}