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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::{format_ident, quote};
use syn::{
    parse_macro_input, AngleBracketedGenericArguments, Attribute, Data, DataStruct, DeriveInput,
    Fields, FieldsNamed, GenericArgument, Meta, MetaList, NestedMeta, Path, PathArguments,
    PathSegment, Type, TypePath,
};

#[proc_macro_derive(Schema, attributes(schema))]
pub fn derive(input: TokenStream) -> TokenStream {
    // Parse the input tokens into a syntax tree.
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;
    let fields = match input.data {
        Data::Struct(DataStruct {
            fields: Fields::Named(FieldsNamed { named, .. }),
            ..
        }) => named,
        _ => panic!("derive(Schema) only supports structs with named fields"),
    };
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let fields: Vec<StructField> = fields
        .iter()
        .map(|f| {
            let ty = f.ty.clone();
            let value_type = extract_attr(&f.attrs);

            let inner_ty = extract_internal_type(&ty).cloned();
            StructField {
                value_type,
                ident: f.ident.clone(),
                ty: f.ty.clone(),
                inner_ty,
            }
        })
        .collect();

    let setters = fields.iter().map(|f| {
        let ident = &f.ident;

        if let Some(ty) = &f.inner_ty {
            quote! {
                pub fn #ident(mut self, #ident: #ty) -> Self {
                    self.#ident = ::std::option::Option::Some(#ident);
                    self
                }
            }
        } else {
            let ty = &f.ty;
            quote! {
                pub fn #ident(mut self, #ident: #ty) -> Self {
                    self.#ident = #ident;
                    self
                }
            }
        }
    });

    // Calls to visit_pair
    let visitor = format_ident!("visitor");
    let from_serde = quote! { ::diem_logger::Value::from_serde };
    let from_display = quote! { ::diem_logger::Value::from_display };
    let from_debug = quote! { ::diem_logger::Value::from_debug };
    let key_new = quote! { ::diem_logger::Key::new };
    let visits = fields.iter().map(|f| {
        let ident = f.ident.as_ref().unwrap();
        let ident_str = ident.to_string();

        let from_fn = match f.value_type {
            Some(ValueType::Display) => &from_display,
            Some(ValueType::Debug) => &from_debug,
            Some(ValueType::Serde) | None => &from_serde,
        };
        if f.inner_ty.is_some() {
            quote! {
                if let Some(#ident) = &self.#ident {
                    #visitor.visit_pair(#key_new(#ident_str), #from_fn(#ident));
                }
            }
        } else {
            quote! {
                #visitor.visit_pair(#key_new(#ident_str), #from_fn(&self.#ident));
            }
        }
    });

    // Build the output, possibly using quasi-quotation
    let expanded = quote! {
        impl #impl_generics #name #ty_generics #where_clause {
            #(#setters)*
        }

        impl #impl_generics ::diem_logger::Schema for #name #ty_generics #where_clause {
            fn visit(&self, visitor: &mut dyn ::diem_logger::Visitor) {
                #(#visits)*
            }
        }
    };

    // Hand the output tokens back to the compiler
    TokenStream::from(expanded)
}

#[derive(Debug)]
enum ValueType {
    Debug,
    Display,
    Serde,
}

#[derive(Debug)]
struct StructField {
    value_type: Option<ValueType>,
    ident: Option<Ident>,
    ty: Type,
    /// Indicates that the type is wrapped by an Option type
    inner_ty: Option<Type>,
}

fn extract_internal_type(ty: &Type) -> Option<&Type> {
    if let Type::Path(TypePath {
        qself: None,
        path: Path { segments, .. },
    }) = ty
    {
        if let Some(PathSegment { ident, arguments }) = segments.first() {
            // Extract the inner type if it is "Option"
            if ident == "Option" {
                if let PathArguments::AngleBracketed(AngleBracketedGenericArguments {
                    args, ..
                }) = arguments
                {
                    if let Some(GenericArgument::Type(ty)) = args.first() {
                        return Some(ty);
                    }
                }
            }
        }
    }

    None
}

fn extract_attr(attrs: &[Attribute]) -> Option<ValueType> {
    for attr in attrs {
        if let Meta::List(MetaList { path, nested, .. }) = attr.parse_meta().unwrap() {
            for segment in path.segments {
                // Only handle schema attrs
                if segment.ident == "schema" {
                    for meta in &nested {
                        let path = if let NestedMeta::Meta(Meta::Path(path)) = meta {
                            path
                        } else {
                            panic!("unsupported schema attribute");
                        };

                        match path.segments.first().unwrap().ident.to_string().as_ref() {
                            "debug" => return Some(ValueType::Debug),
                            "display" => return Some(ValueType::Display),
                            "serde" => return Some(ValueType::Serde),
                            _ => panic!("unsupported schema attribute"),
                        }
                    }
                }
            }
        }
    }

    None
}