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
/**
* Copyright 2019 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
use lazy_static::lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate syn;

lazy_static! {
    static ref BOOL: Ident = Ident::new("bool");
    static ref BWC: Ident = Ident::new("BWC");
    static ref F64: Ident = Ident::new("f64");
    static ref I32: Ident = Ident::new("i32");
    static ref I64: Ident = Ident::new("i64");
    static ref OPTIONAL: Ident = Ident::new("Option");
    static ref STRING: Ident = Ident::new("String");
    static ref U8: Ident = Ident::new("u8");
    static ref U16: Ident = Ident::new("u16");
    static ref U64: Ident = Ident::new("u64");
    static ref UUID: Ident = Ident::new("Uuid");
    static ref VALUE: Ident = Ident::new("Value");
    static ref VEC: Ident = Ident::new("Vec");
}

use proc_macro::TokenStream;
use syn::{Ident, PathParameters, Ty};

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

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

    // Build the impl
    let gen = impl_point(&ast, false);

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

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

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

    // Build the impl
    let gen = impl_point(&ast, true);

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

fn impl_point(ast: &syn::DeriveInput, child: bool) -> quote::Tokens {
    let name = &ast.ident;
    match ast.body {
        syn::Body::Struct(ref data) => impl_struct_point_fields(name, data.fields(), child),
        syn::Body::Enum(ref data) => {
            println!("into_enum_point_fields called");
            impl_enum_point_fields(name, data)
        }
    }
}

fn find_optional_type(field: syn::Field) -> Option<Ident> {
    match field.clone().ty {
        Ty::Path(_, p) => {
            if let Some(i) = p.segments.clone().into_iter().next() {
                match i.parameters {
                    PathParameters::AngleBracketed(a) => {
                        for ty in a.types {
                            match ty {
                                Ty::Path(_, p2) => {
                                    if let Some(i2) = p2.segments.clone().into_iter().next() {
                                        return Some(i2.ident);
                                    } else {
                                        return None;
                                    }
                                }
                                _ => return None,
                            }
                        }
                    }
                    _ => {
                        return None;
                    }
                }
                return None;
            } else {
                return None;
            }
        }
        _ => return None,
    }
}

fn impl_struct_point_fields(
    name: &syn::Ident,
    fields: &[syn::Field],
    child: bool,
) -> quote::Tokens {
    let mut result = Vec::new();
    for field in fields {
        let ident = &field.ident;
        let ident_type = match field.clone().ty {
            Ty::Path(_, p) => {
                if let Some(i) = p.segments.clone().into_iter().next() {
                    Some(i.ident)
                } else {
                    None
                }
            }
            _ => None,
        };

        // In the case of optional types like Option<String> we need to
        // find the second parameter or we won't know what to do below
        let angle_type: Option<Ident> = if let Some(i_type) = ident_type.clone() {
            if i_type == *OPTIONAL {
                find_optional_type(field.clone())
            } else {
                None
            }
        } else {
            None
        };

        let vec_angle_type: Option<Ident> = if let Some(i_type) = ident_type.clone() {
            if i_type == *VEC {
                find_optional_type(field.clone())
            } else {
                None
            }
        } else {
            None
        };

        match ident_type {
            Some(i_type) => {
                if i_type == *BWC {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::Long(self.#ident.average()));
                    });
                } else if i_type == *STRING {
                    result.push(quote! {
                        if !self.#ident.is_empty(){
                            p.add_tag(stringify!(#ident), TsValue::String(self.#ident.clone()));
                        }
                    });
                } else if i_type == *I32 {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::Integer(self.#ident));
                    });
                } else if i_type == *I64 {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::SignedLong(self.#ident));
                    });
                } else if i_type == *UUID {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::String(self.#ident.to_string()));
                    });
                } else if i_type == *U8 {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::Byte(self.#ident));
                    });
                } else if i_type == *U16 {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::Short(self.#ident));
                    });
                } else if i_type == *U64 {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::Long(self.#ident));
                    });
                } else if i_type == *F64 {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::Float(self.#ident));
                    });
                } else if i_type == *BOOL {
                    result.push(quote! {
                        p.add_field(stringify!(#ident), TsValue::Boolean(self.#ident));
                    });
                } else if i_type == *VEC {
                    match &vec_angle_type {
                        Some(ref vec_type) => {
                            if *vec_type == *STRING {
                                result.push(quote! {
                                    p.add_tag(stringify!(#ident), TsValue::StringVec(
                                        self.#ident.clone()
                                    ));
                                });
                            } else if *vec_type == *U64 {
                                result.push(quote! {
                                    p.add_tag(stringify!(#ident), TsValue::LongVec(
                                        self.#ident.clone()
                                    ));
                                });
                            } else if *vec_type == *UUID {
                                result.push(quote! {
                                    p.add_tag(stringify!(#ident), TsValue::StringVec(
                                        self.#ident.iter().map(|i| i.to_string()).collect::<Vec<String>>(),
                                    ));
                                });
                            } else {
                                //println!("vec found {} with inner: {:?}", i_type, vec_angle_type);
                            }
                        }
                        None => {
                            // Unable to identify this type
                            println!(
                                "Unable to identify vec type for {:?} {:?} {:?}",
                                ident, i_type, vec_angle_type
                            );
                        }
                    }
                } else if i_type == *OPTIONAL {
                    //println!("OPTIONAL type: {:?} {:?} {:?}", ident, i_type, angle_type,);
                    match angle_type {
                        Some(option_type) => {
                            if option_type == *STRING {
                                result.push(quote! {
                                    if let Some(ref s) = self.#ident{
                                        if !s.is_empty(){
                                            p.add_tag(stringify!(#ident),
                                                TsValue::String(s.clone()));
                                        }
                                    }
                                });
                            } else if option_type == *BOOL {
                                result.push(quote! {
                                    if self.#ident.is_some(){
                                        p.add_field(stringify!(#ident),
                                            TsValue::Boolean(self.#ident.unwrap()));
                                    }
                                });
                            } else if option_type == *BWC {
                                result.push(quote! {
                                    if self.#ident.is_some(){
                                        let BWC_val = self.#ident.clone().unwrap();
                                        p.add_field(stringify!(#ident),
                                            TsValue::Long(BWC_val.average()));
                                    }
                                });
                            } else if option_type == *I32 {
                                result.push(quote! {
                                    if self.#ident.is_some(){
                                        p.add_field(stringify!(#ident),
                                            TsValue::Integer(self.#ident.unwrap()));
                                    }
                                });
                            } else if option_type == *I64 {
                                result.push(quote! {
                                    if self.#ident.is_some(){
                                        p.add_field(stringify!(#ident),
                                            TsValue::SignedLong(self.#ident.unwrap()));
                                    }
                                });
                            } else if option_type == *UUID {
                                result.push(quote! {
                                    if self.#ident.is_some(){
                                        p.add_field(stringify!(#ident),
                                            TsValue::String(self.#ident.unwrap().to_string()));
                                    }
                                });
                            } else if option_type == *U64 {
                                result.push(quote! {
                                    if self.#ident.is_some(){
                                        p.add_field(stringify!(#ident),
                                            TsValue::Long(self.#ident.unwrap()));
                                    }
                                });
                            } else if option_type == *F64 {
                                result.push(quote! {
                                    if self.#ident.is_some(){
                                        p.add_field(stringify!(#ident),
                                            TsValue::Float(self.#ident.unwrap()));
                                    }
                                });
                            } else {
                                //println!("OPTIONAL else: {:?}", option_type);
                            }
                        }
                        None => {
                            // Unable to identify this type
                            println!(
                                "Unable to identify optional type for {:?} {:?} {:?}",
                                ident, i_type, angle_type
                            );
                        }
                    }
                } else {
                    // Uncomment me to debug why some fields may be missing
                    //println!("else: {:?} {:?} {:?}", ident, i_type, field.clone().ty);
                }
            }
            None => {
                // Unable to identify this type
                println!("Unable to identify type for {:?}", ident);
            }
        }
    }
    if child {
        quote! {
            impl ChildPoint for #name {
                fn sub_point(&self, p: &mut TsPoint) {
                    #(#result)*
                }
            }
        }
    } else {
        quote! {
            impl IntoPoint for #name {
                fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
                    let mut p = TsPoint::new(name.unwrap_or("unknown"), is_time_series);
                    #(#result)*
                    vec![p]
                }
            }
        }
    }
}

fn impl_enum_point_fields(name: &syn::Ident, variants: &[syn::Variant]) -> quote::Tokens {
    let mut result = Vec::new();
    for variant in variants {
        let ident = &variant.ident;
        match variant.discriminant {
            Some(ref val) => {
                result.push(quote! {
                    &#name::#ident => #val.into_point(&mut buff),
                });
            }
            None => {
                result.push(quote! {
                    &#name::#ident => #ident.into_point(&mut buff),
                });
            }
        }
    }
    quote! {
        impl IntoPoint for #name {
            fn into_point(&self, name: Option<&str>, is_time_series: bool) -> TsPoint {
                let mut p = TsPoint::new(point_name.unwrap_or("unknown"), is_time_series);
                match self {
                    #(#result)*
                }
                p
            }
        }
    }
}