armour_derive/
lib.rs

1#[macro_use]
2extern crate darling;
3extern crate proc_macro2;
4extern crate quote;
5extern crate syn;
6
7use proc_macro::TokenStream;
8
9use darling::util::Flag;
10use syn::{Data, DeriveInput, Expr, ExprPath, LitStr, parse_macro_input};
11
12/// Adds metrics tracking to the function.
13///
14/// # Example
15/// ```rust
16/// #[armour_metrics(prefix = "my_prefix", name = tree.raw.name.clone())]
17/// fn my_function() {
18///     // function body
19/// }
20/// ```
21#[proc_macro_attribute]
22pub fn armour_metrics(attr: TokenStream, item: TokenStream) -> TokenStream {
23    metrics::armour_metrics_impl(attr, item)
24}
25
26mod enum_parse;
27mod metrics;
28mod struct_parse;
29
30/// - `#[get_type(idx = 1)]` in fields
31/// - `#[get_type(flatten)]` for unnamed structs
32/// - `#[get_type(with_type(Type))]` for named struct fields
33/// - `#[get_type(unimplemented)]` for named struct fields
34/// - `#[get_type(custom("name", &[Typ::Bool, Typ::Str]))]` for named struct fields
35#[proc_macro_derive(GetType, attributes(idx, get_type))]
36pub fn derive_get_type(stream: TokenStream) -> TokenStream {
37    let ast = parse_macro_input!(stream as DeriveInput);
38    let name = ast.ident;
39    let data = &ast.data;
40
41    match data {
42        Data::Struct(data_struct) => struct_parse::parse(data_struct, name).into(),
43        Data::Enum(data_enum) => enum_parse::parse(data_enum, name),
44        Data::Union(_) => {
45            panic!(
46                "unions not supported, but Rust enums is implemented GetType trait (use Enums instead)"
47            )
48        }
49    }
50}
51
52#[derive(FromMeta, Debug)]
53struct CustomField {
54    name: LitStr,
55    types: Expr,
56}
57
58#[derive(Default, FromField, Debug)]
59#[darling(attributes(get_type))]
60pub(crate) struct FieldAttr {
61    pub(crate) idx: Option<u32>,
62    pub(crate) with_type: Option<ExprPath>,
63    pub(crate) unimplemented: Flag,
64    pub(crate) custom: Option<CustomField>,
65    pub(crate) flatten: Flag,
66}