4 releases
new 0.1.2 | Jan 15, 2025 |
---|---|
0.1.1 | Jan 12, 2025 |
0.1.0 | Dec 31, 2024 |
0.0.0 | Feb 26, 2024 |
#318 in Procedural macros
350 downloads per month
56KB
681 lines
XMacro
A powerful macro system for generating repetitive code using a simple and expressive syntax.
This crate provides two main components:
- A procedural macro library that enables code generation through template expansion
- Two public macros:
xmacro!
andxmacro_items!
for direct use in your code
This crate supersedes the code_product
crate.
Key Features
- Define reusable code templates with substitution points
- Generate multiple variations of code using sets of values
- Support for nested scopes and named definitions
- Table-based code generation for row-wise expansion
- Clear and maintainable syntax for complex code generation
Usage
For example given are the two sets of defintions 'Foo and Bar' and 'This and That', showing different syntactic variants:
Normal definitions expans each-by-each:
# use xmacro::xmacro;
trait Trait<T>{}
struct This; struct That;
struct Foo<T>(T); struct Bar<T>(T);
xmacro!{
// Rather elaborate form with named definitions:
$(T: (This) (That))
$(Type: (Foo) (Bar))
// and inline define `T` to expand to `Foo` and `Bar`
impl Trait<$T> for $Type<$T> {}
}
or
# use xmacro::xmacro;
# trait Trait<T>{}
# struct This; struct That;
# struct Foo<T>(T); struct Bar<T>(T);
xmacro!{
// Alternative form inlining/short definition and reference by index:
impl Trait<$(This That)> for $(Foo Bar)<$0> {}
}
or use the table syntax expands per table row and gives more control what gets expansed:
# use xmacro::xmacro;
# trait Trait<T>{}
# struct This; struct That;
# struct Foo<T>(T); struct Bar<T>(T);
xmacro!{
// Tables have a header line followed by a vertical list of expansions
// they would be more interesting when defining more than one thing in the header
$[
T: Type:
(This) (Foo)
(That) (Foo)
(This) (Bar)
(That) (Bar)
]
// and inline define `T` to expand to `Foo` and `Bar`
impl Trait<$T> for $Type<$T> {}
}
either of the above will expand four times to:
# trait Trait<T>{}
# struct This; struct That;
# struct Foo<T>(T); struct Bar<T>(T);
impl Trait<This> for Foo<This> {}
impl Trait<That> for Foo<That> {}
impl Trait<This> for Bar<This> {}
impl Trait<That> for Bar<That> {}
Please refer to the xmacro_lib crate for a elaborate description of the macro syntax and semantic.
Dependencies
~200KB