Skip to content

Commit 6d8c00b

Browse files
author
Keegan McAllister
committed
RFC: pattern expansion in macros
1 parent 0fc8bc0 commit 6d8c00b

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

active/0000-pattern-macros.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
- Start Date: 2014-05-21
2+
- RFC PR #:
3+
- Rust Issue #:
4+
5+
# Summary
6+
7+
Allow macro expansion in patterns, i.e.
8+
9+
~~~ .rs
10+
match x {
11+
my_macro!() => 1,
12+
_ => 2,
13+
}
14+
~~~
15+
16+
# Motivation
17+
18+
This is consistent with allowing macros in expressions etc. It's also a year-old [open issue](https://github.com/mozilla/rust/issues/6830).
19+
20+
I have [implemented](https://github.com/mozilla/rust/pull/14298) this feature already (with some bugs) and I'm [using it](https://github.com/kmcallister/html5/blob/937684f107090741c8e87135efc6e5476489857b/src/tree_builder/mod.rs#L111-L117) to [condense](https://github.com/kmcallister/html5/blob/937684f107090741c8e87135efc6e5476489857b/src/tree_builder/mod.rs#L261-L269) some ubiquitous patterns in the [HTML parser](https://github.com/kmcallister/html5) I'm writing. This makes the code more concise and easier to cross-reference with the spec.
21+
22+
# Drawbacks / alternatives
23+
24+
A macro invocation in this position:
25+
26+
~~~ .rs
27+
match x {
28+
my_macro!()
29+
~~~
30+
31+
could potentially expand to any of three different syntactic elements:
32+
33+
* A pattern, i.e. `Foo(x)`
34+
* The left side of a `match` arm, i.e. `Foo(x) | Bar(x) if x > 5`
35+
* An entire `match` arm, i.e. `Foo(x) | Bar(x) if x > 5 => 1`
36+
37+
This RFC proposes only the first of these, but the others would be more useful in some cases. Supporting multiple of the above would be significantly more complex.
38+
39+
Another alternative is to use a macro for the entire `match` expression, e.g.
40+
41+
~~~ .rs
42+
my_match!(x {
43+
my_new_syntax => 1,
44+
_ => 2,
45+
})
46+
~~~
47+
48+
This doesn't involve any language changes, but requires writing a complicated procedural macro. (My sustained attempts to do things like this with MBE macros have all failed.) Perhaps I could alleviate some of the pain with a library for writing `match`-like macros, or better use of the existing parser in `libsyntax`.
49+
50+
The `my_match!` approach is also not very composable.
51+
52+
# Unresolved questions
53+
54+
I need to fix the ICE described in [the pull request](https://github.com/mozilla/rust/pull/14298). I don't expect this to have any design impact, but I can't be sure.

0 commit comments

Comments
 (0)