Skip to main content

efx_attrnames/
lib.rs

1#![deny(rust_2018_idioms)]
2
3use proc_macro::TokenStream;
4use proc_macro2::Span;
5use quote::quote;
6use std::collections::HashSet;
7use syn::{parse_macro_input, Data, DeriveInput, Fields, LitStr, Result as SynResult};
8
9/// Derive to generate `ATTR_NAMES` constant (and optionally `ATTR_INFO`) for attribute structures.
10/// Supports:
11/// - `#[attr(name = "...")]` / `#[efx(name = "...")]`
12/// - `#[attr(alias = "...")]` / `#[efx(alias = "...")]` (несколько раз)
13/// - `#[attr(skip)]` / `#[efx(skip)]`
14/// - `#[attr(prefix = "...")]` / `#[efx(prefix = "...")]` на контейнере (struct)
15///
16/// Дополнительно:
17/// - Если в целевом пакете включена фича `attrnames-info`, генерируется:
18///   `pub const ATTR_INFO: &'static [(&'static str, &'static [&'static str])]`.
19#[proc_macro_derive(AttrNames, attributes(attr, efx))]
20pub fn derive_attr_names(input: TokenStream) -> TokenStream {
21    let input = parse_macro_input!(input as DeriveInput);
22    expand_attr_names(&input).unwrap_or_else(|e| e.to_compile_error().into())
23}
24
25fn expand_attr_names(input: &DeriveInput) -> SynResult<TokenStream> {
26    let ty_ident = &input.ident;
27
28    // Supports only structures with named fields
29    let named = match &input.data {
30        Data::Struct(st) => match &st.fields {
31            Fields::Named(n) => n,
32            _ => {
33                return Err(syn::Error::new_spanned(
34                    &st.fields,
35                    "AttrNames supports only structs with named fields",
36                ));
37            }
38        },
39        _ => {
40            return Err(syn::Error::new_spanned(
41                &input.ident,
42                "AttrNames supports only structs",
43            ));
44        }
45    };
46
47    // Prefix on container: #[attr(prefix="data-")] or #[efx(prefix="data-")]
48    let mut container_prefix: Option<String> = None;
49    for a in &input.attrs {
50        if is_attr_or_efx(a) {
51            a.parse_nested_meta(|meta| {
52                if meta.path.is_ident("prefix") {
53                    let lit: LitStr = meta.value()?.parse()?;
54                    container_prefix = Some(lit.value());
55                }
56                Ok(())
57            })?;
58        }
59    }
60
61    // Assembling names (primary + aliases) by fields
62    struct FieldSpec {
63        primary: (String, Span),
64        aliases: Vec<(String, Span)>,
65    }
66
67    let mut specs: Vec<FieldSpec> = Vec::with_capacity(named.named.len());
68
69    for f in &named.named {
70        let ident = match &f.ident {
71            Some(id) => id,
72            None => {
73                return Err(syn::Error::new_spanned(f, "expected named field"));
74            }
75        };
76
77        let mut skip = false;
78        let mut name: Option<(String, Span)> = None;
79        let mut aliases: Vec<(String, Span)> = Vec::new();
80
81        for a in &f.attrs {
82            if is_attr_or_efx(a) {
83                a.parse_nested_meta(|meta| {
84                    if meta.path.is_ident("skip") {
85                        skip = true;
86                    } else if meta.path.is_ident("name") {
87                        let lit: LitStr = meta.value()?.parse()?;
88                        name = Some((lit.value(), lit.span()));
89                    } else if meta.path.is_ident("alias") {
90                        let lit: LitStr = meta.value()?.parse()?;
91                        aliases.push((lit.value(), lit.span()));
92                    }
93                    Ok(())
94                })?;
95            }
96        }
97
98        if skip {
99            continue;
100        }
101
102        let (base_name, base_span) = match name {
103            Some((n, sp)) => (n, sp),
104            None => (ident.to_string(), ident.span()),
105        };
106
107        // Apply prefix to all names (primary + aliases) if specified
108        let with_prefix = |s: &str| -> String {
109            if let Some(pref) = &container_prefix {
110                let mut out = String::with_capacity(pref.len() + s.len());
111                out.push_str(pref);
112                out.push_str(s);
113                out
114            } else {
115                s.to_string()
116            }
117        };
118
119        let prim = (with_prefix(&base_name), base_span);
120        let ali = aliases
121            .into_iter()
122            .map(|(a, sp)| (with_prefix(&a), sp))
123            .collect::<Vec<_>>();
124
125        specs.push(FieldSpec {
126            primary: prim,
127            aliases: ali,
128        });
129    }
130
131    // Check for duplicates after applying prefix
132    let mut seen: HashSet<String> = HashSet::new();
133    for spec in &specs {
134        let (p, pspan) = &spec.primary;
135        if !seen.insert(p.clone()) {
136            return Err(syn::Error::new(
137                *pspan,
138                format!("duplicate attribute name '{p}'"),
139            ));
140        }
141        for (a, aspan) in &spec.aliases {
142            if !seen.insert(a.clone()) {
143                return Err(syn::Error::new(
144                    *aspan,
145                    format!("duplicate attribute name '{a}'"),
146                ));
147            }
148        }
149    }
150
151    // Preparing literals
152    let mut name_lits: Vec<LitStr> = Vec::with_capacity(seen.len());
153    for spec in &specs {
154        let (p, sp) = &spec.primary;
155        name_lits.push(LitStr::new(p, *sp));
156        for (a, asp) in &spec.aliases {
157            name_lits.push(LitStr::new(a, *asp));
158        }
159    }
160
161    // For ATTR_INFO (`attrnames-info`)
162    // &[("primary", &["alias1","alias2"]), ...]
163    let info_pairs = specs.iter().map(|spec| {
164        let (p, psp) = &spec.primary;
165        let prim_lit = LitStr::new(p, *psp);
166        let alias_lits: Vec<LitStr> = spec
167            .aliases
168            .iter()
169            .map(|(a, sp)| LitStr::new(a, *sp))
170            .collect();
171        quote! {
172            (#prim_lit, &[ #( #alias_lits ),* ])
173        }
174    });
175
176    let output = quote! {
177        impl #ty_ident {
178            pub const ATTR_NAMES: &'static [&'static str] = &[ #( #name_lits ),* ];
179
180            /// Additional information: pairs (primary, aliases), generated only if **target** packet has aliases enabled
181            /// feature `attrnames-info`:
182            ///
183            /// ```toml
184            /// [features]
185            /// attrnames-info = []
186            /// ```
187            #[cfg(feature = "attrnames-info")]
188            pub const ATTR_INFO: &'static [(&'static str, &'static [&'static str])] = &[
189                #( #info_pairs ),*
190            ];
191        }
192    };
193
194    Ok(output.into())
195}
196
197#[inline]
198fn is_attr_or_efx(attr: &syn::Attribute) -> bool {
199    let p = attr.path();
200    p.is_ident("attr") || p.is_ident("efx")
201}