zvariant_utils/
macros.rs

1use syn::{
2    Attribute, Expr, Lit, LitBool, LitStr, Meta, MetaList, Result, Token, Type, TypePath,
3    punctuated::Punctuated, spanned::Spanned,
4};
5
6// find the #[@attr_name] attribute in @attrs
7fn find_attribute_meta(attrs: &[Attribute], attr_names: &[&str]) -> Result<Option<MetaList>> {
8    // Find attribute with path matching one of the allowed attribute names,
9    let search_result = attrs.iter().find_map(|a| {
10        attr_names
11            .iter()
12            .find_map(|attr_name| a.path().is_ident(attr_name).then_some((attr_name, a)))
13    });
14
15    let (attr_name, meta) = match search_result {
16        Some((attr_name, a)) => (attr_name, &a.meta),
17        _ => return Ok(None),
18    };
19    match meta.require_list() {
20        Ok(n) => Ok(Some(n.clone())),
21        _ => Err(syn::Error::new(
22            meta.span(),
23            format!("{attr_name} meta must specify a meta list"),
24        )),
25    }
26}
27
28fn get_meta_value<'a>(meta: &'a Meta, attr: &str) -> Result<&'a Lit> {
29    let meta = meta.require_name_value()?;
30    get_expr_lit(&meta.value, attr)
31}
32
33fn get_expr_lit<'a>(expr: &'a Expr, attr: &str) -> Result<&'a Lit> {
34    match expr {
35        Expr::Lit(l) => Ok(&l.lit),
36        // Macro variables are put in a group.
37        Expr::Group(group) => get_expr_lit(&group.expr, attr),
38        expr => Err(syn::Error::new(
39            expr.span(),
40            format!("attribute `{attr}`'s value must be a literal"),
41        )),
42    }
43}
44
45/// Compares `ident` and `attr` and in case they match ensures `value` is `Some` and contains a
46/// [`struct@LitStr`]. Returns `true` in case `ident` and `attr` match, otherwise false.
47///
48/// # Errors
49///
50/// Returns an error in case `ident` and `attr` match but the value is not `Some` or is not a
51/// [`struct@LitStr`].
52pub fn match_attribute_with_str_value<'a>(
53    meta: &'a Meta,
54    attr: &str,
55) -> Result<Option<&'a LitStr>> {
56    if !meta.path().is_ident(attr) {
57        return Ok(None);
58    }
59
60    match get_meta_value(meta, attr)? {
61        Lit::Str(value) => Ok(Some(value)),
62        _ => Err(syn::Error::new(
63            meta.span(),
64            format!("value of the `{attr}` attribute must be a string literal"),
65        )),
66    }
67}
68
69/// Compares `ident` and `attr` and in case they match ensures `value` is `Some` and contains a
70/// [`struct@LitBool`]. Returns `true` in case `ident` and `attr` match, otherwise false.
71///
72/// # Errors
73///
74/// Returns an error in case `ident` and `attr` match but the value is not `Some` or is not a
75/// [`struct@LitBool`].
76pub fn match_attribute_with_bool_value<'a>(
77    meta: &'a Meta,
78    attr: &str,
79) -> Result<Option<&'a LitBool>> {
80    if meta.path().is_ident(attr) {
81        match get_meta_value(meta, attr)? {
82            Lit::Bool(value) => Ok(Some(value)),
83            other => Err(syn::Error::new(
84                other.span(),
85                format!("value of the `{attr}` attribute must be a boolean literal"),
86            )),
87        }
88    } else {
89        Ok(None)
90    }
91}
92
93pub fn match_attribute_with_str_list_value(meta: &Meta, attr: &str) -> Result<Option<Vec<String>>> {
94    if meta.path().is_ident(attr) {
95        let list = meta.require_list()?;
96        let values = list
97            .parse_args_with(Punctuated::<LitStr, Token![,]>::parse_terminated)?
98            .into_iter()
99            .map(|s| s.value())
100            .collect();
101
102        Ok(Some(values))
103    } else {
104        Ok(None)
105    }
106}
107
108/// Compares `ident` and `attr` and in case they match ensures `value` is `None`. Returns `true` in
109/// case `ident` and `attr` match, otherwise false.
110///
111/// # Errors
112///
113/// Returns an error in case `ident` and `attr` match but the value is not `None`.
114pub fn match_attribute_without_value(meta: &Meta, attr: &str) -> Result<bool> {
115    if meta.path().is_ident(attr) {
116        meta.require_path_only()?;
117        Ok(true)
118    } else {
119        Ok(false)
120    }
121}
122
123/// Returns an iterator over the contents of all [`MetaList`]s with the specified identifier in an
124/// array of [`Attribute`]s.
125pub fn iter_meta_lists(
126    attrs: &[Attribute],
127    list_names: &[&str],
128) -> Result<impl Iterator<Item = Meta>> {
129    let meta = find_attribute_meta(attrs, list_names)?;
130
131    Ok(meta
132        .map(|meta| meta.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated))
133        .transpose()?
134        .into_iter()
135        .flatten())
136}
137
138/// Generates one or more structures used for parsing attributes in proc macros.
139///
140/// Generated structures have one static method called parse that accepts a slice of [`Attribute`]s.
141/// The method finds attributes that contain meta lists (look like `#[your_custom_ident(...)]`) and
142/// fills a newly allocated structure with values of the attributes if any.
143///
144/// The expected input looks as follows:
145///
146/// ```
147/// # use zvariant_utils::def_attrs;
148/// def_attrs! {
149///     crate zvariant;
150///
151///     /// A comment.
152///     pub StructAttributes("struct") { foo str, bar str, baz none };
153///     #[derive(Hash)]
154///     FieldAttributes("field") { field_attr bool };
155/// }
156/// ```
157///
158/// Here we see multiple entries: an entry for an attributes group called `StructAttributes` and
159/// another one for `FieldAttributes`. The former has three defined attributes: `foo`, `bar` and
160/// `baz`. The generated structures will look like this in that case:
161///
162/// ```
163/// /// A comment.
164/// #[derive(Default, Clone, Debug)]
165/// pub struct StructAttributes {
166///     foo: Option<String>,
167///     bar: Option<String>,
168///     baz: bool,
169/// }
170///
171/// #[derive(Hash)]
172/// #[derive(Default, Clone, Debug)]
173/// struct FieldAttributes {
174///     field_attr: Option<bool>,
175/// }
176/// ```
177///
178/// `foo` and `bar` attributes got translated to fields with `Option<String>` type which contain the
179/// value of the attribute when one is specified. They are marked with `str` keyword which stands
180/// for string literals. The `baz` attribute, on the other hand, has `bool` type because it's an
181/// attribute without value marked by the `none` keyword.
182///
183/// Currently the following literals are supported:
184///
185/// * `str` - string literals;
186/// * `bool` - boolean literals;
187/// * `[str]` - lists of string literals (`#[macro_name(foo("bar", "baz"))]`);
188/// * `none` - no literal at all, the attribute is specified alone.
189///
190/// The strings between braces are embedded into error messages produced when an attribute defined
191/// for one attribute group is used on another group where it is not defined. For example, if the
192/// `field_attr` attribute was encountered by the generated `StructAttributes::parse` method, the
193/// error message would say that it "is not allowed on structs".
194///
195/// # Nested attribute lists
196///
197/// It is possible to create nested lists for specific attributes. This is done as follows:
198///
199/// ```
200/// # use zvariant_utils::def_attrs;
201/// def_attrs! {
202///     crate zvariant;
203///
204///     pub OuterAttributes("outer") {
205///         simple_attr bool,
206///         nested_attr {
207///             /// An example of nested attributes.
208///             pub InnerAttributes("inner") {
209///                 inner_attr str
210///             }
211///         }
212///     };
213/// }
214/// ```
215///
216/// The syntax for inner attributes is the same as for the outer attributes, but you can specify
217/// only one inner attribute per outer attribute.
218///
219/// # Using attribute names for attribute lists
220///
221/// It is possible to use multiple different "crate" names as follows:
222///
223/// ```
224/// # use zvariant_utils::def_attrs;
225/// def_attrs! {
226///     crate zvariant, zbus;
227///
228///     pub FooAttributes("foo") {
229///         simple_attr bool
230///     };
231/// }
232/// ```
233///
234/// It will be possible to use both `#[zvariant(...)]` and `#[zbus(...)]` attributes with
235/// `FooAttributes`.
236///
237/// Don't forget to add all the supported attributes to your proc macro definition.
238///
239/// # Supporting the `crate` attribute
240///
241/// The macro supports a special `crate_path` field that maps to the `crate` attribute name.
242/// This allows users to specify custom crate paths (e.g., when they've renamed zbus/zvariant
243/// in their Cargo.toml). Example:
244///
245/// ```
246/// # use zvariant_utils::def_attrs;
247/// def_attrs! {
248///     crate zvariant;
249///
250///     pub MyAttributes("struct") {
251///         crate_path str
252///     };
253/// }
254/// ```
255///
256/// Users can then write `#[zvariant(crate = "my_renamed_crate")]` in their code.
257/// The field is named `crate_path` but matches the attribute `crate`.
258/// Access the value via `attrs.crate_path`.
259///
260/// # Calling the macro multiple times
261///
262/// The macro generates static variables with hardcoded names. Calling the macro twice in the same
263/// scope will cause a name alias and thus will fail to compile. You need to place each macro
264/// invocation into a module in that case.
265///
266/// # Errors
267///
268/// The generated parse method checks for some error conditions:
269///
270/// 1. Unknown attributes. When multiple attribute groups are defined in the same macro invocation,
271///    one gets a different error message when providing an attribute from a different attribute
272///    group.
273/// 2. Duplicate attributes.
274/// 3. Missing attribute value or present attribute value when none is expected.
275/// 4. Invalid literal type for attributes with values.
276#[macro_export]
277macro_rules! def_attrs {
278    // Helper to get the attribute name string (for ALLOWED_ATTRS and matching)
279    // Special case: crate_path field -> matches "crate" attribute
280    (@attr_name crate_path $kind:tt) => { "crate" };
281    (@attr_name $attr_name:ident $kind:tt) => { ::std::stringify!($attr_name) };
282
283    (@attr_ty str) => {::std::option::Option<::std::string::String>};
284    (@attr_ty bool) => {::std::option::Option<bool>};
285    (@attr_ty [str]) => {::std::option::Option<::std::vec::Vec<::std::string::String>>};
286    (@attr_ty none) => {bool};
287    (@attr_ty {
288        $(#[$m:meta])*
289        $vis:vis $name:ident($what:literal) {
290            $($attr_name:ident $kind:tt),+
291        }
292    }) => {::std::option::Option<$name>};
293
294    (@match_attr_with $attr_name:ident, $meta:ident, $self:ident, $matched:expr, $display_name:expr) => {
295        if let ::std::option::Option::Some(value) = $matched? {
296            if $self.$attr_name.is_some() {
297                return ::std::result::Result::Err(::syn::Error::new(
298                    $meta.span(),
299                    ::std::format!("duplicate `{}` attribute", $display_name)
300                ));
301            }
302
303            $self.$attr_name = ::std::option::Option::Some(value.value());
304            return Ok(());
305        }
306    };
307
308    // Special case: crate_path field matches "crate" attribute
309    (@match_attr str crate_path, $meta:ident, $self:ident) => {
310        $crate::def_attrs!(
311            @match_attr_with
312            crate_path,
313            $meta,
314            $self,
315            $crate::macros::match_attribute_with_str_value($meta, "crate"),
316            "crate"
317        )
318    };
319    (@match_attr str $attr_name:ident, $meta:ident, $self:ident) => {
320        $crate::def_attrs!(
321            @match_attr_with
322            $attr_name,
323            $meta,
324            $self,
325            $crate::macros::match_attribute_with_str_value(
326                $meta,
327                ::std::stringify!($attr_name),
328            ),
329            ::std::stringify!($attr_name)
330        )
331    };
332    (@match_attr bool $attr_name:ident, $meta:ident, $self:ident) => {
333        $crate::def_attrs!(
334            @match_attr_with
335            $attr_name,
336            $meta,
337            $self,
338            $crate::macros::match_attribute_with_bool_value(
339                $meta,
340                ::std::stringify!($attr_name),
341            ),
342            ::std::stringify!($attr_name)
343        )
344    };
345    (@match_attr [str] $attr_name:ident, $meta:ident, $self:ident) => {
346        if let Some(list) = $crate::macros::match_attribute_with_str_list_value(
347            $meta,
348            ::std::stringify!($attr_name),
349        )? {
350            if $self.$attr_name.is_some() {
351                return ::std::result::Result::Err(::syn::Error::new(
352                    $meta.span(),
353                    concat!("duplicate `", stringify!($attr_name), "` attribute")
354                ));
355            }
356
357            $self.$attr_name = Some(list);
358            return Ok(());
359        }
360    };
361    (@match_attr none $attr_name:ident, $meta:ident, $self:ident) => {
362        if $crate::macros::match_attribute_without_value(
363            $meta,
364            ::std::stringify!($attr_name),
365        )? {
366            if $self.$attr_name {
367                return ::std::result::Result::Err(::syn::Error::new(
368                    $meta.span(),
369                    concat!("duplicate `", stringify!($attr_name), "` attribute")
370                ));
371            }
372
373            $self.$attr_name = true;
374            return Ok(());
375        }
376    };
377    (@match_attr {
378        $(#[$m:meta])*
379        $vis:vis $name:ident($what:literal) $body:tt
380    } $attr_name:ident, $meta:expr, $self:ident) => {
381        if $meta.path().is_ident(::std::stringify!($attr_name)) {
382            if $self.$attr_name.is_some() {
383                return ::std::result::Result::Err(::syn::Error::new(
384                    $meta.span(),
385                    concat!("duplicate `", stringify!($attr_name), "` attribute")
386                ));
387            }
388
389            return match $meta {
390                ::syn::Meta::List(meta) => {
391                        $self.$attr_name = ::std::option::Option::Some($name::parse_nested_metas(
392                            meta.parse_args_with(::syn::punctuated::Punctuated::<::syn::Meta, ::syn::Token![,]>::parse_terminated)?
393                        )?);
394                        ::std::result::Result::Ok(())
395                    }
396                    ::syn::Meta::Path(_) => {
397                        $self.$attr_name = ::std::option::Option::Some($name::default());
398                        ::std::result::Result::Ok(())
399                    }
400                    ::syn::Meta::NameValue(_) => Err(::syn::Error::new(
401                        $meta.span(),
402                        ::std::format!(::std::concat!(
403                            "attribute `", ::std::stringify!($attr_name),
404                            "` must be either a list or a path"
405                        )),
406                    ))
407                };
408        }
409    };
410    (@def_ty str) => {};
411    (@def_ty bool) => {};
412    (@def_ty [str]) => {};
413    (@def_ty none) => {};
414    (
415        @def_ty {
416            $(#[$m:meta])*
417            $vis:vis $name:ident($what:literal) {
418                $($attr_name:ident $kind:tt),+
419            }
420        }
421    ) => {
422        // Recurse further to potentially define nested lists.
423        $($crate::def_attrs!(@def_ty $kind);)+
424
425        $crate::def_attrs!(
426            @def_struct
427            $(#[$m])*
428            $vis $name($what) {
429                $($attr_name $kind),+
430            }
431        );
432    };
433    (
434        @def_struct
435        $(#[$m:meta])*
436        $vis:vis $name:ident($what:literal) {
437            $($attr_name:ident $kind:tt),+
438        }
439    ) => {
440        $(#[$m])*
441        #[derive(Default, Clone, Debug)]
442        $vis struct $name {
443            $(pub $attr_name: $crate::def_attrs!(@attr_ty $kind)),+
444        }
445
446        impl $name {
447            pub fn parse_meta(
448                &mut self,
449                meta: &::syn::Meta
450            ) -> ::syn::Result<()> {
451                use ::syn::spanned::Spanned;
452
453                // This creates subsequent if blocks for simplicity. Any block that is taken
454                // either returns an error or sets the attribute field and returns success.
455                $(
456                    $crate::def_attrs!(@match_attr $kind $attr_name, meta, self);
457                )+
458
459                // None of the if blocks have been taken, return the appropriate error.
460                let err = if ALLOWED_ATTRS.iter().any(|attr| meta.path().is_ident(attr)) {
461                    ::std::format!(
462                        ::std::concat!("attribute `{}` is not allowed on ", $what),
463                        meta.path().get_ident().unwrap()
464                    )
465                } else {
466                    ::std::format!("unknown attribute `{}`", meta.path().get_ident().unwrap())
467                };
468                return ::std::result::Result::Err(::syn::Error::new(meta.span(), err));
469            }
470
471            pub fn parse_nested_metas<I>(iter: I) -> syn::Result<Self>
472            where
473                I: ::std::iter::IntoIterator<Item=::syn::Meta>
474            {
475                let mut parsed = $name::default();
476                for nested_meta in iter {
477                    parsed.parse_meta(&nested_meta)?;
478                }
479
480                Ok(parsed)
481            }
482
483            pub fn parse(attrs: &[::syn::Attribute]) -> ::syn::Result<Self> {
484                let mut parsed = $name::default();
485
486                for nested_meta in $crate::macros::iter_meta_lists(
487                    attrs,
488                    ALLOWED_LISTS,
489                )? {
490                    parsed.parse_meta(&nested_meta)?;
491                }
492
493                Ok(parsed)
494            }
495        }
496    };
497    (
498        crate $($list_name:ident),+;
499        $(
500            $(#[$m:meta])*
501            $vis:vis $name:ident($what:literal) {
502                $($attr_name:ident $kind:tt),+
503            }
504        );+;
505    ) => {
506        static ALLOWED_ATTRS: &[&'static str] = &[
507            $($($crate::def_attrs!(@attr_name $attr_name $kind),)+)+
508        ];
509
510        static ALLOWED_LISTS: &[&'static str] = &[
511            $(::std::stringify!($list_name),)+
512        ];
513
514        $(
515            $crate::def_attrs!(
516                @def_ty {
517                    $(#[$m])*
518                    $vis $name($what) {
519                        $($attr_name $kind),+
520                    }
521                }
522            );
523        )+
524    }
525}
526
527/// Checks if a [`Type`]'s identifier is "Option".
528pub fn ty_is_option(ty: &Type) -> bool {
529    match ty {
530        Type::Path(TypePath {
531            path: syn::Path { segments, .. },
532            ..
533        }) => segments.last().unwrap().ident == "Option",
534        _ => false,
535    }
536}