Is it possible in rust to write a macro that creates other macros. For example, suppose I define the following two macros:
macro_rules! myprint(
($a:expr) => (print!("{}", $a))
)
macro_rules! myprintln(
($a:expr) => (println!("{}", $a))
)
Since the two macros repeat a lot of code, I may want to write a macro to generate the macros.
I've tried to generate such a meta macro.
#![feature(macro_rules)]
macro_rules! metamacro(
($i:ident) => (
macro_rules! $i (
($a:expr) => ({println!("hello {}", $a)})
)
);
)
metamacro!(foo)
fn main() {
foo!(1i);
}
but get the following errors:
<anon>:6:13: 6:14 error: unknown macro variable `a`
<anon>:6 ($a:expr) => ({println!("hello {}", $a)})
^
playpen: application terminated with error code 101
Program ended.
Edit: After playing around with the macros some more, I discovered that a higher order macro works as expected if the returned macro doesn't receive any arguments. For example, the following code
#![feature(macro_rules)]
macro_rules! metamacro(
($i:ident) => (
macro_rules! $i (
() => ({println!("hello")})
)
);
)
metamacro!(foo)
fn main() {
foo!();
}
prints hello