zvariant_utils-1.1.0/.cargo_vcs_info.json0000644000000001540000000000100141110ustar { "git": { "sha1": "25876f399b068749c337374505c35e92dc9e5872" }, "path_in_vcs": "zvariant_utils" }zvariant_utils-1.1.0/Cargo.toml0000644000000021530000000000100121100ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.75" name = "zvariant_utils" version = "1.1.0" authors = [ "Zeeshan Ali Khan ", "turbocooler ", ] description = "Various utilities used internally by the zvariant crate." readme = "README.md" keywords = [ "D-Bus", "DBus", "IPC", "GVariant", ] categories = [ "data-structures", "encoding", "parsing", ] license = "MIT" repository = "https://github.com/dbus2/zbus/" [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0.21" [dependencies.syn] version = "1.0.103" features = [ "extra-traits", "full", ] zvariant_utils-1.1.0/Cargo.toml.orig000064400000000000000000000011031046102023000155630ustar 00000000000000[package] name = "zvariant_utils" version = "1.1.0" authors = [ "Zeeshan Ali Khan ", "turbocooler ", ] edition = "2021" rust-version = "1.75" description = "Various utilities used internally by the zvariant crate." repository = "https://github.com/dbus2/zbus/" keywords = ["D-Bus", "DBus", "IPC", "GVariant"] license = "MIT" categories = ["data-structures", "encoding", "parsing"] readme = "README.md" [dependencies] proc-macro2 = "1.0" syn = { version = "1.0.103", features = ["extra-traits", "full"] } quote = "1.0.21" zvariant_utils-1.1.0/LICENSE000064400000000000000000000017771046102023000137220ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. zvariant_utils-1.1.0/README.md000064400000000000000000000007021046102023000141570ustar 00000000000000# zvariant_utils [![](https://docs.rs/zvariant_utils/badge.svg)](https://docs.rs/zvariant_utils/) [![](https://img.shields.io/crates/v/zvariant_utils)](https://crates.io/crates/zvariant_utils) This crate provides various utilities for [`zvariant`]. ## Stability The API is NOT expected to be stable. The crate, however, will follow semver rules: breaking changes would cause a major version bump. [`zvariant`]: https://crates.io/crates/zvariant zvariant_utils-1.1.0/src/case.rs000064400000000000000000000022431046102023000147520ustar 00000000000000//! Contains utilities used to convert strings between different cases. /// Convert to pascal or camel case, assuming snake case. /// /// If `s` is already in pascal or camel case, should yield the same result. pub fn pascal_or_camel_case(s: &str, is_pascal_case: bool) -> String { let mut result = String::new(); let mut capitalize = is_pascal_case; let mut first = true; for ch in s.chars() { if ch == '_' { capitalize = true; } else if capitalize { result.push(ch.to_ascii_uppercase()); capitalize = false; } else if first && !is_pascal_case { result.push(ch.to_ascii_lowercase()); } else { result.push(ch); } if first { first = false; } } result } /// Convert to snake case, assuming pascal case. /// /// If `s` is already in snake case, should yield the same result. pub fn snake_case(s: &str) -> String { let mut snake = String::new(); for ch in s.chars() { if ch.is_ascii_uppercase() && !snake.is_empty() { snake.push('_'); } snake.push(ch.to_ascii_lowercase()); } snake } zvariant_utils-1.1.0/src/lib.rs000064400000000000000000000001361046102023000146040ustar 00000000000000//! Various utilities used by the `zvariant` crate and others. pub mod case; pub mod macros; zvariant_utils-1.1.0/src/macros.rs000064400000000000000000000475341046102023000153370ustar 00000000000000use 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> { 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> { 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> { 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>> { 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 { 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) } } /// The `AttrParse` trait is a generic interface for attribute structures. /// This is only implemented directly by the [`crate::def_attrs`] macro, within the `zbus_macros` /// crate. This macro allows the parsing of multiple variants when using the [`crate::old_new`] /// macro pattern, using `` as a bounds check at compile time. pub trait AttrParse { fn parse_meta(&mut self, meta: &::syn::Meta) -> ::syn::Result<()>; fn parse_nested_metas<'a, I>(iter: I) -> syn::Result where I: ::std::iter::IntoIterator, Self: Sized; fn parse(attrs: &[::syn::Attribute]) -> ::syn::Result where Self: Sized; } /// 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> { 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, /// bar: Option, /// baz: bool, /// } /// /// #[derive(Hash)] /// #[derive(Default, Clone, Debug)] /// struct FieldAttributes { /// field_attr: Option, /// } /// ``` /// /// `foo` and `bar` attributes got translated to fields with `Option` 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}; (@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 ::zvariant_utils::macros::AttrParse for $name { fn parse_meta( &mut self, meta: &::syn::Meta ) -> ::syn::Result<()> { self.parse_meta(meta) } fn parse_nested_metas<'a, I>(iter: I) -> syn::Result where I: ::std::iter::IntoIterator, Self: Sized { Self::parse_nested_metas(iter) } fn parse(attrs: &[::syn::Attribute]) -> ::syn::Result where Self: Sized { Self::parse(attrs) } } 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 where I: ::std::iter::IntoIterator { 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 { 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, } } #[macro_export] /// The `old_new` macro desognates three structures: /// /// 1. The enum wrapper name. /// 2. The old type name. /// 3. The new type name. /// /// The macro creates a new enumeration with two variants: `::Old(...)` and `::New(...)` /// The old and new variants contain the old and new type, respectively. /// It also implements `From<$old>` and `From<$new>` for the new wrapper type. /// This is to facilitate the deprecation of extremely similar structures that have only a few /// differences, and to be able to warn the user of the library when the `::Old(...)` variant has /// been used. macro_rules! old_new { ($attr_wrapper:ident, $old:ty, $new:ty) => { pub enum $attr_wrapper { Old($old), New($new), } impl From<$old> for $attr_wrapper { fn from(old: $old) -> Self { Self::Old(old) } } impl From<$new> for $attr_wrapper { fn from(new: $new) -> Self { Self::New(new) } } }; }