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