Rust: Macros can't expand to 'match' alternatives

Created on 12 Mar 2014  路  10Comments  路  Source: rust-lang/rust

``` .rs
macro_rules! foo (() => (
2 => "two"
))

fn main() {
match 2 {
foo!(),
_ => "not two",
}
}


$ rustc -v
rustc 0.10-pre (6ae5de0 2014-02-19 12:51:48 -0800)
host: x86_64-unknown-linux-gnu
$ rustc foo.rs
foo.rs:7:12: 7:13 error: expected => but found !
foo.rs:7 foo!(),
^
```

A-macros C-enhancement

Most helpful comment

I don't think there is any RFC that defines an AST node; the fact that match alternatives aren't AST nodes seems like essentially an implementation detail.

If there are any ambiguities in the desired semantics, that may require an RFC to make a choice, but I can't think of any.

Nor can I think of any downside to allowing this, other than making the compiler marginally more complex.

All 10 comments

Not quite a dupe, because 2 => "two" isn't a pattern. I'd like to be able to expand to patterns, or |s of patterns with a guard, or entire match arms. But I think that would be pretty messy to parse.

Oh, whoops.

Traige: updated code sample:

macro_rules! foo (() => (
    2 => "two"
));

fn main() {
    match 2 {
        foo!(),
        _ => "not two",
    }
}

updated error:

hello.rs:7:15: 7:16 error: expected one of `=>`, `if`, or `|`, found `,`
hello.rs:7         foo!(),
                         ^

Seems related to #26330

I'm not sure if this is the same thing (but I assume it is since it would be inserting a partial AST node, if I understand what is happening correctly), but this also doesn't work and, should also be fixed as part of this issue (I think):

// Table tests for a function called "baz" on a result type that is being checked
// with a match
macro_rules! test_invalid_baz {
    ( $( $num:ident: [$arg:expr, $err:expr] ),+ ) => {
        $(
            #[test]
            fn $num() {
                //  with $arg as the input, expect Err($err) as the output
                match baz($arg) {
                    Err($err) => {},
                    _ => panic!("Errors did not match"),
                }
            }
        )*
    };
}

test_invalid_split!([test0, "foo", Error::Bar])

Macros cannot expand to incomplete AST nodes; this is not something that we can readily change/implement I think without an RFC. As such, I'm going to close.

I don't think there is any RFC that defines an AST node; the fact that match alternatives aren't AST nodes seems like essentially an implementation detail.

If there are any ambiguities in the desired semantics, that may require an RFC to make a choice, but I can't think of any.

Nor can I think of any downside to allowing this, other than making the compiler marginally more complex.

Could this issue be re-opened? I think this would be a very useful feature.

At the very least, I think this warrants further discussion.

That discussion should take place in an RFC, not here.

Was this page helpful?
0 / 5 - 0 ratings