1
1
% The Rust Macros Guide
2
2
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
-
12
3
# Introduction
13
4
14
5
Functions are the primary tool that programmers can use to build abstractions.
@@ -46,19 +37,18 @@ lightweight custom syntax extensions, themselves defined using the
46
37
the pattern in the above code:
47
38
48
39
~~~~
49
- # #![feature(macro_rules)]
50
40
# enum T { SpecialA(uint), SpecialB(uint) }
51
41
# fn f() -> uint {
52
42
# let input_1 = T::SpecialA(0);
53
43
# let input_2 = T::SpecialA(0);
54
- macro_rules! early_return(
44
+ macro_rules! early_return {
55
45
($inp:expr $sp:path) => ( // invoke it like `(input_5 SpecialE)`
56
46
match $inp {
57
47
$sp(x) => { return x; }
58
48
_ => {}
59
49
}
60
50
);
61
- );
51
+ }
62
52
// ...
63
53
early_return!(input_1 T::SpecialA);
64
54
// ...
@@ -109,10 +99,10 @@ that could be invoked like: `my_macro!(i->(( 2+2 )))`.
109
99
110
100
## Invocation location
111
101
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.
116
106
117
107
At expansion time, the output of the macro will be parsed as whichever of the
118
108
three 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 `+`
166
156
instead of ` * ` to mean "at least one".
167
157
168
158
~~~~
169
- # #![feature(macro_rules)]
170
159
# enum T { SpecialA(uint),SpecialB(uint),SpecialC(uint),SpecialD(uint)}
171
160
# fn f() -> uint {
172
161
# let input_1 = T::SpecialA(0);
173
162
# let input_2 = T::SpecialA(0);
174
- macro_rules! early_return(
163
+ macro_rules! early_return {
175
164
($inp:expr, [ $($sp:path)|+ ]) => (
176
165
match $inp {
177
166
$(
@@ -180,7 +169,7 @@ macro_rules! early_return(
180
169
_ => {}
181
170
}
182
171
)
183
- );
172
+ }
184
173
// ...
185
174
early_return!(input_1, [T::SpecialA|T::SpecialC|T::SpecialD]);
186
175
// ...
@@ -228,7 +217,6 @@ solves the problem.
228
217
Now consider code like the following:
229
218
230
219
~~~~
231
- # #![feature(macro_rules)]
232
220
# enum T1 { Good1(T2, uint), Bad1}
233
221
# struct T2 { body: T3 }
234
222
# enum T3 { Good2(uint), Bad2}
@@ -255,8 +243,7 @@ a match, but with a syntax that suits the problem better. The following macro
255
243
can solve the problem:
256
244
257
245
~~~~
258
- # #![feature(macro_rules)]
259
- macro_rules! biased_match (
246
+ macro_rules! biased_match {
260
247
// special case: `let (x) = ...` is illegal, so use `let x = ...` instead
261
248
( ($e:expr) ~ ($p:pat) else $err:stmt ;
262
249
binds $bind_res:ident
@@ -275,7 +262,7 @@ macro_rules! biased_match (
275
262
_ => { $err }
276
263
};
277
264
)
278
- );
265
+ }
279
266
280
267
# enum T1 { Good1(T2, uint), Bad1}
281
268
# struct T2 { body: T3 }
@@ -297,13 +284,12 @@ like this, we might prefer to write a single macro invocation. The input
297
284
pattern we want is clear:
298
285
299
286
~~~~
300
- # #![feature(macro_rules)]
301
287
# fn main() {}
302
- # macro_rules! b(
288
+ # macro_rules! b {
303
289
( $( ($e:expr) ~ ($p:pat) else $err:stmt ; )*
304
290
binds $( $bind_res:ident ),*
305
291
)
306
- # => (0));
292
+ # => (0) }
307
293
~~~~
308
294
309
295
However, 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
320
306
input patterns:
321
307
322
308
~~~~
323
- # #![feature(macro_rules)]
324
- # macro_rules! b(
309
+ # macro_rules! b {
325
310
( binds $( $bind_res:ident ),* )
326
- # => (0));
311
+ # => (0) }
327
312
# fn main() {}
328
313
~~~~
329
314
330
315
...and:
331
316
332
317
~~~~
333
- # #![feature(macro_rules)]
334
318
# fn main() {}
335
- # macro_rules! b(
319
+ # macro_rules! b {
336
320
( ($e :expr) ~ ($p :pat) else $err :stmt ;
337
321
$( ($e_rest:expr) ~ ($p_rest:pat) else $err_rest:stmt ; )*
338
322
binds $( $bind_res:ident ),*
339
323
)
340
- # => (0));
324
+ # => (0) }
341
325
~~~~
342
326
343
327
The resulting macro looks like this. Note that the separation into
344
328
` biased_match! ` and ` biased_match_rec! ` occurs only because we have an outer
345
329
piece of syntax (the ` let ` ) which we only want to transcribe once.
346
330
347
331
~~~~
348
- # #![feature(macro_rules)]
349
332
# fn main() {
350
333
351
- macro_rules! biased_match_rec (
334
+ macro_rules! biased_match_rec {
352
335
// Handle the first layer
353
336
( ($e :expr) ~ ($p :pat) else $err :stmt ;
354
337
$( ($e_rest:expr) ~ ($p_rest:pat) else $err_rest:stmt ; )*
@@ -366,10 +349,10 @@ macro_rules! biased_match_rec (
366
349
);
367
350
// Produce the requested values
368
351
( binds $( $bind_res:ident ),* ) => ( ($( $bind_res ),*) )
369
- );
352
+ }
370
353
371
354
// Wrap the whole thing in a `let`.
372
- macro_rules! biased_match (
355
+ macro_rules! biased_match {
373
356
// special case: `let (x) = ...` is illegal, so use `let x = ...` instead
374
357
( $( ($e:expr) ~ ($p:pat) else $err:stmt ; )*
375
358
binds $bind_res:ident
@@ -388,7 +371,7 @@ macro_rules! biased_match (
388
371
binds $( $bind_res ),*
389
372
);
390
373
)
391
- );
374
+ }
392
375
393
376
394
377
# enum T1 { Good1(T2, uint), Bad1}
@@ -434,17 +417,15 @@ As an example, `loop` and `for-loop` labels (discussed in the lifetimes guide)
434
417
will not clash. The following code will print "Hello!" only once:
435
418
436
419
~~~
437
- #![feature(macro_rules)]
438
-
439
- macro_rules! loop_x (
420
+ macro_rules! loop_x {
440
421
($e: expr) => (
441
422
// $e will not interact with this 'x
442
423
'x: loop {
443
424
println!("Hello!");
444
425
$e
445
426
}
446
427
);
447
- );
428
+ }
448
429
449
430
fn main() {
450
431
'x: loop {
@@ -467,45 +448,53 @@ lexical-order traversal of a crate's source. So a macro defined at module scope
467
448
is visible to any subsequent code in the same module, which includes the body
468
449
of any subsequent child ` mod ` items.
469
450
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.
474
455
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.
480
470
481
471
An example:
482
472
483
473
``` rust
484
- # #![feature(macro_rules)]
485
- macro_rules! m1 (() => (()));
474
+ macro_rules! m1 { () => (()) }
486
475
487
476
// visible here: m1
488
477
489
478
mod foo {
490
479
// visible here: m1
491
480
492
481
#[macro_export]
493
- macro_rules! m2 (( ) => (()));
482
+ macro_rules! m2 { ( ) => (()) }
494
483
495
484
// visible here: m1, m2
496
485
}
497
486
498
487
// visible here: m1
499
488
500
- macro_rules! m3 (( ) => (()));
489
+ macro_rules! m3 { ( ) => (()) }
501
490
502
491
// visible here: m1, m3
503
492
504
- #[macro_escape ]
493
+ #[macro_use ]
505
494
mod bar {
506
495
// visible here: m1, m3
507
496
508
- macro_rules! m4 (( ) => (()));
497
+ macro_rules! m4 { ( ) => (()) }
509
498
510
499
// visible here: m1, m3, m4
511
500
}
@@ -514,8 +503,58 @@ mod bar {
514
503
# fn main () { }
515
504
```
516
505
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.
519
558
520
559
# A final note
521
560
0 commit comments