ruma_macros/serde/
util.rs

1use proc_macro2::Span;
2use syn::{punctuated::Punctuated, ItemEnum, Token, Variant};
3
4use super::{
5    attr::{Attr, EnumAttrs, RenameAllAttr},
6    case::RenameRule,
7};
8
9pub fn get_rename_rule(input: &ItemEnum) -> syn::Result<RenameRule> {
10    let rules: Vec<_> = input
11        .attrs
12        .iter()
13        .filter(|attr| attr.path().is_ident("ruma_enum"))
14        .map(|attr| attr.parse_args::<RenameAllAttr>().map(RenameAllAttr::into_inner))
15        .collect::<syn::Result<_>>()?;
16
17    match rules.len() {
18        0 => Ok(RenameRule::None),
19        1 => Ok(rules[0]),
20        _ => Err(syn::Error::new(
21            Span::call_site(),
22            "found multiple ruma_enum(rename_all) attributes",
23        )),
24    }
25}
26
27pub fn get_enum_attributes(input: &Variant) -> syn::Result<EnumAttrs> {
28    let mut attributes = EnumAttrs::default();
29
30    for attr in &input.attrs {
31        if !attr.path().is_ident("ruma_enum") {
32            continue;
33        }
34
35        let enum_attrs = attr.parse_args_with(Punctuated::<_, Token![,]>::parse_terminated)?;
36        for enum_attr in enum_attrs {
37            match enum_attr {
38                Attr::Rename(s) => {
39                    if attributes.rename.is_some() {
40                        return Err(syn::Error::new(
41                            Span::call_site(),
42                            "found multiple ruma_enum(rename) attributes",
43                        ));
44                    }
45                    attributes.rename = Some(s);
46                }
47                Attr::Alias(s) => {
48                    attributes.aliases.push(s);
49                }
50            }
51        }
52    }
53
54    Ok(attributes)
55}