π Eval Macro
Eval Macro introduces a new macro type for Rust, blending power and ease of use. Hereβs how
it compares to macro_rules!
and procedural macros:
Proc Macro | Eval Macro | Macro Rules | |
---|---|---|---|
Input | Token Stream | Rust Code | Macro Fragments |
Output | Token Stream | Rust Code | Macro Fragments |
Hygienic | β | β | β |
Advanced transformations | β | β | β |
Easy to define | β | β | β |
Easy to read | β | β | β |
Reusable | β | β | β |
In short, Eval Macros offer procedural macro power with macro_rules!
simplicity. However,
they are not reusable β you cannot export an Eval Macro for use in other crates.
π€© Syntax
Use the eval!
macro to create and run an Eval Macro inline. The content of the macro is
regular Rust code, which will be compiled and executed at build time.
Inside the eval!
block, you can use the output!
macro to emit Rust code. output!
supports
double-brace interpolation, allowing you to embed variables directly into the generated
code.
Example:
use eval;
eval!
#
This will generate:
#
Doing this with macro_rules!
or procedural macros would be far more complex!
π How It Works
The content inside eval!
is pasted into the main
function of a temporary Rust project.
This project is compiled and executed at build time, and its stdout
becomes the generated
Rust code. The generated main
function looks something like this:
fn main() {
let mut output_buffer = String::new();
{your_code}
println!("{{output_buffer}}");
}
The output!
macro is essentially a shortcut for writing to output_buffer
using format!
,
so this:
use eval;
eval!
#
Is equivalent to:
use eval;
eval!
#
And that, in turn, is just shorthand for:
use eval;
eval!
#
β οΈ Troubleshooting
β οΈ Note: Rust IDEs differ in how they handle macro expansion. This macro is tuned for
RustRoverβs
expansion engine.
If your IDE struggles to correctly expand eval!
, you can manually switch to the write_ln!
syntax described above. If you encounter issues, please
open an issue to let us know!