zvariant_utils/macros.rs
1use syn::{
2 punctuated::Punctuated, spanned::Spanned, Attribute, Expr, Lit, LitBool, LitStr, Meta,
3 MetaList, Result, Token, Type, TypePath,
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/// # Calling the macro multiple times
240///
241/// The macro generates static variables with hardcoded names. Calling the macro twice in the same
242/// scope will cause a name alias and thus will fail to compile. You need to place each macro
243/// invocation into a module in that case.
244///
245/// # Errors
246///
247/// The generated parse method checks for some error conditions:
248///
249/// 1. Unknown attributes. When multiple attribute groups are defined in the same macro invocation,
250/// one gets a different error message when providing an attribute from a different attribute
251/// group.
252/// 2. Duplicate attributes.
253/// 3. Missing attribute value or present attribute value when none is expected.
254/// 4. Invalid literal type for attributes with values.
255#[macro_export]
256macro_rules! def_attrs {
257 (@attr_ty str) => {::std::option::Option<::std::string::String>};
258 (@attr_ty bool) => {::std::option::Option<bool>};
259 (@attr_ty [str]) => {::std::option::Option<::std::vec::Vec<::std::string::String>>};
260 (@attr_ty none) => {bool};
261 (@attr_ty {
262 $(#[$m:meta])*
263 $vis:vis $name:ident($what:literal) {
264 $($attr_name:ident $kind:tt),+
265 }
266 }) => {::std::option::Option<$name>};
267 (@match_attr_with $attr_name:ident, $meta:ident, $self:ident, $matched:expr) => {
268 if let ::std::option::Option::Some(value) = $matched? {
269 if $self.$attr_name.is_some() {
270 return ::std::result::Result::Err(::syn::Error::new(
271 $meta.span(),
272 ::std::concat!("duplicate `", ::std::stringify!($attr_name), "` attribute")
273 ));
274 }
275
276 $self.$attr_name = ::std::option::Option::Some(value.value());
277 return Ok(());
278 }
279 };
280 (@match_attr str $attr_name:ident, $meta:ident, $self:ident) => {
281 $crate::def_attrs!(
282 @match_attr_with
283 $attr_name,
284 $meta,
285 $self,
286 $crate::macros::match_attribute_with_str_value(
287 $meta,
288 ::std::stringify!($attr_name),
289 )
290 )
291 };
292 (@match_attr bool $attr_name:ident, $meta:ident, $self:ident) => {
293 $crate::def_attrs!(
294 @match_attr_with
295 $attr_name,
296 $meta,
297 $self,
298 $crate::macros::match_attribute_with_bool_value(
299 $meta,
300 ::std::stringify!($attr_name),
301 )
302 )
303 };
304 (@match_attr [str] $attr_name:ident, $meta:ident, $self:ident) => {
305 if let Some(list) = $crate::macros::match_attribute_with_str_list_value(
306 $meta,
307 ::std::stringify!($attr_name),
308 )? {
309 if $self.$attr_name.is_some() {
310 return ::std::result::Result::Err(::syn::Error::new(
311 $meta.span(),
312 concat!("duplicate `", stringify!($attr_name), "` attribute")
313 ));
314 }
315
316 $self.$attr_name = Some(list);
317 return Ok(());
318 }
319 };
320 (@match_attr none $attr_name:ident, $meta:ident, $self:ident) => {
321 if $crate::macros::match_attribute_without_value(
322 $meta,
323 ::std::stringify!($attr_name),
324 )? {
325 if $self.$attr_name {
326 return ::std::result::Result::Err(::syn::Error::new(
327 $meta.span(),
328 concat!("duplicate `", stringify!($attr_name), "` attribute")
329 ));
330 }
331
332 $self.$attr_name = true;
333 return Ok(());
334 }
335 };
336 (@match_attr {
337 $(#[$m:meta])*
338 $vis:vis $name:ident($what:literal) $body:tt
339 } $attr_name:ident, $meta:expr, $self:ident) => {
340 if $meta.path().is_ident(::std::stringify!($attr_name)) {
341 if $self.$attr_name.is_some() {
342 return ::std::result::Result::Err(::syn::Error::new(
343 $meta.span(),
344 concat!("duplicate `", stringify!($attr_name), "` attribute")
345 ));
346 }
347
348 return match $meta {
349 ::syn::Meta::List(meta) => {
350 $self.$attr_name = ::std::option::Option::Some($name::parse_nested_metas(
351 meta.parse_args_with(::syn::punctuated::Punctuated::<::syn::Meta, ::syn::Token![,]>::parse_terminated)?
352 )?);
353 ::std::result::Result::Ok(())
354 }
355 ::syn::Meta::Path(_) => {
356 $self.$attr_name = ::std::option::Option::Some($name::default());
357 ::std::result::Result::Ok(())
358 }
359 ::syn::Meta::NameValue(_) => Err(::syn::Error::new(
360 $meta.span(),
361 ::std::format!(::std::concat!(
362 "attribute `", ::std::stringify!($attr_name),
363 "` must be either a list or a path"
364 )),
365 ))
366 };
367 }
368 };
369 (@def_ty str) => {};
370 (@def_ty bool) => {};
371 (@def_ty [str]) => {};
372 (@def_ty none) => {};
373 (
374 @def_ty {
375 $(#[$m:meta])*
376 $vis:vis $name:ident($what:literal) {
377 $($attr_name:ident $kind:tt),+
378 }
379 }
380 ) => {
381 // Recurse further to potentially define nested lists.
382 $($crate::def_attrs!(@def_ty $kind);)+
383
384 $crate::def_attrs!(
385 @def_struct
386 $(#[$m])*
387 $vis $name($what) {
388 $($attr_name $kind),+
389 }
390 );
391 };
392 (
393 @def_struct
394 $(#[$m:meta])*
395 $vis:vis $name:ident($what:literal) {
396 $($attr_name:ident $kind:tt),+
397 }
398 ) => {
399 $(#[$m])*
400 #[derive(Default, Clone, Debug)]
401 $vis struct $name {
402 $(pub $attr_name: $crate::def_attrs!(@attr_ty $kind)),+
403 }
404
405 impl $name {
406 pub fn parse_meta(
407 &mut self,
408 meta: &::syn::Meta
409 ) -> ::syn::Result<()> {
410 use ::syn::spanned::Spanned;
411
412 // This creates subsequent if blocks for simplicity. Any block that is taken
413 // either returns an error or sets the attribute field and returns success.
414 $(
415 $crate::def_attrs!(@match_attr $kind $attr_name, meta, self);
416 )+
417
418 // None of the if blocks have been taken, return the appropriate error.
419 let err = if ALLOWED_ATTRS.iter().any(|attr| meta.path().is_ident(attr)) {
420 ::std::format!(
421 ::std::concat!("attribute `{}` is not allowed on ", $what),
422 meta.path().get_ident().unwrap()
423 )
424 } else {
425 ::std::format!("unknown attribute `{}`", meta.path().get_ident().unwrap())
426 };
427 return ::std::result::Result::Err(::syn::Error::new(meta.span(), err));
428 }
429
430 pub fn parse_nested_metas<I>(iter: I) -> syn::Result<Self>
431 where
432 I: ::std::iter::IntoIterator<Item=::syn::Meta>
433 {
434 let mut parsed = $name::default();
435 for nested_meta in iter {
436 parsed.parse_meta(&nested_meta)?;
437 }
438
439 Ok(parsed)
440 }
441
442 pub fn parse(attrs: &[::syn::Attribute]) -> ::syn::Result<Self> {
443 let mut parsed = $name::default();
444
445 for nested_meta in $crate::macros::iter_meta_lists(
446 attrs,
447 ALLOWED_LISTS,
448 )? {
449 parsed.parse_meta(&nested_meta)?;
450 }
451
452 Ok(parsed)
453 }
454 }
455 };
456 (
457 crate $($list_name:ident),+;
458 $(
459 $(#[$m:meta])*
460 $vis:vis $name:ident($what:literal) {
461 $($attr_name:ident $kind:tt),+
462 }
463 );+;
464 ) => {
465 static ALLOWED_ATTRS: &[&'static str] = &[
466 $($(::std::stringify!($attr_name),)+)+
467 ];
468
469 static ALLOWED_LISTS: &[&'static str] = &[
470 $(::std::stringify!($list_name),)+
471 ];
472
473 $(
474 $crate::def_attrs!(
475 @def_ty {
476 $(#[$m])*
477 $vis $name($what) {
478 $($attr_name $kind),+
479 }
480 }
481 );
482 )+
483 }
484}
485
486/// Checks if a [`Type`]'s identifier is "Option".
487pub fn ty_is_option(ty: &Type) -> bool {
488 match ty {
489 Type::Path(TypePath {
490 path: syn::Path { segments, .. },
491 ..
492 }) => segments.last().unwrap().ident == "Option",
493 _ => false,
494 }
495}