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
use proc_macro::TokenStream;
use proc_macro2::{TokenStream as TStream2, TokenTree};
use quote::quote;
use syn::{
    parse_macro_input, parse_quote, Attribute, Data, DeriveInput, Fields, GenericParam, Generics,
    Path, Type,
};

fn krate() -> TStream2 {
    quote!(::telegraf)
}

#[proc_macro_derive(Metric, attributes(measurement, telegraf))]
pub fn derive_metric(tokens: TokenStream) -> TokenStream {
    expand_metric(tokens)
}

fn expand_metric(tokens: TokenStream) -> TokenStream {
    let krate = krate();
    let input = parse_macro_input!(tokens as DeriveInput);

    let name = &input.ident;
    let measurement = get_measurement_name(&input);

    let generics = add_trait_bounds(input.generics);
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let pt = get_to_point(&input.data);

    let expanded = quote! {
        impl #impl_generics #krate::Metric for #name #ty_generics #where_clause {
            fn to_point(&self) -> #krate::Point {
                let mut pf: Vec<(String, Box<dyn #krate::IntoFieldData>)> = Vec::new();
                let mut pt: Vec<(String, String)> = Vec::new();
                let mut tsp: Option<u64> = None;
                #pt
                #krate::Point::new(#measurement, pt, pf, tsp)
            }
        }
    };

    TokenStream::from(expanded)
}

fn get_measurement_name(input: &DeriveInput) -> TStream2 {
    let default = &input.ident;
    let measurement = input
        .attrs
        .iter()
        .find(|a| a.path.segments.len() == 1 && a.path.segments[0].ident == "measurement");

    match measurement {
        Some(attr) => {
            let q = attr
                .tokens
                .clone()
                .into_iter()
                .nth(1)
                .map(|t| match t {
                    TokenTree::Literal(l) => l,
                    _ => panic!("unexpected type"),
                })
                .unwrap();
            quote!(#q.to_string())
        }
        None => quote!(stringify!(#default).to_string()),
    }
}

fn add_trait_bounds(mut generics: Generics) -> Generics {
    let krate = krate();
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(#krate::Metric));
        }
    }
    generics
}

fn has_attr(attr: &Attribute) -> bool {
    attr.path
        .segments
        .iter()
        .last()
        .map(|seg| seg.ident.to_string())
        .unwrap_or_default()
        == "telegraf"
}

fn check_attr(t_tree: TokenTree, cmp: &str) -> bool {
    match t_tree {
        TokenTree::Group(group) => group
            .stream()
            .into_iter()
            .next()
            .map(|token_tree| match token_tree {
                TokenTree::Ident(ident) => ident == cmp,
                _ => false,
            })
            .unwrap(),
        _ => false,
    }
}

fn is_tag(attr: &Attribute) -> bool {
    if !has_attr(attr) {
        return false;
    }

    attr.tokens
        .clone()
        .into_iter()
        .next()
        .map(|t_tree| check_attr(t_tree, "tag"))
        .unwrap()
}

fn is_timestamp(attr: &Attribute) -> bool {
    if !has_attr(attr) {
        return false;
    }

    attr.tokens
        .clone()
        .into_iter()
        .next()
        .map(|t_tree| check_attr(t_tree, "timestamp"))
        .unwrap()
}

fn get_to_point(data: &Data) -> TStream2 {
    fn path_is_option(path: &Path) -> bool {
        path.leading_colon.is_none()
            && path.segments.len() == 1
            && path.segments.iter().next().unwrap().ident == "Option"
    }

    match *data {
        Data::Struct(ref data) => {
            match data.fields {
                Fields::Named(ref fields) => {
                    fields.named
                        .iter()
                        .map(|f| {
                            match &f.ty {
                                Type::Path(typath) if typath.qself.is_none() && path_is_option(&typath.path) => {
                                    let name = &f.ident;
                                    if f.attrs.iter().any(is_tag) {
                                        quote!(
                                            if let Some(ref v) = self.#name {
                                                pt.push((stringify!(#name).to_string(), format!("{}", v)));
                                            }
                                        )
                                    } else if f.attrs.iter().any(is_timestamp) {
                                        quote!(
                                            if let Some(ref v) = self.#name {
                                                tsp = tsp.or(Some(v.into()));
                                            }
                                        )
                                    } else {
                                        quote!(
                                            if let Some(ref v) = self.#name {
                                                pf.push((stringify!(#name).to_string(), Box::new(v.clone())));
                                            }
                                        )
                                    }
                                },
                                _ => {
                                    let name = &f.ident;
                                    if f.attrs.iter().any(is_tag) {
                                        quote!(pt.push((stringify!(#name).to_string(), format!("{}", self.#name)));)
                                    } else if f.attrs.iter().any(is_timestamp) {
                                        quote!(tsp = tsp.or(Some(self.#name.into()));)
                                    } else {
                                        quote!(pf.push((stringify!(#name).to_string(), Box::new(self.#name.clone())));)
                                    }
                                }
                            }
                        })
                        .collect()
                }
                _ => panic!("only named fields supported")
            }
        }
        _ => panic!("cannot derive for data type")
    }
}