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