]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/macros.md
Rollup merge of #21357 - kimroen:patch-1, r=sanxiyn
[rust.git] / src / doc / trpl / macros.md
1 % Macros
2
3 # Introduction
4
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:
12
13 ~~~~
14 # enum T { SpecialA(u32), SpecialB(u32) }
15 # fn f() -> u32 {
16 # let input_1 = T::SpecialA(0);
17 # let input_2 = T::SpecialA(0);
18 match input_1 {
19     T::SpecialA(x) => { return x; }
20     _ => {}
21 }
22 // ...
23 match input_2 {
24     T::SpecialB(x) => { return x; }
25     _ => {}
26 }
27 # return 0;
28 # }
29 ~~~~
30
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:
38
39 ~~~~
40 # enum T { SpecialA(u32), SpecialB(u32) }
41 # fn f() -> 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)`
46         match $inp {
47             $sp(x) => { return x; }
48             _ => {}
49         }
50     );
51 }
52 // ...
53 early_return!(input_1, T::SpecialA);
54 // ...
55 early_return!(input_2, T::SpecialB);
56 # return 0;
57 # }
58 # fn main() {}
59 ~~~~
60
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.
66
67 # Invocation syntax
68
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:
72
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
76 forbidden.
77 4. Some arguments can be followed only by a limited set of separators, to
78 avoid ambiguity (described below).
79
80 Otherwise, the invocation syntax is free-form.
81
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:
86
87 * `ident` (an identifier, referring to a variable or item. Examples: `f`, `x`,
88   `foo`.)
89 * `expr` (an expression. Examples: `2 + 2`; `if true then { 1 } else { 2 }`;
90   `f(42)`.)
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; }`)
96
97 The parser interprets any token that's not preceded by a `$` literally. Rust's usual
98 rules of tokenization apply,
99
100 So `($x:ident -> (($e:expr)))`, though excessively fancy, would designate a macro
101 that could be invoked like: `my_macro!(i->(( 2+2 )))`.
102
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.
108
109 ## Invocation location
110
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
114 the location.
115
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.
122
123
124 # Transcription syntax
125
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.
129
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).
136
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.
143
144 ## Interpolation location
145
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).
149
150 # Multiplicity
151
152 ## Invocation
153
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"
159 cases.
160
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".
166
167 ~~~~
168 # enum T { SpecialA(u32), SpecialB(u32), SpecialC(u32), SpecialD(u32) }
169 # fn f() -> 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),+ ]) => (
174         match $inp {
175             $(
176                 $sp(x) => { return x; }
177             )+
178             _ => {}
179         }
180     )
181 }
182 // ...
183 early_return!(input_1, [T::SpecialA,T::SpecialC,T::SpecialD]);
184 // ...
185 early_return!(input_2, [T::SpecialB]);
186 # return 0;
187 # }
188 # fn main() {}
189 ~~~~
190
191 ### Transcription
192
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.
202
203 ## Parsing limitations
204
205
206 For technical reasons, there are two limitations to the treatment of syntax
207 fragments by the macro parser:
208
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`
220 solves the problem.
221
222 # Macro argument pattern matching
223
224 ## Motivation
225
226 Now consider code like the following:
227
228 ~~~~
229 # enum T1 { Good1(T2, u32), Bad1}
230 # struct T2 { body: T3 }
231 # enum T3 { Good2(u32), Bad2}
232 # fn f(x: T1) -> u32 {
233 match x {
234     T1::Good1(g1, val) => {
235         match g1.body {
236             T3::Good2(result) => {
237                 // complicated stuff goes here
238                 return result + val;
239             },
240             _ => panic!("Didn't get good_2")
241         }
242     }
243     _ => return 0 // default value
244 }
245 # }
246 # fn main() {}
247 ~~~~
248
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:
253
254 ~~~~
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
259     ) => (
260         let $bind_res = match $e {
261             $p => ( $bind_res ),
262             _ => { $err }
263         };
264     );
265     // more than one name; use a tuple
266     ( ($e:expr) -> ($p:pat) else $err:stmt ;
267       binds $( $bind_res:ident ),*
268     ) => (
269         let ( $( $bind_res ),* ) = match $e {
270             $p => ( $( $bind_res ),* ),
271             _ => { $err }
272         };
273     )
274 }
275
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 };
281               binds g1, val );
282 biased_match!((g1.body) -> (T3::Good2(result) )
283                   else { panic!("Didn't get good_2") };
284               binds result );
285 // complicated stuff goes here
286 return result + val;
287 # }
288 # fn main() {}
289 ~~~~
290
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:
294
295 ~~~~
296 # fn main() {}
297 # macro_rules! b {
298     ( $( ($e:expr) -> ($p:pat) else $err:stmt ; )*
299       binds $( $bind_res:ident ),*
300     )
301 # => (0) }
302 ~~~~
303
304 However, it's not possible to directly expand to nested match statements. But
305 there is a solution.
306
307 ## The recursive approach to macro writing
308
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
311 "wins".
312
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
315 input patterns:
316
317 ~~~~
318 # macro_rules! b {
319     ( binds $( $bind_res:ident ),* )
320 # => (0) }
321 # fn main() {}
322 ~~~~
323
324 ...and:
325
326 ~~~~
327 # fn main() {}
328 # macro_rules! b {
329     (    ($e     :expr) -> ($p     :pat) else $err     :stmt ;
330       $( ($e_rest:expr) -> ($p_rest:pat) else $err_rest:stmt ; )*
331       binds  $( $bind_res:ident ),*
332     )
333 # => (0) }
334 ~~~~
335
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.
339
340 ~~~~
341 # fn main() {
342
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 ),*
348     ) => (
349         match $e {
350             $p => {
351                 // Recursively handle the next layer
352                 biased_match_rec!($( ($e_rest) -> ($p_rest) else $err_rest ; )*
353                                   binds $( $bind_res ),*
354                 )
355             }
356             _ => { $err }
357         }
358     );
359     // Produce the requested values
360     ( binds $( $bind_res:ident ),* ) => ( ($( $bind_res ),*) )
361 }
362
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
368     ) => (
369         let $bind_res = biased_match_rec!(
370             $( ($e) -> ($p) else $err ; )*
371             binds $bind_res
372         );
373     );
374     // more than one name: use a tuple
375     ( $( ($e:expr) -> ($p:pat) else $err:stmt ; )*
376       binds  $( $bind_res:ident ),*
377     ) => (
378         let ( $( $bind_res ),* ) = biased_match_rec!(
379             $( ($e) -> ($p) else $err ; )*
380             binds $( $bind_res ),*
381         );
382     )
383 }
384
385
386 # enum T1 { Good1(T2, u32), Bad1}
387 # struct T2 { body: T3 }
388 # enum T3 { Good2(u32), Bad2}
389 # fn f(x: T1) -> u32 {
390 biased_match!(
391     (x)       -> (T1::Good1(g1, val)) else { return 0 };
392     (g1.body) -> (T3::Good2(result) ) else { panic!("Didn't get Good2") };
393     binds val, result );
394 // complicated stuff goes here
395 return result + val;
396 # }
397 # }
398 ~~~~
399
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.
403
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.
411
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).
419
420 # Hygiene
421
422 To prevent clashes, rust implements
423 [hygienic macros](http://en.wikipedia.org/wiki/Hygienic_macro).
424
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:
427
428 ~~~
429 macro_rules! loop_x {
430     ($e: expr) => (
431         // $e will not interact with this 'x
432         'x: loop {
433             println!("Hello!");
434             $e
435         }
436     );
437 }
438
439 fn main() {
440     'x: loop {
441         loop_x!(break 'x);
442         println!("I am never printed.");
443     }
444 }
445 ~~~
446
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.
449
450 # Scoping and macro import/export
451
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.
455
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.
460
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.
463
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`
467 item, and so forth.
468
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.
471
472 ```rust,ignore
473 #[macro_use(foo, bar)]
474 extern crate baz;
475 ```
476
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.
480
481 To load a crate's macros *without* linking it into the output, use `#[no_link]`
482 as well.
483
484 An example:
485
486 ```rust
487 macro_rules! m1 { () => (()) }
488
489 // visible here: m1
490
491 mod foo {
492     // visible here: m1
493
494     #[macro_export]
495     macro_rules! m2 { () => (()) }
496
497     // visible here: m1, m2
498 }
499
500 // visible here: m1
501
502 macro_rules! m3 { () => (()) }
503
504 // visible here: m1, m3
505
506 #[macro_use]
507 mod bar {
508     // visible here: m1, m3
509
510     macro_rules! m4 { () => (()) }
511
512     // visible here: m1, m3, m4
513 }
514
515 // visible here: m1, m3, m4
516 # fn main() { }
517 ```
518
519 When this library is loaded with `#[use_macros] extern crate`, only `m2` will
520 be imported.
521
522 The Rust Reference has a [listing of macro-related
523 attributes](../reference.html#macro--and-plugin-related-attributes).
524
525 # The variable `$crate`
526
527 A further difficulty occurs when a macro is used in multiple crates.  Say that
528 `mylib` defines
529
530 ```rust
531 pub fn increment(x: u32) -> u32 {
532     x + 1
533 }
534
535 #[macro_export]
536 macro_rules! inc_a {
537     ($x:expr) => ( ::increment($x) )
538 }
539
540 #[macro_export]
541 macro_rules! inc_b {
542     ($x:expr) => ( ::mylib::increment($x) )
543 }
544 # fn main() { }
545 ```
546
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
549 another name.
550
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
556
557 ```rust
558 #[macro_export]
559 macro_rules! inc {
560     ($x:expr) => ( $crate::increment($x) )
561 }
562 # fn main() { }
563 ```
564
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`.
567
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.
571
572 # A final note
573
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.
581
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.