11% The Rust Macros Guide
22
3- <div class =" unstable-feature " >
4- <b >Warning:</b > There are currently various problems with invoking macros, how
5- they interact with their environment, and how they are used outside of the
6- location in which they are defined. Macro definitions are likely to change
7- slightly in the future. For this reason, they are hidden behind the
8- <code >macro_rules</code > <a href =" reference.html#compiler-features " >feature
9- attribute</a >.
10- </div >
11-
123# Introduction
134
145Functions are the primary tool that programmers can use to build abstractions.
@@ -46,19 +37,18 @@ lightweight custom syntax extensions, themselves defined using the
4637the pattern in the above code:
4738
4839~~~~
49- # #![feature(macro_rules)]
5040# enum T { SpecialA(uint), SpecialB(uint) }
5141# fn f() -> uint {
5242# let input_1 = T::SpecialA(0);
5343# let input_2 = T::SpecialA(0);
54- macro_rules! early_return(
44+ macro_rules! early_return {
5545 ($inp:expr $sp:path) => ( // invoke it like `(input_5 SpecialE)`
5646 match $inp {
5747 $sp(x) => { return x; }
5848 _ => {}
5949 }
6050 );
61- );
51+ }
6252// ...
6353early_return!(input_1 T::SpecialA);
6454// ...
@@ -109,10 +99,10 @@ that could be invoked like: `my_macro!(i->(( 2+2 )))`.
10999
110100## Invocation location
111101
112- A macro invocation may take the place of (and therefore expand to)
113- an expression, an item, or a statement.
114- The Rust parser will parse the macro invocation as a "placeholder"
115- for whichever of those three nonterminals is appropriate for the location.
102+ A macro invocation may take the place of (and therefore expand to) an
103+ expression, item, statement, or pattern. The Rust parser will parse the macro
104+ invocation as a "placeholder" for whichever syntactic form is appropriate for
105+ the location.
116106
117107At expansion time, the output of the macro will be parsed as whichever of the
118108three nonterminals it stands in for. This means that a single macro might,
@@ -166,12 +156,11 @@ separator token (a comma-separated list could be written `$(...),*`), and `+`
166156instead of ` * ` to mean "at least one".
167157
168158~~~~
169- # #![feature(macro_rules)]
170159# enum T { SpecialA(uint),SpecialB(uint),SpecialC(uint),SpecialD(uint)}
171160# fn f() -> uint {
172161# let input_1 = T::SpecialA(0);
173162# let input_2 = T::SpecialA(0);
174- macro_rules! early_return(
163+ macro_rules! early_return {
175164 ($inp:expr, [ $($sp:path)|+ ]) => (
176165 match $inp {
177166 $(
@@ -180,7 +169,7 @@ macro_rules! early_return(
180169 _ => {}
181170 }
182171 )
183- );
172+ }
184173// ...
185174early_return!(input_1, [T::SpecialA|T::SpecialC|T::SpecialD]);
186175// ...
@@ -228,7 +217,6 @@ solves the problem.
228217Now consider code like the following:
229218
230219~~~~
231- # #![feature(macro_rules)]
232220# enum T1 { Good1(T2, uint), Bad1}
233221# struct T2 { body: T3 }
234222# enum T3 { Good2(uint), Bad2}
@@ -255,8 +243,7 @@ a match, but with a syntax that suits the problem better. The following macro
255243can solve the problem:
256244
257245~~~~
258- # #![feature(macro_rules)]
259- macro_rules! biased_match (
246+ macro_rules! biased_match {
260247 // special case: `let (x) = ...` is illegal, so use `let x = ...` instead
261248 ( ($e:expr) ~ ($p:pat) else $err:stmt ;
262249 binds $bind_res:ident
@@ -275,7 +262,7 @@ macro_rules! biased_match (
275262 _ => { $err }
276263 };
277264 )
278- );
265+ }
279266
280267# enum T1 { Good1(T2, uint), Bad1}
281268# struct T2 { body: T3 }
@@ -297,13 +284,12 @@ like this, we might prefer to write a single macro invocation. The input
297284pattern we want is clear:
298285
299286~~~~
300- # #![feature(macro_rules)]
301287# fn main() {}
302- # macro_rules! b(
288+ # macro_rules! b {
303289 ( $( ($e:expr) ~ ($p:pat) else $err:stmt ; )*
304290 binds $( $bind_res:ident ),*
305291 )
306- # => (0));
292+ # => (0) }
307293~~~~
308294
309295However, it's not possible to directly expand to nested match statements. But
@@ -320,35 +306,32 @@ process the semicolon-terminated lines, one-by-one. So, we want the following
320306input patterns:
321307
322308~~~~
323- # #![feature(macro_rules)]
324- # macro_rules! b(
309+ # macro_rules! b {
325310 ( binds $( $bind_res:ident ),* )
326- # => (0));
311+ # => (0) }
327312# fn main() {}
328313~~~~
329314
330315...and:
331316
332317~~~~
333- # #![feature(macro_rules)]
334318# fn main() {}
335- # macro_rules! b(
319+ # macro_rules! b {
336320 ( ($e :expr) ~ ($p :pat) else $err :stmt ;
337321 $( ($e_rest:expr) ~ ($p_rest:pat) else $err_rest:stmt ; )*
338322 binds $( $bind_res:ident ),*
339323 )
340- # => (0));
324+ # => (0) }
341325~~~~
342326
343327The resulting macro looks like this. Note that the separation into
344328` biased_match! ` and ` biased_match_rec! ` occurs only because we have an outer
345329piece of syntax (the ` let ` ) which we only want to transcribe once.
346330
347331~~~~
348- # #![feature(macro_rules)]
349332# fn main() {
350333
351- macro_rules! biased_match_rec (
334+ macro_rules! biased_match_rec {
352335 // Handle the first layer
353336 ( ($e :expr) ~ ($p :pat) else $err :stmt ;
354337 $( ($e_rest:expr) ~ ($p_rest:pat) else $err_rest:stmt ; )*
@@ -366,10 +349,10 @@ macro_rules! biased_match_rec (
366349 );
367350 // Produce the requested values
368351 ( binds $( $bind_res:ident ),* ) => ( ($( $bind_res ),*) )
369- );
352+ }
370353
371354// Wrap the whole thing in a `let`.
372- macro_rules! biased_match (
355+ macro_rules! biased_match {
373356 // special case: `let (x) = ...` is illegal, so use `let x = ...` instead
374357 ( $( ($e:expr) ~ ($p:pat) else $err:stmt ; )*
375358 binds $bind_res:ident
@@ -388,7 +371,7 @@ macro_rules! biased_match (
388371 binds $( $bind_res ),*
389372 );
390373 )
391- );
374+ }
392375
393376
394377# enum T1 { Good1(T2, uint), Bad1}
@@ -434,17 +417,15 @@ As an example, `loop` and `for-loop` labels (discussed in the lifetimes guide)
434417will not clash. The following code will print "Hello!" only once:
435418
436419~~~
437- #![feature(macro_rules)]
438-
439- macro_rules! loop_x (
420+ macro_rules! loop_x {
440421 ($e: expr) => (
441422 // $e will not interact with this 'x
442423 'x: loop {
443424 println!("Hello!");
444425 $e
445426 }
446427 );
447- );
428+ }
448429
449430fn main() {
450431 'x: loop {
@@ -467,45 +448,53 @@ lexical-order traversal of a crate's source. So a macro defined at module scope
467448is visible to any subsequent code in the same module, which includes the body
468449of any subsequent child ` mod ` items.
469450
470- If a module has the ` macro_escape ` attribute, its macros are also visible in
471- its parent module after the child's ` mod ` item. If the parent also has
472- ` macro_escape ` then the macros will be visible in the grandparent after the
473- parent's ` mod ` item, and so forth.
451+ If a module has the ` macro_use ` attribute, its macros are also visible in its
452+ parent module after the child's ` mod ` item. If the parent also has ` macro_use `
453+ then the macros will be visible in the grandparent after the parent's ` mod `
454+ item, and so forth.
474455
475- Independent of ` macro_escape ` , the ` macro_export ` attribute controls visibility
476- between crates. Any ` macro_rules! ` definition with the ` macro_export `
477- attribute will be visible to other crates that have loaded this crate with
478- ` phase(plugin) ` . There is currently no way for the importing crate to control
479- which macros are imported.
456+ The ` macro_use ` attribute can also appear on ` extern crate ` . In this context
457+ it controls which macros are loaded from the external crate, e.g.
458+
459+ ``` rust,ignore
460+ #[macro_use(foo, bar)]
461+ extern crate baz;
462+ ```
463+
464+ If the attribute is given simply as ` #[macro_use] ` , all macros are loaded. If
465+ there is no ` #[macro_use] ` attribute then no macros are loaded. Only macros
466+ defined with the ` #[macro_export] ` attribute may be loaded.
467+
468+ To load a crate's macros * without* linking it into the output, use ` #[no_link] `
469+ as well.
480470
481471An example:
482472
483473``` rust
484- # #![feature(macro_rules)]
485- macro_rules! m1 (() => (()));
474+ macro_rules! m1 { () => (()) }
486475
487476// visible here: m1
488477
489478mod foo {
490479 // visible here: m1
491480
492481 #[macro_export]
493- macro_rules! m2 (( ) => (()));
482+ macro_rules! m2 { ( ) => (()) }
494483
495484 // visible here: m1, m2
496485}
497486
498487// visible here: m1
499488
500- macro_rules! m3 (( ) => (()));
489+ macro_rules! m3 { ( ) => (()) }
501490
502491// visible here: m1, m3
503492
504- #[macro_escape ]
493+ #[macro_use ]
505494mod bar {
506495 // visible here: m1, m3
507496
508- macro_rules! m4 (( ) => (()));
497+ macro_rules! m4 { ( ) => (()) }
509498
510499 // visible here: m1, m3, m4
511500}
@@ -514,8 +503,58 @@ mod bar {
514503# fn main () { }
515504```
516505
517- When this library is loaded with ` #[phase(plugin)] extern crate ` , only ` m2 `
518- will be imported.
506+ When this library is loaded with ` #[use_macros] extern crate ` , only ` m2 ` will
507+ be imported.
508+
509+ The Rust Reference has a [ listing of macro-related
510+ attributes] ( reference.html#macro--and-plugin-related-attributes ) .
511+
512+ # The variable ` $crate `
513+
514+ A further difficulty occurs when a macro is used in multiple crates. Say that
515+ ` mylib ` defines
516+
517+ ``` rust
518+ pub fn increment (x : uint ) -> uint {
519+ x + 1
520+ }
521+
522+ #[macro_export]
523+ macro_rules! inc_a {
524+ ($ x : expr ) => ( :: increment ($ x ) )
525+ }
526+
527+ #[macro_export]
528+ macro_rules! inc_b {
529+ ($ x : expr ) => ( :: mylib :: increment ($ x ) )
530+ }
531+ # fn main () { }
532+ ```
533+
534+ ` inc_a ` only works within ` mylib ` , while ` inc_b ` only works outside the
535+ library. Furthermore, ` inc_b ` will break if the user imports ` mylib ` under
536+ another name.
537+
538+ Rust does not (yet) have a hygiene system for crate references, but it does
539+ provide a simple workaround for this problem. Within a macro imported from a
540+ crate named ` foo ` , the special macro variable ` $crate ` will expand to ` ::foo ` .
541+ By contrast, when a macro is defined and then used in the same crate, ` $crate `
542+ will expand to nothing. This means we can write
543+
544+ ``` rust
545+ #[macro_export]
546+ macro_rules! inc {
547+ ($ x : expr ) => ( $ crate :: increment ($ x ) )
548+ }
549+ # fn main () { }
550+ ```
551+
552+ to define a single macro that works both inside and outside our library. The
553+ function name will expand to either ` ::increment ` or ` ::mylib::increment ` .
554+
555+ To keep this system simple and correct, ` #[macro_use] extern crate ... ` may
556+ only appear at the root of your crate, not inside ` mod ` . This ensures that
557+ ` $crate ` is a single identifier.
519558
520559# A final note
521560
0 commit comments