Crates.io | attribute-derive |
lib.rs | attribute-derive |
version | 0.10.2 |
source | src |
created_at | 2022-02-06 16:54:08.235658 |
updated_at | 2024-10-30 22:24:54.776255 |
description | Clap like parsing for attributes in proc-macros |
homepage | |
repository | https://github.com/ModProg/attribute-derive |
max_upload_size | |
id | 527921 |
size | 79,237 |
Basically clap for attribute macros:
use attribute_derive::Attribute;
use syn::Type;
#[derive(Attribute)]
#[attribute(ident = collection)]
#[attribute(error(missing_field = "`{field}` was not specified"))]
struct CollectionAttribute {
// Options are optional by default (will be set to None if not specified)
authority: Option<String>,
name: String,
// Any type implementing default can be flagged as default
// This will be set to Vec::default() when not specified
#[attribute(optional)]
views: Vec<Type>,
// Booleans can be used without assigning a value, i.e., as a flag.
// If omitted they are set to false
some_flag: bool,
}
Will be able to parse an attribute like this:
#[collection(authority="Some String", name = r#"Another string"#, views = [Option, ()])]
There are some limitations in syntax parsing that will be lifted future releases.
#[attr(42, 3.14, "hi")]
#[attr(view(a = "test"))]
key: value
There are multiple ways of parsing a struct deriving Attribute
.
For helper attributes there is:
Attribute::from_attributes
which takes in an IntoIterator<Item = &'a syn::Attribute
(e.g. a &Vec<syn::Attribute>
). Most useful for derive macros.Attribute::remove_attributes
which takes an &mut Vec<syn::Attribute>
and does not only parse the Attribute
but also removes those matching. Useful for helper
attributes for proc macros, where the helper attributes need to be removed.For parsing a single TokenStream
e.g. for parsing the proc macro input there a two ways:
Attribute::from_args
taking in a TokenStream
derive(Attribute)
also derives Parse
so you can use the parse API,
e.g. with parse_macro_input!(tokens as Attribute)
.