Can macros expand array/vector into multiple indexed arguments? - macros

Is it possible to write a macro that expands an expression into multiple indexed arguments, which can be passed to a function or another macro?
See this simple self contained example.The aim is to have unpack3 expand v into v[0], v[1], v[2].
macro_rules! elem {
($val:expr, $($var:expr), *) => {
$($val == $var) || *
}
}
// attempt to expand an array.
macro_rules! unpack3 {
($v:expr) => {
$v[0], $v[1], $v[2]
}
}
fn main() {
let a = 2;
let vars = [0, 1, 3];
// works!
if elem!(a, vars[0], vars[1], vars[2]) {
println!("Found!");
}
// fails!
if elem!(a, unpack3!(vars)) {
println!("Found!");
}
}
The second example fails, is it possible to make this work?
Possible solutions could include:
Changing use of macro grammar.
Using tuples, then expanding into arguments after.
Re-arranging the expressions to workaround macro constraints.
Note, this may be related to Escaping commas in macro output but don't think its a duplicate.

This is impossible in two different ways.
First, to quote the answer to the question you yourself linked: "No; the result of a macro must be a complete grammar construct like an expression or an item. You absolutely cannot have random bits of syntax like a comma or a closing brace." Just because it isn't exactly a comma doesn't change matters: a collection of function arguments are not a complete grammar construct.
Secondly, macros cannot parse the output of other macros. This requires eager expansion, which Rust doesn't have. You can only do this using recursion.

Related

How to match "mut" in a Rust macro?

I would like to pass mutability to a macro so that I can do
mymacro![mut foo];
mymacro![bar];
and the macro will see them as different matches. which specifier to use?
There isn't one. You'll need two rules: one which matches a literal mut, and one that doesn't.
macro_rules! do_something {
(mut $name:ident) => { ... };
($name:ident) => { ... };
}
And yes, they do have to be in that order, because macro arms are matched top-to-bottom.

How to pass named loop labels to a macro in Rust?

Using a macro that breaks out of a loop works, but I want to pass in a label to be able to define which outer loop to break out of.
Passing the argument in as an expression gave a syntax error, the only way I managed to get this to work was to pass in a block however this isn't very elegant, e.g.:
my_macro({ break 'outer; });
Is there a way to pass:
my_macro('outer);
... that can be written in the macro as break $my_label; that expands into break 'outer; ?
Passing it as the versatile tt (token tree) works:
macro_rules! my_break {
($label:tt) => { break $label; }
}
fn main() {
'outer: loop {
println!("Start of outer");
loop {
println!("Start of inner");
my_break!('outer);
println!("Not reachable");
}
println!("End of outer");
}
println!("End of main");
}
Playground
To future readers, there's an accepted RFC adding a lifetime specifier for macro parameters.

How to process expanded macros from within procedural macros?

For overflower, I'm trying to replace all arithmetic operations (binary +, -, *, /, %, <<, >> and unary -) with corresponding trait method calls. However, I'm hitting a wall with macros. Ideally, I'd work on the already expanded macro, but this does not appear to work.
I've followed the suggestion in syntax::fold::Folder::fold_mac(..) and called noop_fold_mac(mac, self), but that does not appear to do anything to stuff inside a macro, like assert_eq!(2, 1 + 1). I don't care about the code pre-expansion, so how do I have my macro work on the expanded code?
I could probably work on the TokenTrees directly, but that's cumbersome.
I'm using rustc 1.11.0-nightly (915b003e3 2016-06-02)
You can use the expand_expr function to do a full expansion (if let, macros, etc...). You need a MacroExpander, which you can get by passing a mutable reference to the ExtCtxt to the MacroExpander::new method or call the ExtCtxt's expander() method.
The actual code is:
fn fold_expr(&mut self, expr: P<Expr>) -> P<Expr> {
..
if let ExprKind::Mac(_) = expr.node {
let expanded = expand_expr(expr.unwrap(), &mut self.cx.expander());
return self.fold_expr(expanded);
}
..
}
Edit: For completeness, one should also expand Items with ItemKind::Mac; there's an syntax::ext::expand::expand_item(..) method working similarly to expand_expr(..).

How do I write a wrapper for a macro without repeating the rules?

I am trying to make a wrapper for a macro. The trouble is that I don't want to repeat the same rules in both macro. Is there a way to do that?
Here is what I tried:
macro_rules! inner {
($test:ident) => { stringify!($test) };
($test:ident.run()) => { format!("{}.run()", stringify!($test)) };
}
macro_rules! outer {
($expression:expr) => {
println!("{}", inner!($expression));
}
}
fn main() {
println!("{}", inner!(test));
println!("{}", inner!(test.run()));
outer!(test);
outer!(test.run());
}
but I get the following error:
src/main.rs:8:31: 8:42 error: expected ident, found test
src/main.rs:8 println!("{}", inner!($expression));
^~~~~~~~~~~
If I change the outer macro for this, the code compile:
macro_rules! outer {
($expression:expr) => {
println!("{}", stringify!($expression));
}
}
What am I doing wrong?
macro_rules! is both cleverer and dumber than you might realise.
Initially, all input to a macro begins life as undifferentiated token soup. An Ident here, StrLit there, etc. However, when you match and capture a bit of the input, generally the input will be parsed in an Abstract Syntax Tree node; this is the case with expr.
The "clever" bit is that when you substitute this capture (for example, $expression), you don't just substitute the tokens that were originally matched: you substitute the entire AST node as a single token. So there's now this weird not-really-a-token in the output that's an entire syntax element.
The "dumb" bit is that this process is basically irreversible and mostly totally invisible. So let's take your example:
outer!(test);
We run this through one level of expansion, and it becomes this:
println!("{}", inner!(test));
Except, that's not what it looks like. To make things clearer, I'm going to invent some non-standard syntax:
println!("{}", inner!( $(test):expr ));
Pretend that $(test):expr is a single token: it's an expression which can be represented by the token sequence test. It is not simply the token sequence test. This is important, because when the macro interpreter goes to expand that inner! macro, it checks the first rule:
($test:ident) => { stringify!($test) };
The problem is that $(test):expr is an expression, not an identifier. Yes, it contains an identifier, but the macro interpreter doesn't look that deep. It sees an expression and just gives up.
It fails to match the second rule for the same reason.
So what do you do? ... Well, that depends. If outer! doesn't do any sort of processing on its input, you can use a tt matcher instead:
macro_rules! outer {
($($tts:tt)*) => {
println!("{}", inner!($($tts)*));
}
}
tt will match any token tree (see the Macros chapter of the Rust Book). $($tts:tt)* will match any sequence of tokens, without changing them. This of this as a way to safely forward a bunch of tokens to another macro.
If you need to do processing on the input and forward it on to the inner! macro... you're probably going to have to repeat the rules.
I had some success with the $($stuff: expr),+ syntax.
macro_rules! println {
( $($stuff: expr),+) => {
avr_device::interrupt::free(|cs| {
uwriteln!(unsafe { &SERIAL_STATIC}.borrow(cs).borrow_mut().as_mut().unwrap(),
$($stuff),+)
})
}
}

; expected but <place your favourite keyword here> found

I'm trying to write a class for a scala project and I get this error in multiple places with keywords such as class, def, while.
It happens in places like this:
var continue = true
while (continue) {
[..]
}
And I'm sure the error is not there since when I isolate that code in another class it doesn't give me any error.
Could you please give me a rule of thumb for such errors? Where should I find them? are there some common syntactic errors elsewhere when this happens?
It sounds like you're using reserved keywords as variable names. "Continue", for instance, is a Java keyword.
You probably don't have parentheses or braces matched somewhere, and the compiler can't tell until it hits a structure that looks like the one you showed.
The other possibility is that Scala sometimes has trouble distinguishing between the end of a statement with a new one on the next line, and a multi-line statement. In that case, just drop the ; at the end of the first line and see if the compiler's happy. (This doesn't seem like it fits your case, as Scala should be able to tell that nothing should come after true, and that you're done assigning a variable.)
Can you let us know what this code is inside? Scala expects "expressions" i.e. things that resolve to a particular value/type. In the case of "var continue = true", this does not evaluate to a value, so it cannot be at the end of an expression (i.e. inside an if-expression or match-expression or function block).
i.e.
def foo() = {
var continue = true
while (continue) {
[..]
}
}
This is a problem, as the function block is an expression and needs to have an (ignored?) return value, i.e.
def foo() = {
var continue = true
while (continue) {
[..]
}
()
}
() => a value representing the "Unit" type.
I get this error when I forget to put an = sign after a function definition:
def function(val: String):Boolean {
// Some stuff
}