Skip to main content

zvariant_utils/derive/
attrs.rs

1use crate::{case, def_attrs};
2
3/// Parses the `crate` attribute value into a path.
4pub fn parse_crate_path(crate_attr: Option<&str>) -> Result<Option<syn::Path>, syn::Error> {
5    crate_attr.map(syn::parse_str).transpose()
6}
7
8/// Renames `ident` per the `rename`/`rename_all` attribute values, `rename` taking precedence.
9pub fn rename_identifier(
10    ident: String,
11    span: proc_macro2::Span,
12    rename_attr: Option<String>,
13    rename_all_attr: Option<&str>,
14) -> Result<String, syn::Error> {
15    if let Some(name) = rename_attr {
16        Ok(name)
17    } else {
18        match rename_all_attr {
19            Some("lowercase") => Ok(ident.to_ascii_lowercase()),
20            Some("UPPERCASE") => Ok(ident.to_ascii_uppercase()),
21            Some("PascalCase") => Ok(case::pascal_or_camel_case(&ident, true)),
22            Some("camelCase") => Ok(case::pascal_or_camel_case(&ident, false)),
23            Some("snake_case") => Ok(case::snake_or_kebab_case(&ident, true)),
24            Some("kebab-case") => Ok(case::snake_or_kebab_case(&ident, false)),
25            None => Ok(ident),
26            Some(other) => Err(syn::Error::new(
27                span,
28                format!("invalid `rename_all` attribute value {other}"),
29            )),
30        }
31    }
32}
33
34// The generated `parse()` is hardwired to the `zbus`/`zvariant` lists named below, so shared
35// codegen that may run under another namespace (e.g. a future `#[zgvariant(...)]`) must parse
36// via `parse_with_lists(attrs, config.attr_lists)` instead, or it will silently ignore that
37// namespace's attributes.
38def_attrs! {
39    crate zbus, zvariant;
40
41    /// Attributes defined on structures.
42    pub StructAttributes("struct") { signature str, rename_all str, deny_unknown_fields none, crate_path str };
43    /// Attributes defined on fields.
44    pub FieldAttributes("field") { rename str };
45    /// Attributes defined on enumerations.
46    pub EnumAttributes("enum") { signature str, rename_all str, crate_path str };
47    /// Attributes defined on variants.
48    pub VariantAttributes("variant") { rename str };
49}