I'm new to Rust and even more to the macro engine, I'm trying to come up with a way of creating a DSL that I'll use for HTML templating that looks like the following,
h! {
foo(
"bar",
tag_with_parens(),
tag_without_parens,
"some other expression",
element(child),
),
"tags and strings can be siblings",
}
I've toyed around a bit but I'm not sure if it's even possible
macro_rules! h {
// single idents and strings are matched here
($t:tt) => { h!($t(),) };
($t:tt( $($inner:tt),* )) => {h!($t($($inner),*),)};
($t:tt( $($inner:tt),* ), $($rest:tt),*) => {{
// recursion with the contents of the tag
h!($($inner),*);
// do something with the rest of the parameters
h!($($rest),*);
}};
}
In this simple example, I'm using tt
since it matches both identifiers and the string literals but it breaks when the token is followed by the parenthesis because I imagine it considers it a separate token. I get error: no rules expected the token (
. Also if I want to support not only passing a string but any expression it would have to be different
An extra credit assignment that would be my next step if I get the previous thing to work would be optional attributes as first argument. :)
h!(foo({ident="expr", bar}, "content"))