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
extern crate proc_macro;
extern crate syn;

#[macro_use]
extern crate quote;

use proc_macro::TokenStream;
use syn::{VariantData, Body, MetaItem, Lit};

#[proc_macro_derive(Serialize, attributes(id))]
pub fn serialize(input: TokenStream) -> TokenStream {
    // Construct a string representation of the type definition
    let s = input.to_string();

    // Parse the string representation
    let ast = syn::parse_macro_input(&s).unwrap();

    // Build the impl
    let gen = impl_serialize(&ast);

    // Return the generated impl
    gen.parse().unwrap()
}

fn impl_serialize(ast: &syn::MacroInput) -> quote::Tokens {
    let mut properties = Vec::new();

    match ast.body {
        Body::Struct(VariantData::Struct(ref fields)) => {
            for field in fields {
                if let Some(ref field_name) = field.ident {
                    properties.push(quote! {
                        self.#field_name.serialize_to(buffer)?;
                    });
                }
            }
        }

        _ => {
            // Do nothing
        }
    }

    let mut id = None;

    for attr in &ast.attrs {
        match attr.value {
            MetaItem::NameValue(ref name, ref value) => {
                if name.as_ref() == "id" {
                    if let Lit::Int(value, _) = *value {
                        // Found an identifier
                        id = Some(quote! {
                            (#value as u32).serialize_to(buffer)?;
                        });

                        break;
                    }
                }
            }

            _ => {
                // Do nothing
            }
        }
    }

    let name = &ast.ident;

    quote! {
        impl ::ser::Serialize for #name {
            fn serialize_to(&self, buffer: &mut Vec<u8>) -> ::error::Result<()> {
                // Identifier
                #id

                // Properties
                #(#properties)*

                Ok(())
            }
        }
    }
}