1use syn::{
2 punctuated::Punctuated, spanned::Spanned, Attribute, Expr, Lit, LitBool, LitStr, Meta,
3 MetaList, Result, Token, Type, TypePath,
4};
5
6fn find_attribute_meta(attrs: &[Attribute], attr_name: &str) -> Result<Option<MetaList>> {
8 let meta = match attrs.iter().find(|a| a.path().is_ident(attr_name)) {
9 Some(a) => &a.meta,
10 _ => return Ok(None),
11 };
12 match meta.require_list() {
13 Ok(n) => Ok(Some(n.clone())),
14 _ => Err(syn::Error::new(
15 meta.span(),
16 format!("{attr_name} meta must specify a meta list"),
17 )),
18 }
19}
20
21fn get_meta_value<'a>(meta: &'a Meta, attr: &str) -> Result<&'a Lit> {
22 let meta = meta.require_name_value()?;
23 get_expr_lit(&meta.value, attr)
24}
25
26fn get_expr_lit<'a>(expr: &'a Expr, attr: &str) -> Result<&'a Lit> {
27 match expr {
28 Expr::Lit(l) => Ok(&l.lit),
29 Expr::Group(group) => get_expr_lit(&group.expr, attr),
31 expr => Err(syn::Error::new(
32 expr.span(),
33 format!("attribute `{attr}`'s value must be a literal"),
34 )),
35 }
36}
37
38pub 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) => Ok(Some(value)),
55 _ => Err(syn::Error::new(
56 meta.span(),
57 format!("value of the `{attr}` attribute must be a string literal"),
58 )),
59 }
60}
61
62pub 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) => Ok(Some(value)),
76 other => Err(syn::Error::new(
77 other.span(),
78 format!("value of the `{attr}` attribute must be a boolean literal"),
79 )),
80 }
81 } else {
82 Ok(None)
83 }
84}
85
86pub 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 = meta.require_list()?;
89 let values = list
90 .parse_args_with(Punctuated::<LitStr, Token![,]>::parse_terminated)?
91 .into_iter()
92 .map(|s| s.value())
93 .collect();
94
95 Ok(Some(values))
96 } else {
97 Ok(None)
98 }
99}
100
101pub 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
116pub 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
133pub fn iter_meta_lists(attrs: &[Attribute], list_name: &str) -> Result<impl Iterator<Item = Meta>> {
136 let meta = find_attribute_meta(attrs, list_name)?;
137
138 Ok(meta
139 .map(|meta| meta.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated))
140 .transpose()?
141 .into_iter()
142 .flatten())
143}
144
145#[macro_export]
242macro_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 $($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 $(
419 $crate::def_attrs!(@match_attr $kind $attr_name, meta, self);
420 )+
421
422 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
486pub 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}
496
497#[macro_export]
498macro_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}