Derive-Attribute

A set of macros to automatically deserialize standard attributes
-
Compatible with all major versions of Syn
-
Supports custom deserialization
-
Can return multiple errors at once
-
Allows for flexible attribute syntax
Syn Compatibility
This crate is meant to be used in conjunction with Syn within a procedural macro crate.
A major version of Syn can be selected as a feature like: features = ["syn_2"]
.
Note: A Syn version must be selected
Flexible Attribute Syntax
Implicit Booleans
#[some_attr(is_bool)]
can also be written as #[some_attr(is_bool = true)]
Seperated Lists
#[some_attr(list(key_a = "value", key_b = 123))]
can also be written as
#[some_attr(list(key_a = "value"))]
#[some_attr(list(key_b = 123))]
Multiple Errors
Most macros will only return one attribute error at a time. This crate's macros can return multiple errors at once resulting in a better developer experience.
Custom Deserialization
Any type that implements TryFromMeta
can be used as a valid attribute type.
Although Its recommended that you use CustomArgFromMeta
instead in order to simplify the implementation.
See example
Attr Arguments
The #[attr()]
attribute can be added to the attribute struct or its fields to add additional options.
The full list of arguments are:
name [str] - Renames the field.
default [bool/str] - Uses a default value if the argument isn't found.
If its a boolean, the type's implementation of Default::default will be used.
If its a string, it must be a path to a function that returns the type.
Usage
Our attribute type is declared in a procedural macro crate:
// We set the attribute name to 'my_attr'
It can then be used to parse the following attribute using the from_attrs method:
lets look at the same attribute used in a derive macro
Basic derive
procedural macro crate:
use ;
use TokenStream as TokenStream2;
use quote;
use ;
Another crate using our macro
;
Now lets add our own argument type
Custom Deserialization
proc-macro crate:
use ;
// Any type that implements 'TryFromMeta' can be deserialized however its a bit verbose
// In order to simplify the implementation we can implement 'CustomArgFromMeta' instead and wrap our type in the 'CustomArg' struct
Our attribute struct now looks like this:
Another crate using our macro:
;