5 Functions are the primary tool that programmers can use to build abstractions.
6 Sometimes, however, programmers want to abstract over compile-time syntax
7 rather than run-time values.
8 Macros provide syntactic abstraction.
9 For an example of how this can be useful, consider the following two code fragments,
10 which both pattern-match on their input and both return early in one case,
11 doing nothing otherwise:
14 # enum T { SpecialA(u32), SpecialB(u32) }
16 # let input_1 = T::SpecialA(0);
17 # let input_2 = T::SpecialA(0);
19 T::SpecialA(x) => { return x; }
24 T::SpecialB(x) => { return x; }
31 This code could become tiresome if repeated many times.
32 However, no function can capture its functionality to make it possible
33 to abstract the repetition away.
34 Rust's macro system, however, can eliminate the repetition. Macros are
35 lightweight custom syntax extensions, themselves defined using the
36 `macro_rules!` syntax extension. The following `early_return` macro captures
37 the pattern in the above code:
40 # enum T { SpecialA(u32), SpecialB(u32) }
42 # let input_1 = T::SpecialA(0);
43 # let input_2 = T::SpecialA(0);
44 macro_rules! early_return {
45 ($inp:expr, $sp:path) => ( // invoke it like `(input_5, SpecialE)`
47 $sp(x) => { return x; }
53 early_return!(input_1, T::SpecialA);
55 early_return!(input_2, T::SpecialB);
61 Macros are defined in pattern-matching style: in the above example, the text
62 `($inp:expr, $sp:path)` that appears on the left-hand side of the `=>` is the
63 *macro invocation syntax*, a pattern denoting how to write a call to the
64 macro. The text on the right-hand side of the `=>`, beginning with `match
65 $inp`, is the *macro transcription syntax*: what the macro expands to.
69 The macro invocation syntax specifies the syntax for the arguments to the
70 macro. It appears on the left-hand side of the `=>` in a macro definition. It
71 conforms to the following rules:
73 1. It must be surrounded by parentheses.
74 2. `$` has special meaning (described below).
75 3. The `()`s, `[]`s, and `{}`s it contains must balance. For example, `([)` is
77 4. Some arguments can be followed only by a limited set of separators, to
78 avoid ambiguity (described below).
80 Otherwise, the invocation syntax is free-form.
82 To take a fragment of Rust code as an argument, write `$` followed by a name
83 (for use on the right-hand side), followed by a `:`, followed by a *fragment
84 specifier*. The fragment specifier denotes the sort of fragment to match. The
85 most common fragment specifiers are:
87 * `ident` (an identifier, referring to a variable or item. Examples: `f`, `x`,
89 * `expr` (an expression. Examples: `2 + 2`; `if true then { 1 } else { 2 }`;
91 * `ty` (a type. Examples: `i32`, `Vec<(char, String)>`, `&T`.)
92 * `path` (a path to struct or enum variant. Example: `T::SpecialA`)
93 * `pat` (a pattern, usually appearing in a `match` or on the left-hand side of
94 a declaration. Examples: `Some(t)`; `(17, 'a')`; `_`.)
95 * `block` (a sequence of actions. Example: `{ log(error, "hi"); return 12; }`)
97 The parser interprets any token that's not preceded by a `$` literally. Rust's usual
98 rules of tokenization apply,
100 So `($x:ident -> (($e:expr)))`, though excessively fancy, would designate a macro
101 that could be invoked like: `my_macro!(i->(( 2+2 )))`.
103 To avoid ambiguity, macro invocation syntax must conform to the following rules:
104 * `expr` must be followed by `=>`, `,` or `;`.
105 * `ty` and `path` must be followed by `=>`, `,`, `:`, `=`, `>` or `as`.
106 * `pat` must be followed by `=>`, `,` or `=`.
107 * `ident` and `block` can be followed by any token.
109 ## Invocation location
111 A macro invocation may take the place of (and therefore expand to) an
112 expression, item, statement, or pattern. The Rust parser will parse the macro
113 invocation as a "placeholder" for whichever syntactic form is appropriate for
116 At expansion time, the output of the macro will be parsed as whichever of the
117 three nonterminals it stands in for. This means that a single macro might,
118 for example, expand to an item or an expression, depending on its arguments
119 (and cause a syntax error if it is called with the wrong argument for its
120 location). Although this behavior sounds excessively dynamic, it is known to
121 be useful under some circumstances.
124 # Transcription syntax
126 The right-hand side of the `=>` follows the same rules as the left-hand side,
127 except that a `$` need only be followed by the name of the syntactic fragment
128 to transcribe into the macro expansion; its type need not be repeated.
130 The right-hand side must be enclosed by delimiters, which the transcriber ignores.
131 Therefore `() => ((1,2,3))` is a macro that expands to a tuple expression,
132 `() => (let $x=$val)` is a macro that expands to a statement,
133 and `() => (1,2,3)` is a macro that expands to a syntax error
134 (since the transcriber interprets the parentheses on the right-hand-size as delimiters,
135 and `1,2,3` is not a valid Rust expression on its own).
137 Except for permissibility of `$name` (and `$(...)*`, discussed below), the
138 right-hand side of a macro definition is ordinary Rust syntax. In particular,
139 macro invocations (including invocations of the macro currently being defined)
140 are permitted in expression, statement, and item locations. However, nothing
141 else about the code is examined or executed by the macro system; execution
142 still has to wait until run-time.
144 ## Interpolation location
146 The interpolation `$argument_name` may appear in any location consistent with
147 its fragment specifier (i.e., if it is specified as `ident`, it may be used
148 anywhere an identifier is permitted).
154 Going back to the motivating example, recall that `early_return` expanded into
155 a `match` that would `return` if the `match`'s scrutinee matched the
156 "special case" identifier provided as the second argument to `early_return`,
157 and do nothing otherwise. Now suppose that we wanted to write a
158 version of `early_return` that could handle a variable number of "special"
161 The syntax `$(...)*` on the left-hand side of the `=>` in a macro definition
162 accepts zero or more occurrences of its contents. It works much
163 like the `*` operator in regular expressions. It also supports a
164 separator token (a comma-separated list could be written `$(...),*`), and `+`
165 instead of `*` to mean "at least one".
168 # enum T { SpecialA(u32), SpecialB(u32), SpecialC(u32), SpecialD(u32) }
170 # let input_1 = T::SpecialA(0);
171 # let input_2 = T::SpecialA(0);
172 macro_rules! early_return {
173 ($inp:expr, [ $($sp:path),+ ]) => (
176 $sp(x) => { return x; }
183 early_return!(input_1, [T::SpecialA,T::SpecialC,T::SpecialD]);
185 early_return!(input_2, [T::SpecialB]);
193 As the above example demonstrates, `$(...)*` is also valid on the right-hand
194 side of a macro definition. The behavior of `*` in transcription,
195 especially in cases where multiple `*`s are nested, and multiple different
196 names are involved, can seem somewhat magical and unintuitive at first. The
197 system that interprets them is called "Macro By Example". The two rules to
198 keep in mind are (1) the behavior of `$(...)*` is to walk through one "layer"
199 of repetitions for all of the `$name`s it contains in lockstep, and (2) each
200 `$name` must be under at least as many `$(...)*`s as it was matched against.
201 If it is under more, it'll be repeated, as appropriate.
203 ## Parsing limitations
206 For technical reasons, there are two limitations to the treatment of syntax
207 fragments by the macro parser:
209 1. The parser will always parse as much as possible of a Rust syntactic
210 fragment. For example, if the comma were omitted from the syntax of
211 `early_return!` above, `input_1 [` would've been interpreted as the beginning
212 of an array index. In fact, invoking the macro would have been impossible.
213 2. The parser must have eliminated all ambiguity by the time it reaches a
214 `$name:fragment_specifier` declaration. This limitation can result in parse
215 errors when declarations occur at the beginning of, or immediately after,
216 a `$(...)*`. For example, the grammar `$($t:ty)* $e:expr` will always fail to
217 parse because the parser would be forced to choose between parsing `t` and
218 parsing `e`. Changing the invocation syntax to require a distinctive token in
219 front can solve the problem. In the above example, `$(T $t:ty)* E $e:exp`
222 # Macro argument pattern matching
226 Now consider code like the following:
229 # enum T1 { Good1(T2, u32), Bad1}
230 # struct T2 { body: T3 }
231 # enum T3 { Good2(u32), Bad2}
232 # fn f(x: T1) -> u32 {
234 T1::Good1(g1, val) => {
236 T3::Good2(result) => {
237 // complicated stuff goes here
240 _ => panic!("Didn't get good_2")
243 _ => return 0 // default value
249 All the complicated stuff is deeply indented, and the error-handling code is
250 separated from matches that fail. We'd like to write a macro that performs
251 a match, but with a syntax that suits the problem better. The following macro
252 can solve the problem:
255 macro_rules! biased_match {
256 // special case: `let (x) = ...` is illegal, so use `let x = ...` instead
257 ( ($e:expr) -> ($p:pat) else $err:stmt ;
258 binds $bind_res:ident
260 let $bind_res = match $e {
265 // more than one name; use a tuple
266 ( ($e:expr) -> ($p:pat) else $err:stmt ;
267 binds $( $bind_res:ident ),*
269 let ( $( $bind_res ),* ) = match $e {
270 $p => ( $( $bind_res ),* ),
276 # enum T1 { Good1(T2, u32), Bad1}
277 # struct T2 { body: T3 }
278 # enum T3 { Good2(u32), Bad2}
279 # fn f(x: T1) -> u32 {
280 biased_match!((x) -> (T1::Good1(g1, val)) else { return 0 };
282 biased_match!((g1.body) -> (T3::Good2(result) )
283 else { panic!("Didn't get good_2") };
285 // complicated stuff goes here
291 This solves the indentation problem. But if we have a lot of chained matches
292 like this, we might prefer to write a single macro invocation. The input
293 pattern we want is clear:
298 ( $( ($e:expr) -> ($p:pat) else $err:stmt ; )*
299 binds $( $bind_res:ident ),*
304 However, it's not possible to directly expand to nested match statements. But
307 ## The recursive approach to macro writing
309 A macro may accept multiple different input grammars. The first one to
310 successfully match the actual argument to a macro invocation is the one that
313 In the case of the example above, we want to write a recursive macro to
314 process the semicolon-terminated lines, one-by-one. So, we want the following
319 ( binds $( $bind_res:ident ),* )
329 ( ($e :expr) -> ($p :pat) else $err :stmt ;
330 $( ($e_rest:expr) -> ($p_rest:pat) else $err_rest:stmt ; )*
331 binds $( $bind_res:ident ),*
336 The resulting macro looks like this. Note that the separation into
337 `biased_match!` and `biased_match_rec!` occurs only because we have an outer
338 piece of syntax (the `let`) which we only want to transcribe once.
343 macro_rules! biased_match_rec {
344 // Handle the first layer
345 ( ($e :expr) -> ($p :pat) else $err :stmt ;
346 $( ($e_rest:expr) -> ($p_rest:pat) else $err_rest:stmt ; )*
347 binds $( $bind_res:ident ),*
351 // Recursively handle the next layer
352 biased_match_rec!($( ($e_rest) -> ($p_rest) else $err_rest ; )*
353 binds $( $bind_res ),*
359 // Produce the requested values
360 ( binds $( $bind_res:ident ),* ) => ( ($( $bind_res ),*) )
363 // Wrap the whole thing in a `let`.
364 macro_rules! biased_match {
365 // special case: `let (x) = ...` is illegal, so use `let x = ...` instead
366 ( $( ($e:expr) -> ($p:pat) else $err:stmt ; )*
367 binds $bind_res:ident
369 let $bind_res = biased_match_rec!(
370 $( ($e) -> ($p) else $err ; )*
374 // more than one name: use a tuple
375 ( $( ($e:expr) -> ($p:pat) else $err:stmt ; )*
376 binds $( $bind_res:ident ),*
378 let ( $( $bind_res ),* ) = biased_match_rec!(
379 $( ($e) -> ($p) else $err ; )*
380 binds $( $bind_res ),*
386 # enum T1 { Good1(T2, u32), Bad1}
387 # struct T2 { body: T3 }
388 # enum T3 { Good2(u32), Bad2}
389 # fn f(x: T1) -> u32 {
391 (x) -> (T1::Good1(g1, val)) else { return 0 };
392 (g1.body) -> (T3::Good2(result) ) else { panic!("Didn't get Good2") };
394 // complicated stuff goes here
400 This technique applies to many cases where transcribing a result all at once is not possible.
401 The resulting code resembles ordinary functional programming in some respects,
402 but has some important differences from functional programming.
404 The first difference is important, but also easy to forget: the transcription
405 (right-hand) side of a `macro_rules!` rule is literal syntax, which can only
406 be executed at run-time. If a piece of transcription syntax does not itself
407 appear inside another macro invocation, it will become part of the final
408 program. If it is inside a macro invocation (for example, the recursive
409 invocation of `biased_match_rec!`), it does have the opportunity to affect
410 transcription, but only through the process of attempted pattern matching.
412 The second, related, difference is that the evaluation order of macros feels
413 "backwards" compared to ordinary programming. Given an invocation
414 `m1!(m2!())`, the expander first expands `m1!`, giving it as input the literal
415 syntax `m2!()`. If it transcribes its argument unchanged into an appropriate
416 position (in particular, not as an argument to yet another macro invocation),
417 the expander will then proceed to evaluate `m2!()` (along with any other macro
418 invocations `m1!(m2!())` produced).
422 To prevent clashes, rust implements
423 [hygienic macros](http://en.wikipedia.org/wiki/Hygienic_macro).
425 As an example, `loop` and `for-loop` labels (discussed in the lifetimes guide)
426 will not clash. The following code will print "Hello!" only once:
429 macro_rules! loop_x {
431 // $e will not interact with this 'x
442 println!("I am never printed.");
447 The two `'x` names did not clash, which would have caused the loop
448 to print "I am never printed" and to run forever.
450 # Scoping and macro import/export
452 Macros are expanded at an early stage in compilation, before name resolution.
453 One downside is that scoping works differently for macros, compared to other
454 constructs in the language.
456 Definition and expansion of macros both happen in a single depth-first,
457 lexical-order traversal of a crate's source. So a macro defined at module scope
458 is visible to any subsequent code in the same module, which includes the body
459 of any subsequent child `mod` items.
461 A macro defined within the body of a single `fn`, or anywhere else not at
462 module scope, is visible only within that item.
464 If a module has the `macro_use` attribute, its macros are also visible in its
465 parent module after the child's `mod` item. If the parent also has `macro_use`
466 then the macros will be visible in the grandparent after the parent's `mod`
469 The `macro_use` attribute can also appear on `extern crate`. In this context
470 it controls which macros are loaded from the external crate, e.g.
473 #[macro_use(foo, bar)]
477 If the attribute is given simply as `#[macro_use]`, all macros are loaded. If
478 there is no `#[macro_use]` attribute then no macros are loaded. Only macros
479 defined with the `#[macro_export]` attribute may be loaded.
481 To load a crate's macros *without* linking it into the output, use `#[no_link]`
487 macro_rules! m1 { () => (()) }
495 macro_rules! m2 { () => (()) }
497 // visible here: m1, m2
502 macro_rules! m3 { () => (()) }
504 // visible here: m1, m3
508 // visible here: m1, m3
510 macro_rules! m4 { () => (()) }
512 // visible here: m1, m3, m4
515 // visible here: m1, m3, m4
519 When this library is loaded with `#[use_macros] extern crate`, only `m2` will
522 The Rust Reference has a [listing of macro-related
523 attributes](../reference.html#macro--and-plugin-related-attributes).
525 # The variable `$crate`
527 A further difficulty occurs when a macro is used in multiple crates. Say that
531 pub fn increment(x: u32) -> u32 {
537 ($x:expr) => ( ::increment($x) )
542 ($x:expr) => ( ::mylib::increment($x) )
547 `inc_a` only works within `mylib`, while `inc_b` only works outside the
548 library. Furthermore, `inc_b` will break if the user imports `mylib` under
551 Rust does not (yet) have a hygiene system for crate references, but it does
552 provide a simple workaround for this problem. Within a macro imported from a
553 crate named `foo`, the special macro variable `$crate` will expand to `::foo`.
554 By contrast, when a macro is defined and then used in the same crate, `$crate`
555 will expand to nothing. This means we can write
560 ($x:expr) => ( $crate::increment($x) )
565 to define a single macro that works both inside and outside our library. The
566 function name will expand to either `::increment` or `::mylib::increment`.
568 To keep this system simple and correct, `#[macro_use] extern crate ...` may
569 only appear at the root of your crate, not inside `mod`. This ensures that
570 `$crate` is a single identifier.
574 Macros, as currently implemented, are not for the faint of heart. Even
575 ordinary syntax errors can be more difficult to debug when they occur inside a
576 macro, and errors caused by parse problems in generated code can be very
577 tricky. Invoking the `log_syntax!` macro can help elucidate intermediate
578 states, invoking `trace_macros!(true)` will automatically print those
579 intermediate states out, and passing the flag `--pretty expanded` as a
580 command-line argument to the compiler will show the result of expansion.
582 If Rust's macro system can't do what you need, you may want to write a
583 [compiler plugin](plugins.html) instead. Compared to `macro_rules!`
584 macros, this is significantly more work, the interfaces are much less stable,
585 and the warnings about debugging apply ten-fold. In exchange you get the
586 flexibility of running arbitrary Rust code within the compiler. Syntax
587 extension plugins are sometimes called *procedural macros* for this reason.