Expand description
§macro_rules_attr
Use declarative macros as proc_macro attributes. (#[apply] your macro_rules!)
§Usage
First, bring the apply attribute macro into scope:
use macro_rules_attr::apply;Then, define your macro using macro_rules!:
/// Your macro that you want to use as an attribute.
macro_rules! the_macro {
// Your macro implementation here.
}Finally, annotate your item with the apply attribute macro:
#[apply(the_macro)]
struct One {}
// Expands to:
the_macro! { struct One {} }Additional tokens are appended after the annotated item:
#[apply(the_macro, "additional tokens", anything, (you - like))]
struct Another {}
// Expands to:
the_macro! { struct Another {}, "additional tokens", anything, (you - like) }§Example
use macro_rules_attr::apply;
/// Simple macro that generates a `hello` function for given struct, which returns `Hello, {name}!`. If given a second argument, it will replace `{name}`.
macro_rules! make_hello {
( // Matches a struct definition (some details omitted for brevity)
struct $StructName:ident {
// ...
}$(, $replacement:expr)?
) => {
// Repeat the struct definition
struct $StructName {
// ...
}
// Implement the `hello` function
impl $StructName {
fn hello() -> String {
let name = stringify!($StructName);
$(let name = $replacement;)? // Shadow `name` if a replacement was provided
format!("Hello, {name}!")
}
}
};
}
#[apply(make_hello)] // No additional tokens
struct WithoutReplacement {}
assert_eq!(WithoutReplacement::hello(), "Hello, WithoutReplacement!");
#[apply(make_hello, "World")] // Additional tokens
struct WithReplacement {}
assert_eq!(WithReplacement::hello(), "Hello, World!");§Cargo Features
log: Enable logging with thelogcrate. (Requireslogas a dependency)
§Comparison
This crate is heavily inspired by macro_rules_attribute, but differs in the following ways:
macro_rules_attris more lightweight and has no dependencies by default.- Less than 100 lines of code. (Excluding tests and documentation)
- You can enable logging with the
logfeature, which requireslogas a dependency. pasteis required as a dev-dependency for the tests.
macro_rules_attronly has one attribute:#[apply], whilemacro_rules_attributeprovides more.macro_rules_attrallows you to append any tokens after the annotated item, whilemacro_rules_attributedoes not.
Attribute Macros§
- apply
- Apply the given
macro_rulesto the annotated item, appending additional tokens if provided.