]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/macros.md
Auto merge of #24646 - brson:stab, r=alexcrichton
[rust.git] / src / doc / trpl / macros.md
1 % Macros
2
3 By now you've learned about many of the tools Rust provides for abstracting and
4 reusing code. These units of code reuse have a rich semantic structure. For
5 example, functions have a type signature, type parameters have trait bounds,
6 and overloaded functions must belong to a particular trait.
7
8 This structure means that Rust's core abstractions have powerful compile-time
9 correctness checking. But this comes at the price of reduced flexibility. If
10 you visually identify a pattern of repeated code, you may find it's difficult
11 or cumbersome to express that pattern as a generic function, a trait, or
12 anything else within Rust's semantics.
13
14 Macros allow us to abstract at a *syntactic* level. A macro invocation is
15 shorthand for an "expanded" syntactic form. This expansion happens early in
16 compilation, before any static checking. As a result, macros can capture many
17 patterns of code reuse that Rust's core abstractions cannot.
18
19 The drawback is that macro-based code can be harder to understand, because
20 fewer of the built-in rules apply. Like an ordinary function, a well-behaved
21 macro can be used without understanding its implementation. However, it can be
22 difficult to design a well-behaved macro!  Additionally, compiler errors in
23 macro code are harder to interpret, because they describe problems in the
24 expanded code, not the source-level form that developers use.
25
26 These drawbacks make macros something of a "feature of last resort". That's not
27 to say that macros are bad; they are part of Rust because sometimes they're
28 needed for truly concise, well-abstracted code. Just keep this tradeoff in
29 mind.
30
31 # Defining a macro
32
33 You may have seen the `vec!` macro, used to initialize a [vector][] with any
34 number of elements.
35
36 [vector]: vectors.html
37
38 ```rust
39 let x: Vec<u32> = vec![1, 2, 3];
40 # assert_eq!(x, [1, 2, 3]);
41 ```
42
43 This can't be an ordinary function, because it takes any number of arguments.
44 But we can imagine it as syntactic shorthand for
45
46 ```rust
47 let x: Vec<u32> = {
48     let mut temp_vec = Vec::new();
49     temp_vec.push(1);
50     temp_vec.push(2);
51     temp_vec.push(3);
52     temp_vec
53 };
54 # assert_eq!(x, [1, 2, 3]);
55 ```
56
57 We can implement this shorthand, using a macro: [^actual]
58
59 [^actual]: The actual definition of `vec!` in libcollections differs from the
60            one presented here, for reasons of efficiency and reusability. Some
61            of these are mentioned in the [advanced macros chapter][].
62
63 ```rust
64 macro_rules! vec {
65     ( $( $x:expr ),* ) => {
66         {
67             let mut temp_vec = Vec::new();
68             $(
69                 temp_vec.push($x);
70             )*
71             temp_vec
72         }
73     };
74 }
75 # fn main() {
76 #     assert_eq!(vec![1,2,3], [1, 2, 3]);
77 # }
78 ```
79
80 Whoa, that's a lot of new syntax! Let's break it down.
81
82 ```ignore
83 macro_rules! vec { ... }
84 ```
85
86 This says we're defining a macro named `vec`, much as `fn vec` would define a
87 function named `vec`. In prose, we informally write a macro's name with an
88 exclamation point, e.g. `vec!`. The exclamation point is part of the invocation
89 syntax and serves to distinguish a macro from an ordinary function.
90
91 ## Matching
92
93 The macro is defined through a series of *rules*, which are pattern-matching
94 cases. Above, we had
95
96 ```ignore
97 ( $( $x:expr ),* ) => { ... };
98 ```
99
100 This is like a `match` expression arm, but the matching happens on Rust syntax
101 trees, at compile time. The semicolon is optional on the last (here, only)
102 case. The "pattern" on the left-hand side of `=>` is known as a *matcher*.
103 These have [their own little grammar] within the language.
104
105 [their own little grammar]: ../reference.html#macros
106
107 The matcher `$x:expr` will match any Rust expression, binding that syntax tree
108 to the *metavariable* `$x`. The identifier `expr` is a *fragment specifier*;
109 the full possibilities are enumerated in the [advanced macros chapter][].
110 Surrounding the matcher with `$(...),*` will match zero or more expressions,
111 separated by commas.
112
113 Aside from the special matcher syntax, any Rust tokens that appear in a matcher
114 must match exactly. For example,
115
116 ```rust
117 macro_rules! foo {
118     (x => $e:expr) => (println!("mode X: {}", $e));
119     (y => $e:expr) => (println!("mode Y: {}", $e));
120 }
121
122 fn main() {
123     foo!(y => 3);
124 }
125 ```
126
127 will print
128
129 ```text
130 mode Y: 3
131 ```
132
133 With
134
135 ```rust,ignore
136 foo!(z => 3);
137 ```
138
139 we get the compiler error
140
141 ```text
142 error: no rules expected the token `z`
143 ```
144
145 ## Expansion
146
147 The right-hand side of a macro rule is ordinary Rust syntax, for the most part.
148 But we can splice in bits of syntax captured by the matcher. From the original
149 example:
150
151 ```ignore
152 $(
153     temp_vec.push($x);
154 )*
155 ```
156
157 Each matched expression `$x` will produce a single `push` statement in the
158 macro expansion. The repetition in the expansion proceeds in "lockstep" with
159 repetition in the matcher (more on this in a moment).
160
161 Because `$x` was already declared as matching an expression, we don't repeat
162 `:expr` on the right-hand side. Also, we don't include a separating comma as
163 part of the repetition operator. Instead, we have a terminating semicolon
164 within the repeated block.
165
166 Another detail: the `vec!` macro has *two* pairs of braces on the right-hand
167 side. They are often combined like so:
168
169 ```ignore
170 macro_rules! foo {
171     () => {{
172         ...
173     }}
174 }
175 ```
176
177 The outer braces are part of the syntax of `macro_rules!`. In fact, you can use
178 `()` or `[]` instead. They simply delimit the right-hand side as a whole.
179
180 The inner braces are part of the expanded syntax. Remember, the `vec!` macro is
181 used in an expression context. To write an expression with multiple statements,
182 including `let`-bindings, we use a block. If your macro expands to a single
183 expression, you don't need this extra layer of braces.
184
185 Note that we never *declared* that the macro produces an expression. In fact,
186 this is not determined until we use the macro as an expression. With care, you
187 can write a macro whose expansion works in several contexts. For example,
188 shorthand for a data type could be valid as either an expression or a pattern.
189
190 ## Repetition
191
192 The repetition operator follows two principal rules:
193
194 1. `$(...)*` walks through one "layer" of repetitions, for all of the `$name`s
195    it contains, in lockstep, and
196 2. each `$name` must be under at least as many `$(...)*`s as it was matched
197    against. If it is under more, it'll be duplicated, as appropriate.
198
199 This baroque macro illustrates the duplication of variables from outer
200 repetition levels.
201
202 ```rust
203 macro_rules! o_O {
204     (
205         $(
206             $x:expr; [ $( $y:expr ),* ]
207         );*
208     ) => {
209         &[ $($( $x + $y ),*),* ]
210     }
211 }
212
213 fn main() {
214     let a: &[i32]
215         = o_O!(10; [1, 2, 3];
216                20; [4, 5, 6]);
217
218     assert_eq!(a, [11, 12, 13, 24, 25, 26]);
219 }
220 ```
221
222 That's most of the matcher syntax. These examples use `$(...)*`, which is a
223 "zero or more" match. Alternatively you can write `$(...)+` for a "one or
224 more" match. Both forms optionally include a separator, which can be any token
225 except `+` or `*`.
226
227 This system is based on
228 "[Macro-by-Example](http://www.cs.indiana.edu/ftp/techreports/TR206.pdf)"
229 (PDF link).
230
231 # Hygiene
232
233 Some languages implement macros using simple text substitution, which leads to
234 various problems. For example, this C program prints `13` instead of the
235 expected `25`.
236
237 ```text
238 #define FIVE_TIMES(x) 5 * x
239
240 int main() {
241     printf("%d\n", FIVE_TIMES(2 + 3));
242     return 0;
243 }
244 ```
245
246 After expansion we have `5 * 2 + 3`, and multiplication has greater precedence
247 than addition. If you've used C macros a lot, you probably know the standard
248 idioms for avoiding this problem, as well as five or six others. In Rust, we
249 don't have to worry about it.
250
251 ```rust
252 macro_rules! five_times {
253     ($x:expr) => (5 * $x);
254 }
255
256 fn main() {
257     assert_eq!(25, five_times!(2 + 3));
258 }
259 ```
260
261 The metavariable `$x` is parsed as a single expression node, and keeps its
262 place in the syntax tree even after substitution.
263
264 Another common problem in macro systems is *variable capture*. Here's a C
265 macro, using [a GNU C extension] to emulate Rust's expression blocks.
266
267 [a GNU C extension]: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
268
269 ```text
270 #define LOG(msg) ({ \
271     int state = get_log_state(); \
272     if (state > 0) { \
273         printf("log(%d): %s\n", state, msg); \
274     } \
275 })
276 ```
277
278 Here's a simple use case that goes terribly wrong:
279
280 ```text
281 const char *state = "reticulating splines";
282 LOG(state)
283 ```
284
285 This expands to
286
287 ```text
288 const char *state = "reticulating splines";
289 int state = get_log_state();
290 if (state > 0) {
291     printf("log(%d): %s\n", state, state);
292 }
293 ```
294
295 The second variable named `state` shadows the first one.  This is a problem
296 because the print statement should refer to both of them.
297
298 The equivalent Rust macro has the desired behavior.
299
300 ```rust
301 # fn get_log_state() -> i32 { 3 }
302 macro_rules! log {
303     ($msg:expr) => {{
304         let state: i32 = get_log_state();
305         if state > 0 {
306             println!("log({}): {}", state, $msg);
307         }
308     }};
309 }
310
311 fn main() {
312     let state: &str = "reticulating splines";
313     log!(state);
314 }
315 ```
316
317 This works because Rust has a [hygienic macro system][]. Each macro expansion
318 happens in a distinct *syntax context*, and each variable is tagged with the
319 syntax context where it was introduced. It's as though the variable `state`
320 inside `main` is painted a different "color" from the variable `state` inside
321 the macro, and therefore they don't conflict.
322
323 [hygienic macro system]: http://en.wikipedia.org/wiki/Hygienic_macro
324
325 This also restricts the ability of macros to introduce new bindings at the
326 invocation site. Code such as the following will not work:
327
328 ```rust,ignore
329 macro_rules! foo {
330     () => (let x = 3);
331 }
332
333 fn main() {
334     foo!();
335     println!("{}", x);
336 }
337 ```
338
339 Instead you need to pass the variable name into the invocation, so it's tagged
340 with the right syntax context.
341
342 ```rust
343 macro_rules! foo {
344     ($v:ident) => (let $v = 3);
345 }
346
347 fn main() {
348     foo!(x);
349     println!("{}", x);
350 }
351 ```
352
353 This holds for `let` bindings and loop labels, but not for [items][].
354 So the following code does compile:
355
356 ```rust
357 macro_rules! foo {
358     () => (fn x() { });
359 }
360
361 fn main() {
362     foo!();
363     x();
364 }
365 ```
366
367 [items]: ../reference.html#items
368
369 # Recursive macros
370
371 A macro's expansion can include more macro invocations, including invocations
372 of the very same macro being expanded.  These recursive macros are useful for
373 processing tree-structured input, as illustrated by this (simplistic) HTML
374 shorthand:
375
376 ```rust
377 # #![allow(unused_must_use)]
378 macro_rules! write_html {
379     ($w:expr, ) => (());
380
381     ($w:expr, $e:tt) => (write!($w, "{}", $e));
382
383     ($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{
384         write!($w, "<{}>", stringify!($tag));
385         write_html!($w, $($inner)*);
386         write!($w, "</{}>", stringify!($tag));
387         write_html!($w, $($rest)*);
388     }};
389 }
390
391 fn main() {
392 #   // FIXME(#21826)
393     use std::fmt::Write;
394     let mut out = String::new();
395
396     write_html!(&mut out,
397         html[
398             head[title["Macros guide"]]
399             body[h1["Macros are the best!"]]
400         ]);
401
402     assert_eq!(out,
403         "<html><head><title>Macros guide</title></head>\
404          <body><h1>Macros are the best!</h1></body></html>");
405 }
406 ```
407
408 # Debugging macro code
409
410 To see the results of expanding macros, run `rustc --pretty expanded`. The
411 output represents a whole crate, so you can also feed it back in to `rustc`,
412 which will sometimes produce better error messages than the original
413 compilation. Note that the `--pretty expanded` output may have a different
414 meaning if multiple variables of the same name (but different syntax contexts)
415 are in play in the same scope. In this case `--pretty expanded,hygiene` will
416 tell you about the syntax contexts.
417
418 `rustc` provides two syntax extensions that help with macro debugging. For now,
419 they are unstable and require feature gates.
420
421 * `log_syntax!(...)` will print its arguments to standard output, at compile
422   time, and "expand" to nothing.
423
424 * `trace_macros!(true)` will enable a compiler message every time a macro is
425   expanded. Use `trace_macros!(false)` later in expansion to turn it off.
426
427 # Syntactic requirements
428
429 Even when Rust code contains un-expanded macros, it can be parsed as a full
430 [syntax tree][ast]. This property can be very useful for editors and other
431 tools that process code. It also has a few consequences for the design of
432 Rust's macro system.
433
434 [ast]: glossary.html#abstract-syntax-tree
435
436 One consequence is that Rust must determine, when it parses a macro invocation,
437 whether the macro stands in for
438
439 * zero or more items,
440 * zero or more methods,
441 * an expression,
442 * a statement, or
443 * a pattern.
444
445 A macro invocation within a block could stand for some items, or for an
446 expression / statement. Rust uses a simple rule to resolve this ambiguity. A
447 macro invocation that stands for items must be either
448
449 * delimited by curly braces, e.g. `foo! { ... }`, or
450 * terminated by a semicolon, e.g. `foo!(...);`
451
452 Another consequence of pre-expansion parsing is that the macro invocation must
453 consist of valid Rust tokens. Furthermore, parentheses, brackets, and braces
454 must be balanced within a macro invocation. For example, `foo!([)` is
455 forbidden. This allows Rust to know where the macro invocation ends.
456
457 More formally, the macro invocation body must be a sequence of *token trees*.
458 A token tree is defined recursively as either
459
460 * a sequence of token trees surrounded by matching `()`, `[]`, or `{}`, or
461 * any other single token.
462
463 Within a matcher, each metavariable has a *fragment specifier*, identifying
464 which syntactic form it matches.
465
466 * `ident`: an identifier. Examples: `x`; `foo`.
467 * `path`: a qualified name. Example: `T::SpecialA`.
468 * `expr`: an expression. Examples: `2 + 2`; `if true then { 1 } else { 2 }`; `f(42)`.
469 * `ty`: a type. Examples: `i32`; `Vec<(char, String)>`; `&T`.
470 * `pat`: a pattern. Examples: `Some(t)`; `(17, 'a')`; `_`.
471 * `stmt`: a single statement. Example: `let x = 3`.
472 * `block`: a brace-delimited sequence of statements. Example:
473   `{ log(error, "hi"); return 12; }`.
474 * `item`: an [item][]. Examples: `fn foo() { }`; `struct Bar;`.
475 * `meta`: a "meta item", as found in attributes. Example: `cfg(target_os = "windows")`.
476 * `tt`: a single token tree.
477
478 There are additional rules regarding the next token after a metavariable:
479
480 * `expr` variables must be followed by one of: `=> , ;`
481 * `ty` and `path` variables must be followed by one of: `=> , : = > as`
482 * `pat` variables must be followed by one of: `=> , =`
483 * Other variables may be followed by any token.
484
485 These rules provide some flexibility for Rust's syntax to evolve without
486 breaking existing macros.
487
488 The macro system does not deal with parse ambiguity at all. For example, the
489 grammar `$($t:ty)* $e:expr` will always fail to parse, because the parser would
490 be forced to choose between parsing `$t` and parsing `$e`. Changing the
491 invocation syntax to put a distinctive token in front can solve the problem. In
492 this case, you can write `$(T $t:ty)* E $e:exp`.
493
494 [item]: ../reference.html#items
495
496 # Scoping and macro import/export
497
498 Macros are expanded at an early stage in compilation, before name resolution.
499 One downside is that scoping works differently for macros, compared to other
500 constructs in the language.
501
502 Definition and expansion of macros both happen in a single depth-first,
503 lexical-order traversal of a crate's source. So a macro defined at module scope
504 is visible to any subsequent code in the same module, which includes the body
505 of any subsequent child `mod` items.
506
507 A macro defined within the body of a single `fn`, or anywhere else not at
508 module scope, is visible only within that item.
509
510 If a module has the `macro_use` attribute, its macros are also visible in its
511 parent module after the child's `mod` item. If the parent also has `macro_use`
512 then the macros will be visible in the grandparent after the parent's `mod`
513 item, and so forth.
514
515 The `macro_use` attribute can also appear on `extern crate`. In this context
516 it controls which macros are loaded from the external crate, e.g.
517
518 ```rust,ignore
519 #[macro_use(foo, bar)]
520 extern crate baz;
521 ```
522
523 If the attribute is given simply as `#[macro_use]`, all macros are loaded. If
524 there is no `#[macro_use]` attribute then no macros are loaded. Only macros
525 defined with the `#[macro_export]` attribute may be loaded.
526
527 To load a crate's macros *without* linking it into the output, use `#[no_link]`
528 as well.
529
530 An example:
531
532 ```rust
533 macro_rules! m1 { () => (()) }
534
535 // visible here: m1
536
537 mod foo {
538     // visible here: m1
539
540     #[macro_export]
541     macro_rules! m2 { () => (()) }
542
543     // visible here: m1, m2
544 }
545
546 // visible here: m1
547
548 macro_rules! m3 { () => (()) }
549
550 // visible here: m1, m3
551
552 #[macro_use]
553 mod bar {
554     // visible here: m1, m3
555
556     macro_rules! m4 { () => (()) }
557
558     // visible here: m1, m3, m4
559 }
560
561 // visible here: m1, m3, m4
562 # fn main() { }
563 ```
564
565 When this library is loaded with `#[macro_use] extern crate`, only `m2` will
566 be imported.
567
568 The Rust Reference has a [listing of macro-related
569 attributes](../reference.html#macro--and-plugin-related-attributes).
570
571 # The variable `$crate`
572
573 A further difficulty occurs when a macro is used in multiple crates. Say that
574 `mylib` defines
575
576 ```rust
577 pub fn increment(x: u32) -> u32 {
578     x + 1
579 }
580
581 #[macro_export]
582 macro_rules! inc_a {
583     ($x:expr) => ( ::increment($x) )
584 }
585
586 #[macro_export]
587 macro_rules! inc_b {
588     ($x:expr) => ( ::mylib::increment($x) )
589 }
590 # fn main() { }
591 ```
592
593 `inc_a` only works within `mylib`, while `inc_b` only works outside the
594 library. Furthermore, `inc_b` will break if the user imports `mylib` under
595 another name.
596
597 Rust does not (yet) have a hygiene system for crate references, but it does
598 provide a simple workaround for this problem. Within a macro imported from a
599 crate named `foo`, the special macro variable `$crate` will expand to `::foo`.
600 By contrast, when a macro is defined and then used in the same crate, `$crate`
601 will expand to nothing. This means we can write
602
603 ```rust
604 #[macro_export]
605 macro_rules! inc {
606     ($x:expr) => ( $crate::increment($x) )
607 }
608 # fn main() { }
609 ```
610
611 to define a single macro that works both inside and outside our library. The
612 function name will expand to either `::increment` or `::mylib::increment`.
613
614 To keep this system simple and correct, `#[macro_use] extern crate ...` may
615 only appear at the root of your crate, not inside `mod`. This ensures that
616 `$crate` is a single identifier.
617
618 # The deep end
619
620 The introductory chapter mentioned recursive macros, but it did not give the
621 full story. Recursive macros are useful for another reason: Each recursive
622 invocation gives you another opportunity to pattern-match the macro's
623 arguments.
624
625 As an extreme example, it is possible, though hardly advisable, to implement
626 the [Bitwise Cyclic Tag](http://esolangs.org/wiki/Bitwise_Cyclic_Tag) automaton
627 within Rust's macro system.
628
629 ```rust
630 macro_rules! bct {
631     // cmd 0:  d ... => ...
632     (0, $($ps:tt),* ; $_d:tt)
633         => (bct!($($ps),*, 0 ; ));
634     (0, $($ps:tt),* ; $_d:tt, $($ds:tt),*)
635         => (bct!($($ps),*, 0 ; $($ds),*));
636
637     // cmd 1p:  1 ... => 1 ... p
638     (1, $p:tt, $($ps:tt),* ; 1)
639         => (bct!($($ps),*, 1, $p ; 1, $p));
640     (1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*)
641         => (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p));
642
643     // cmd 1p:  0 ... => 0 ...
644     (1, $p:tt, $($ps:tt),* ; $($ds:tt),*)
645         => (bct!($($ps),*, 1, $p ; $($ds),*));
646
647     // halt on empty data string
648     ( $($ps:tt),* ; )
649         => (());
650 }
651 ```
652
653 Exercise: use macros to reduce duplication in the above definition of the
654 `bct!` macro.
655
656 # Common macros
657
658 Here are some common macros you’ll see in Rust code.
659
660 ## panic!
661
662 This macro causes the current thread to panic. You can give it a message
663 to panic with:
664
665 ```rust,no_run
666 panic!("oh no!");
667 ```
668
669 ## vec!
670
671 The `vec!` macro is used throughout the book, so you’ve probably seen it
672 already. It creates `Vec<T>`s with ease:
673
674 ```rust
675 let v = vec![1, 2, 3, 4, 5];
676 ```
677
678 It also lets you make vectors with repeating values. For example, a hundred
679 zeroes:
680
681 ```rust
682 let v = vec![0; 100];
683 ```
684
685 ## assert! and assert_eq!
686
687 These two macros are used in tests. `assert!` takes a boolean, and `assert_eq!`
688 takes two values and compares them. Truth passes, success `panic!`s. Like
689 this:
690
691 ```rust,no_run
692 // A-ok!
693
694 assert!(true);
695 assert_eq!(5, 3 + 2);
696
697 // nope :(
698
699 assert!(5 < 3);
700 assert_eq!(5, 3);
701 ```
702 ## try!
703
704 `try!` is used for error handling. It takes something that can return a
705 `Result<T, E>`, and gives `T` if it’s a `Ok<T>`, and `return`s with the
706 `Err(E)` if it’s that. Like this:
707
708 ```rust,no_run
709 use std::fs::File;
710
711 fn foo() -> std::io::Result<()> {
712     let f = try!(File::create("foo.txt"));
713
714     Ok(())
715 }
716 ```
717
718 This is cleaner than doing this:
719
720 ```rust,no_run
721 use std::fs::File;
722
723 fn foo() -> std::io::Result<()> {
724     let f = File::create("foo.txt");
725
726     let f = match f {
727         Ok(t) => t,
728         Err(e) => return Err(e),
729     };
730
731     Ok(())
732 }
733 ```
734
735 ## unreachable!
736
737 This macro is used when you think some code should never execute:
738
739 ```rust
740 if false {
741     unreachable!();
742 }
743 ```
744
745 Sometimes, the compiler may make you have a different branch that you know
746 will never, ever run. In these cases, use this macro, so that if you end
747 up wrong, you’ll get a `panic!` about it.
748
749 ```rust
750 let x: Option<i32> = None;
751
752 match x {
753     Some(_) => unreachable!(),
754     None => println!("I know x is None!"),
755 }
756 ```
757
758 ## unimplemented!
759
760 The `unimplemented!` macro can be used when you’re trying to get your functions
761 to typecheck, and don’t want to worry about writing out the body of the
762 function. One example of this situation is implementing a trait with multiple
763 required methods, where you want to tackle one at a time. Define the others
764 as `unimplemented!` until you’re ready to write them.
765
766 # Procedural macros
767
768 If Rust's macro system can't do what you need, you may want to write a
769 [compiler plugin](plugins.html) instead. Compared to `macro_rules!`
770 macros, this is significantly more work, the interfaces are much less stable,
771 and bugs can be much harder to track down. In exchange you get the
772 flexibility of running arbitrary Rust code within the compiler. Syntax
773 extension plugins are sometimes called *procedural macros* for this reason.