I would like to use macros to generate the body of a function, but to do so they need to access variables in the local scope:
macro_rules! generate_func {
($name:ident) => {
fn $name(param: i32) {
generate_body!()
}
};
}
macro_rules! generate_body {
() => {
println!("{}", ¶m);
}
}
generate_func!(foo);
error[E0425]: cannot find value `param` in this scope
--> src/lib.rs:11:25
|
11 | println!("{}", ¶m);
| ^^^^^ not found in this scope
...
15 | generate_func!(foo);
| -------------------- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
It's very frustrating that this doesn't work, because I can run cargo-expand
and see that the resulting code is valid:
fn foo(param: i32) {
{
::std::io::_print(::core::fmt::Arguments::new_v1(&["", "\n"],
&match (&¶m,) {
(arg0,) =>
[::core::fmt::ArgumentV1::new(arg0,
::core::fmt::Display::fmt)],
}));
}
}
(this is a bit messy because of the println!
, but you can see the valid reference there)
I can even copy and paste the expansion into my source and the compiler accepts it. Surely there is some way to accomplish the desired outcome?
It seems roughly related to:
- "cannot find value `a` in this scope" in Rust macro
- https://github.com/dtolnay/proc-macro-hack/issues/15
But I couldn't be sure that I had the exact same issue; my case seems more basic.