1
1
# Macros By Example
2
2
3
+ r[ macro.decl]
4
+
5
+ r[ macro.decl.syntax]
3
6
> ** <sup >Syntax</sup >** \
4
7
> _ MacroRulesDefinition_ :\
5
8
>   ;  ; ` macro_rules ` ` ! ` [ IDENTIFIER] _ MacroRulesDef_
39
42
> _ MacroTranscriber_ :\
40
43
>   ;  ; [ _ DelimTokenTree_ ]
41
44
45
+ r[ macro.decl.intro]
42
46
` macro_rules ` allows users to define syntax extension in a declarative way. We
43
47
call such extensions "macros by example" or simply "macros".
44
48
@@ -51,10 +55,15 @@ items), types, or patterns.
51
55
52
56
## Transcribing
53
57
58
+ r[ macro.decl.transcription]
59
+
60
+ r[ macro.decl.transcription.intro]
54
61
When a macro is invoked, the macro expander looks up macro invocations by name,
55
62
and tries each macro rule in turn. It transcribes the first successful match; if
56
- this results in an error, then future matches are not tried. When matching, no
57
- lookahead is performed; if the compiler cannot unambiguously determine how to
63
+ this results in an error, then future matches are not tried.
64
+
65
+ r[ macro.decl.transcription.lookahead]
66
+ When matching, no lookahead is performed; if the compiler cannot unambiguously determine how to
58
67
parse the macro invocation one token at a time, then it is an error. In the
59
68
following example, the compiler does not look ahead past the identifier to see
60
69
if the following token is a ` ) ` , even though that would allow it to parse the
@@ -68,6 +77,7 @@ macro_rules! ambiguity {
68
77
ambiguity!(error); // Error: local ambiguity
69
78
```
70
79
80
+ r[ macro.decl.transcription.syntax]
71
81
In both the matcher and the transcriber, the ` $ ` token is used to invoke special
72
82
behaviours from the macro engine (described below in [ Metavariables] and
73
83
[ Repetitions] ). Tokens that aren't part of such an invocation are matched and
@@ -78,6 +88,8 @@ instance, the matcher `(())` will match `{()}` but not `{{}}`. The character
78
88
79
89
### Forwarding a matched fragment
80
90
91
+ r[ macro.decl.transcription.fragment]
92
+
81
93
When forwarding a matched fragment to another macro-by-example, matchers in
82
94
the second macro will see an opaque AST of the fragment type. The second macro
83
95
can't use literal tokens to match the fragments in the matcher, only a
@@ -116,9 +128,14 @@ foo!(3);
116
128
117
129
## Metavariables
118
130
131
+ r[ macro.decl.meta]
132
+
133
+ r[ macro.decl.meta.intro]
119
134
In the matcher, ` $ ` _ name_ ` : ` _ fragment-specifier_ matches a Rust syntax
120
- fragment of the kind specified and binds it to the metavariable ` $ ` _ name_ . Valid
121
- fragment specifiers are:
135
+ fragment of the kind specified and binds it to the metavariable ` $ ` _ name_ .
136
+
137
+ r[ macro.decl.meta.specifier]
138
+ Valid fragment specifiers are:
122
139
123
140
* ` item ` : an [ _ Item_ ]
124
141
* ` block ` : a [ _ BlockExpression_ ]
@@ -136,18 +153,23 @@ fragment specifiers are:
136
153
* ` vis ` : a possibly empty [ _ Visibility_ ] qualifier
137
154
* ` literal ` : matches ` - ` <sup >?</sup >[ _ LiteralExpression_ ]
138
155
156
+ r[ macro.decl.meta.transcription]
139
157
In the transcriber, metavariables are referred to simply by ` $ ` _ name_ , since
140
158
the fragment kind is specified in the matcher. Metavariables are replaced with
141
- the syntax element that matched them. The keyword metavariable ` $crate ` can be
142
- used to refer to the current crate; see [ Hygiene] below. Metavariables can be
159
+ the syntax element that matched them.
160
+
161
+ r[ macro.decl.meta.dollar-crate]
162
+ The keyword metavariable ` $crate ` can be used to refer to the current crate; see [ Hygiene] below. Metavariables can be
143
163
transcribed more than once or not at all.
144
164
165
+ r[ macro.decl.meta.expr-underscore]
145
166
For reasons of backwards compatibility, though ` _ ` [ is also an
146
167
expression] [ _UnderscoreExpression_ ] , a standalone underscore is not matched by
147
168
the ` expr ` fragment specifier. However, ` _ ` is matched by the ` expr ` fragment
148
169
specifier when it appears as a subexpression.
149
170
For the same reason, a standalone [ const block] is not matched but it is matched when appearing as a subexpression.
150
171
172
+ r[ macro.decl.meta.edition2021]
151
173
> ** Edition differences** : Starting with the 2021 edition, ` pat ` fragment-specifiers match top-level or-patterns (that is, they accept [ _ Pattern_ ] ).
152
174
>
153
175
> Before the 2021 edition, they match exactly the same fragments as ` pat_param ` (that is, they accept [ _ PatternNoTopAlt_ ] ).
@@ -156,22 +178,31 @@ For the same reason, a standalone [const block] is not matched but it is matched
156
178
157
179
## Repetitions
158
180
181
+ r[ macro.decl.repetition]
182
+
183
+ r[ macro.decl.repetition.intro]
159
184
In both the matcher and transcriber, repetitions are indicated by placing the
160
185
tokens to be repeated inside ` $( ` …` ) ` , followed by a repetition operator,
161
- optionally with a separator token between. The separator token can be any token
186
+ optionally with a separator token between.
187
+
188
+ r[ macro.decl.repetition.separator]
189
+ The separator token can be any token
162
190
other than a delimiter or one of the repetition operators, but ` ; ` and ` , ` are
163
191
the most common. For instance, ` $( $i:ident ),* ` represents any number of
164
192
identifiers separated by commas. Nested repetitions are permitted.
165
193
194
+ r[ macro.decl.repetition.operators]
166
195
The repetition operators are:
167
196
168
197
- ` * ` --- indicates any number of repetitions.
169
198
- ` + ` --- indicates any number but at least one.
170
199
- ` ? ` --- indicates an optional fragment with zero or one occurrence.
171
200
201
+ r[ macro.decl.repetition.optional-restriction]
172
202
Since ` ? ` represents at most one occurrence, it cannot be used with a
173
203
separator.
174
204
205
+ r[ macro.decl.repetition.fragment]
175
206
The repeated fragment both matches and transcribes to the specified number of
176
207
the fragment, separated by the separator token. Metavariables are matched to
177
208
every repetition of their corresponding fragment. For instance, the `$( $i: ident
@@ -198,13 +229,17 @@ compiler knows how to expand them properly:
198
229
199
230
## Scoping, Exporting, and Importing
200
231
232
+ r[ macro.decl.scope]
233
+
234
+ r[ macro.decl.scope.intro]
201
235
For historical reasons, the scoping of macros by example does not work entirely
202
236
like items. Macros have two forms of scope: textual scope, and path-based scope.
203
237
Textual scope is based on the order that things appear in source files, or even
204
238
across multiple files, and is the default scoping. It is explained further below.
205
239
Path-based scope works exactly the same way that item scoping does. The scoping,
206
240
exporting, and importing of macros is controlled largely by attributes.
207
241
242
+ r[ macro.decl.scope.unqualified]
208
243
When a macro is invoked by an unqualified identifier (not part of a multi-part
209
244
path), it is first looked up in textual scoping. If this does not yield any
210
245
results, then it is looked up in path-based scoping. If the macro's name is
@@ -224,6 +259,9 @@ self::lazy_static!{} // Path-based lookup ignores our macro, finds imported one.
224
259
225
260
### Textual Scope
226
261
262
+ r[ macro.decl.scope.textual]
263
+
264
+ r[ macro.decl.scope.textual.intro]
227
265
Textual scope is based largely on the order that things appear in source files,
228
266
and works similarly to the scope of local variables declared with ` let ` except
229
267
it also applies at the module level. When ` macro_rules! ` is used to define a
@@ -253,6 +291,7 @@ mod has_macro {
253
291
m!{} // OK: appears after declaration of m in src/lib.rs
254
292
```
255
293
294
+ r[ macro.decl.scope.textual.shadow]
256
295
It is not an error to define a macro multiple times; the most recent declaration
257
296
will shadow the previous one unless it has gone out of scope.
258
297
@@ -299,6 +338,9 @@ fn foo() {
299
338
300
339
### The ` macro_use ` attribute
301
340
341
+ r[ macro.decl.scope.macro_use]
342
+
343
+ r[ macro.decl.scope.macro_use.mod-decl]
302
344
The * ` macro_use ` attribute* has two purposes. First, it can be used to make a
303
345
module's macro scope not end when the module is closed, by applying it to a
304
346
module:
@@ -314,6 +356,7 @@ mod inner {
314
356
m! ();
315
357
```
316
358
359
+ r[ macro.decl.scope.macro_use.prelude]
317
360
Second, it can be used to import macros from another crate, by attaching it to
318
361
an ` extern crate ` declaration appearing in the crate's root module. Macros
319
362
imported this way are imported into the [ ` macro_use ` prelude] , not textually,
@@ -332,11 +375,15 @@ lazy_static!{}
332
375
// self::lazy_static!{} // Error: lazy_static is not defined in `self`
333
376
```
334
377
378
+ r[ macro.decl.scope.macro_use.export]
335
379
Macros to be imported with ` #[macro_use] ` must be exported with
336
380
` #[macro_export] ` , which is described below.
337
381
338
382
### Path-Based Scope
339
383
384
+ r[ macro.decl.scope.path]
385
+
386
+ r[ macro.decl.scope.path.intro]
340
387
By default, a macro has no path-based scope. However, if it has the
341
388
` #[macro_export] ` attribute, then it is declared in the crate root scope and can
342
389
be referred to normally as such:
@@ -358,11 +405,15 @@ mod mac {
358
405
}
359
406
```
360
407
408
+ r[ macro.decl.scope.path.export]
361
409
Macros labeled with ` #[macro_export] ` are always ` pub ` and can be referred to
362
410
by other crates, either by path or by ` #[macro_use] ` as described above.
363
411
364
412
## Hygiene
365
413
414
+ r[ macro.decl.hygiene]
415
+
416
+ r[ macreo.decl.hygiene.intro]
366
417
By default, all identifiers referred to in a macro are expanded as-is, and are
367
418
looked up at the macro's invocation site. This can lead to issues if a macro
368
419
refers to an item or macro which isn't in scope at the invocation site. To
@@ -406,6 +457,7 @@ pub mod inner {
406
457
}
407
458
```
408
459
460
+ r[ macro.decl.hygiene.vis]
409
461
Additionally, even though ` $crate ` allows a macro to refer to items within its
410
462
own crate when expanding, its use has no effect on visibility. An item or macro
411
463
referred to must still be visible from the invocation site. In the following
@@ -429,6 +481,7 @@ fn foo() {}
429
481
> modified to use ` $crate ` or ` local_inner_macros ` to work well with path-based
430
482
> imports.
431
483
484
+ r[ macro.decl.hygeine.local_inner_macros]
432
485
When a macro is exported, the ` #[macro_export] ` attribute can have the
433
486
` local_inner_macros ` keyword added to automatically prefix all contained macro
434
487
invocations with ` $crate:: ` . This is intended primarily as a tool to migrate
@@ -449,9 +502,15 @@ macro_rules! helper {
449
502
450
503
## Follow-set Ambiguity Restrictions
451
504
505
+ r[ macro.decl.follow-set]
506
+
507
+ r[ macro.decl.follow-set.intro]
452
508
The parser used by the macro system is reasonably powerful, but it is limited in
453
- order to prevent ambiguity in current or future versions of the language. In
454
- particular, in addition to the rule about ambiguous expansions, a nonterminal
509
+ order to prevent ambiguity in current or future versions of the language.
510
+
511
+
512
+ r[ macro.decl.follow-set.token-restriction]
513
+ In particular, in addition to the rule about ambiguous expansions, a nonterminal
455
514
matched by a metavariable must be followed by a token which has been decided can
456
515
be safely used after that kind of match.
457
516
@@ -464,19 +523,32 @@ matcher would become ambiguous or would misparse, breaking working code.
464
523
Matchers like ` $i:expr, ` or ` $i:expr; ` would be legal, however, because ` , ` and
465
524
` ; ` are legal expression separators. The specific rules are:
466
525
526
+ r[ macro.decl.follow-set.token-expr-stmt]
467
527
* ` expr ` and ` stmt ` may only be followed by one of: ` => ` , ` , ` , or ` ; ` .
528
+
529
+ r[ macro.decl.follow-set.token-pat_param]
468
530
* ` pat_param ` may only be followed by one of: ` => ` , ` , ` , ` = ` , ` | ` , ` if ` , or ` in ` .
531
+
532
+ r[ macro.decl.follow-set.token-pat]
469
533
* ` pat ` may only be followed by one of: ` => ` , ` , ` , ` = ` , ` if ` , or ` in ` .
534
+
535
+ r[ macro.decl.follow-set.token-path-ty]
470
536
* ` path ` and ` ty ` may only be followed by one of: ` => ` , ` , ` , ` = ` , ` | ` , ` ; ` ,
471
537
` : ` , ` > ` , ` >> ` , ` [ ` , ` { ` , ` as ` , ` where ` , or a macro variable of ` block `
472
538
fragment specifier.
539
+
540
+ r[ macro.decl.follow-set.token-vis]
473
541
* ` vis ` may only be followed by one of: ` , ` , an identifier other than a
474
542
non-raw ` priv ` , any token that can begin a type, or a metavariable with a
475
543
` ident ` , ` ty ` , or ` path ` fragment specifier.
544
+
545
+ r[ macro.decl.follow-set.token-other]
476
546
* All other fragment specifiers have no restrictions.
477
547
548
+ r[ macro.decl.follow-set.edition2021]
478
549
> ** Edition differences** : Before the 2021 edition, ` pat ` may also be followed by ` | ` .
479
550
551
+ r[ macro.decl.follow-set.repetition]
480
552
When repetitions are involved, then the rules apply to every possible number of
481
553
expansions, taking separators into account. This means:
482
554
0 commit comments