]>
Commit | Line | Data |
---|---|---|
8bb4bdeb XL |
1 | # Macros By Example |
2 | ||
13cf67c4 XL |
3 | > **<sup>Syntax</sup>**\ |
4 | > _MacroRulesDefinition_ :\ | |
5 | > `macro_rules` `!` [IDENTIFIER] _MacroRulesDef_ | |
6 | > | |
7 | > _MacroRulesDef_ :\ | |
8 | > `(` _MacroRules_ `)` `;`\ | |
9 | > | `[` _MacroRules_ `]` `;`\ | |
10 | > | `{` _MacroRules_ `}` | |
11 | > | |
12 | > _MacroRules_ :\ | |
13 | > _MacroRule_ ( `;` _MacroRule_ )<sup>\*</sup> `;`<sup>?</sup> | |
14 | > | |
15 | > _MacroRule_ :\ | |
16 | > _MacroMatcher_ `=>` _MacroTranscriber_ | |
17 | > | |
18 | > _MacroMatcher_ :\ | |
19 | > `(` _MacroMatch_<sup>\*</sup> `)`\ | |
20 | > | `[` _MacroMatch_<sup>\*</sup> `]`\ | |
21 | > | `{` _MacroMatch_<sup>\*</sup> `}` | |
22 | > | |
23 | > _MacroMatch_ :\ | |
24 | > [_Token_]<sub>_except $ and delimiters_</sub>\ | |
25 | > | _MacroMatcher_\ | |
26 | > | `$` [IDENTIFIER] `:` _MacroFragSpec_\ | |
532ac7d7 | 27 | > | `$` `(` _MacroMatch_<sup>+</sup> `)` _MacroRepSep_<sup>?</sup> _MacroRepOp_ |
13cf67c4 XL |
28 | > |
29 | > _MacroFragSpec_ :\ | |
532ac7d7 | 30 | > `block` | `expr` | `ident` | `item` | `lifetime` | `literal`\ |
17df50a5 | 31 | > | `meta` | `pat` | `pat_param` | `path` | `stmt` | `tt` | `ty` | `vis` |
13cf67c4 XL |
32 | > |
33 | > _MacroRepSep_ :\ | |
532ac7d7 | 34 | > [_Token_]<sub>_except delimiters and repetition operators_</sub> |
13cf67c4 | 35 | > |
dc9dc135 XL |
36 | > _MacroRepOp_ :\ |
37 | > `*` | `+` | `?` | |
13cf67c4 XL |
38 | > |
39 | > _MacroTranscriber_ :\ | |
40 | > [_DelimTokenTree_] | |
41 | ||
8bb4bdeb XL |
42 | `macro_rules` allows users to define syntax extension in a declarative way. We |
43 | call such extensions "macros by example" or simply "macros". | |
44 | ||
532ac7d7 XL |
45 | Each macro by example has a name, and one or more _rules_. Each rule has two |
46 | parts: a _matcher_, describing the syntax that it matches, and a _transcriber_, | |
47 | describing the syntax that will replace a successfully matched invocation. Both | |
48 | the matcher and the transcriber must be surrounded by delimiters. Macros can | |
49 | expand to expressions, statements, items (including traits, impls, and foreign | |
50 | items), types, or patterns. | |
51 | ||
52 | ## Transcribing | |
53 | ||
54 | When a macro is invoked, the macro expander looks up macro invocations by name, | |
55 | 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 | |
58 | parse the macro invocation one token at a time, then it is an error. In the | |
59 | following example, the compiler does not look ahead past the identifier to see | |
60 | if the following token is a `)`, even though that would allow it to parse the | |
61 | invocation unambiguously: | |
62 | ||
63 | ```rust,compile_fail | |
64 | macro_rules! ambiguity { | |
65 | ($($i:ident)* $j:ident) => { }; | |
66 | } | |
67 | ||
68 | ambiguity!(error); // Error: local ambiguity | |
69 | ``` | |
70 | ||
71 | In both the matcher and the transcriber, the `$` token is used to invoke special | |
72 | behaviours from the macro engine (described below in [Metavariables] and | |
73 | [Repetitions]). Tokens that aren't part of such an invocation are matched and | |
74 | transcribed literally, with one exception. The exception is that the outer | |
75 | delimiters for the matcher will match any pair of delimiters. Thus, for | |
76 | instance, the matcher `(())` will match `{()}` but not `{{}}`. The character | |
77 | `$` cannot be matched or transcribed literally. | |
78 | ||
79 | When forwarding a matched fragment to another macro-by-example, matchers in | |
80 | the second macro will see an opaque AST of the fragment type. The second macro | |
81 | can't use literal tokens to match the fragments in the matcher, only a | |
82 | fragment specifier of the same type. The `ident`, `lifetime`, and `tt` | |
83 | fragment types are an exception, and *can* be matched by literal tokens. The | |
84 | following illustrates this restriction: | |
85 | ||
86 | ```rust,compile_fail | |
87 | macro_rules! foo { | |
88 | ($l:expr) => { bar!($l); } | |
89 | // ERROR: ^^ no rules expected this token in macro call | |
90 | } | |
91 | ||
92 | macro_rules! bar { | |
93 | (3) => {} | |
94 | } | |
95 | ||
96 | foo!(3); | |
97 | ``` | |
98 | ||
99 | The following illustrates how tokens can be directly matched after matching a | |
100 | `tt` fragment: | |
101 | ||
102 | ```rust | |
103 | // compiles OK | |
104 | macro_rules! foo { | |
105 | ($l:tt) => { bar!($l); } | |
106 | } | |
107 | ||
108 | macro_rules! bar { | |
109 | (3) => {} | |
110 | } | |
111 | ||
112 | foo!(3); | |
113 | ``` | |
114 | ||
115 | ## Metavariables | |
116 | ||
117 | In the matcher, `$` _name_ `:` _fragment-specifier_ matches a Rust syntax | |
118 | fragment of the kind specified and binds it to the metavariable `$`_name_. Valid | |
119 | fragment specifiers are: | |
120 | ||
121 | * `item`: an [_Item_] | |
122 | * `block`: a [_BlockExpression_] | |
123 | * `stmt`: a [_Statement_] without the trailing semicolon (except for item | |
124 | statements that require semicolons) | |
17df50a5 XL |
125 | * `pat_param`: a [_PatternNoTopAlt_] |
126 | * `pat`: equivalent to `pat_param` | |
532ac7d7 XL |
127 | * `expr`: an [_Expression_] |
128 | * `ty`: a [_Type_] | |
129 | * `ident`: an [IDENTIFIER_OR_KEYWORD] | |
130 | * `path`: a [_TypePath_] style path | |
131 | * `tt`: a [_TokenTree_] (a single [token] or tokens in matching delimiters `()`, `[]`, or `{}`) | |
e74abb32 | 132 | * `meta`: an [_Attr_], the contents of an attribute |
532ac7d7 XL |
133 | * `lifetime`: a [LIFETIME_TOKEN] |
134 | * `vis`: a possibly empty [_Visibility_] qualifier | |
135 | * `literal`: matches `-`<sup>?</sup>[_LiteralExpression_] | |
136 | ||
137 | In the transcriber, metavariables are referred to simply by `$`_name_, since | |
138 | the fragment kind is specified in the matcher. Metavariables are replaced with | |
139 | the syntax element that matched them. The keyword metavariable `$crate` can be | |
140 | used to refer to the current crate; see [Hygiene] below. Metavariables can be | |
141 | transcribed more than once or not at all. | |
142 | ||
143 | ## Repetitions | |
144 | ||
145 | In both the matcher and transcriber, repetitions are indicated by placing the | |
146 | tokens to be repeated inside `$(`…`)`, followed by a repetition operator, | |
147 | optionally with a separator token between. The separator token can be any token | |
148 | other than a delimiter or one of the repetition operators, but `;` and `,` are | |
149 | the most common. For instance, `$( $i:ident ),*` represents any number of | |
150 | identifiers separated by commas. Nested repetitions are permitted. | |
151 | ||
152 | The repetition operators are: | |
153 | ||
154 | - `*` — indicates any number of repetitions. | |
155 | - `+` — indicates any number but at least one. | |
156 | - `?` — indicates an optional fragment with zero or one occurrences. | |
157 | ||
158 | Since `?` represents at most one occurrence, it cannot be used with a | |
159 | separator. | |
160 | ||
161 | The repeated fragment both matches and transcribes to the specified number of | |
162 | the fragment, separated by the separator token. Metavariables are matched to | |
163 | every repetition of their corresponding fragment. For instance, the `$( $i:ident | |
164 | ),*` example above matches `$i` to all of the identifiers in the list. | |
165 | ||
166 | During transcription, additional restrictions apply to repetitions so that the | |
167 | compiler knows how to expand them properly: | |
168 | ||
169 | 1. A metavariable must appear in exactly the same number, kind, and nesting | |
170 | order of repetitions in the transcriber as it did in the matcher. So for the | |
171 | matcher `$( $i:ident ),*`, the transcribers `=> { $i }`, | |
172 | `=> { $( $( $i)* )* }`, and `=> { $( $i )+ }` are all illegal, but | |
173 | `=> { $( $i );* }` is correct and replaces a comma-separated list of | |
174 | identifiers with a semicolon-separated list. | |
f035d41b XL |
175 | 2. Each repetition in the transcriber must contain at least one metavariable to |
176 | decide how many times to expand it. If multiple metavariables appear in the | |
177 | same repetition, they must be bound to the same number of fragments. For | |
cdc7bbd5 | 178 | instance, `( $( $i:ident ),* ; $( $j:ident ),* ) => (( $( ($i,$j) ),* ))` must |
f035d41b | 179 | bind the same number of `$i` fragments as `$j` fragments. This means that |
cdc7bbd5 | 180 | invoking the macro with `(a, b, c; d, e, f)` is legal and expands to |
f035d41b XL |
181 | `((a,d), (b,e), (c,f))`, but `(a, b, c; d, e)` is illegal because it does |
182 | not have the same number. This requirement applies to every layer of nested | |
183 | repetitions. | |
532ac7d7 | 184 | |
532ac7d7 XL |
185 | ## Scoping, Exporting, and Importing |
186 | ||
f035d41b XL |
187 | For historical reasons, the scoping of macros by example does not work entirely |
188 | like items. Macros have two forms of scope: textual scope, and path-based scope. | |
532ac7d7 XL |
189 | Textual scope is based on the order that things appear in source files, or even |
190 | across multiple files, and is the default scoping. It is explained further below. | |
191 | Path-based scope works exactly the same way that item scoping does. The scoping, | |
192 | exporting, and importing of macros is controlled largely by attributes. | |
193 | ||
194 | When a macro is invoked by an unqualified identifier (not part of a multi-part | |
195 | path), it is first looked up in textual scoping. If this does not yield any | |
196 | results, then it is looked up in path-based scoping. If the macro's name is | |
197 | qualified with a path, then it is only looked up in path-based scoping. | |
198 | ||
60c5eb7d | 199 | <!-- ignore: requires external crates --> |
532ac7d7 XL |
200 | ```rust,ignore |
201 | use lazy_static::lazy_static; // Path-based import. | |
202 | ||
203 | macro_rules! lazy_static { // Textual definition. | |
204 | (lazy) => {}; | |
205 | } | |
206 | ||
207 | lazy_static!{lazy} // Textual lookup finds our macro first. | |
208 | self::lazy_static!{} // Path-based lookup ignores our macro, finds imported one. | |
209 | ``` | |
210 | ||
211 | ### Textual Scope | |
212 | ||
213 | Textual scope is based largely on the order that things appear in source files, | |
214 | and works similarly to the scope of local variables declared with `let` except | |
215 | it also applies at the module level. When `macro_rules!` is used to define a | |
216 | macro, the macro enters the scope after the definition (note that it can still | |
217 | be used recursively, since names are looked up from the invocation site), up | |
218 | until its surrounding scope, typically a module, is closed. This can enter child | |
219 | modules and even span across multiple files: | |
220 | ||
60c5eb7d | 221 | <!-- ignore: requires external modules --> |
532ac7d7 XL |
222 | ```rust,ignore |
223 | //// src/lib.rs | |
224 | mod has_macro { | |
225 | // m!{} // Error: m is not in scope. | |
226 | ||
227 | macro_rules! m { | |
228 | () => {}; | |
229 | } | |
230 | m!{} // OK: appears after declaration of m. | |
231 | ||
232 | mod uses_macro; | |
233 | } | |
234 | ||
235 | // m!{} // Error: m is not in scope. | |
236 | ||
237 | //// src/has_macro/uses_macro.rs | |
238 | ||
239 | m!{} // OK: appears after declaration of m in src/lib.rs | |
240 | ``` | |
241 | ||
242 | It is not an error to define a macro multiple times; the most recent declaration | |
243 | will shadow the previous one unless it has gone out of scope. | |
244 | ||
245 | ```rust | |
246 | macro_rules! m { | |
247 | (1) => {}; | |
248 | } | |
249 | ||
250 | m!(1); | |
251 | ||
252 | mod inner { | |
253 | m!(1); | |
254 | ||
255 | macro_rules! m { | |
256 | (2) => {}; | |
257 | } | |
258 | // m!(1); // Error: no rule matches '1' | |
259 | m!(2); | |
260 | ||
261 | macro_rules! m { | |
262 | (3) => {}; | |
263 | } | |
264 | m!(3); | |
265 | } | |
266 | ||
267 | m!(1); | |
268 | ``` | |
13cf67c4 | 269 | |
532ac7d7 XL |
270 | Macros can be declared and used locally inside functions as well, and work |
271 | similarly: | |
272 | ||
273 | ```rust | |
274 | fn foo() { | |
275 | // m!(); // Error: m is not in scope. | |
276 | macro_rules! m { | |
277 | () => {}; | |
278 | } | |
279 | m!(); | |
280 | } | |
281 | ||
282 | ||
283 | // m!(); // Error: m is not in scope. | |
284 | ``` | |
285 | ||
286 | ### The `macro_use` attribute | |
287 | ||
288 | The *`macro_use` attribute* has two purposes. First, it can be used to make a | |
289 | module's macro scope not end when the module is closed, by applying it to a | |
290 | module: | |
291 | ||
292 | ```rust | |
293 | #[macro_use] | |
294 | mod inner { | |
295 | macro_rules! m { | |
296 | () => {}; | |
297 | } | |
298 | } | |
299 | ||
300 | m!(); | |
301 | ``` | |
302 | ||
303 | Second, it can be used to import macros from another crate, by attaching it to | |
304 | an `extern crate` declaration appearing in the crate's root module. Macros | |
5869c6ff | 305 | imported this way are imported into the [`macro_use` prelude], not textually, |
532ac7d7 XL |
306 | which means that they can be shadowed by any other name. While macros imported |
307 | by `#[macro_use]` can be used before the import statement, in case of a | |
308 | conflict, the last macro imported wins. Optionally, a list of macros to import | |
309 | can be specified using the [_MetaListIdents_] syntax; this is not supported | |
310 | when `#[macro_use]` is applied to a module. | |
311 | ||
60c5eb7d | 312 | <!-- ignore: requires external crates --> |
532ac7d7 XL |
313 | ```rust,ignore |
314 | #[macro_use(lazy_static)] // Or #[macro_use] to import all macros. | |
315 | extern crate lazy_static; | |
316 | ||
dc9dc135 | 317 | lazy_static!{} |
532ac7d7 XL |
318 | // self::lazy_static!{} // Error: lazy_static is not defined in `self` |
319 | ``` | |
320 | ||
321 | Macros to be imported with `#[macro_use]` must be exported with | |
322 | `#[macro_export]`, which is described below. | |
323 | ||
324 | ### Path-Based Scope | |
325 | ||
326 | By default, a macro has no path-based scope. However, if it has the | |
327 | `#[macro_export]` attribute, then it is declared in the crate root scope and can | |
328 | be referred to normally as such: | |
329 | ||
330 | ```rust | |
331 | self::m!(); | |
332 | m!(); // OK: Path-based lookup finds m in the current module. | |
333 | ||
334 | mod inner { | |
335 | super::m!(); | |
336 | crate::m!(); | |
337 | } | |
338 | ||
339 | mod mac { | |
340 | #[macro_export] | |
341 | macro_rules! m { | |
342 | () => {}; | |
343 | } | |
344 | } | |
345 | ``` | |
346 | ||
347 | Macros labeled with `#[macro_export]` are always `pub` and can be referred to | |
348 | by other crates, either by path or by `#[macro_use]` as described above. | |
349 | ||
350 | ## Hygiene | |
351 | ||
352 | By default, all identifiers referred to in a macro are expanded as-is, and are | |
353 | looked up at the macro's invocation site. This can lead to issues if a macro | |
354 | refers to an item or macro which isn't in scope at the invocation site. To | |
355 | alleviate this, the `$crate` metavariable can be used at the start of a path to | |
356 | force lookup to occur inside the crate defining the macro. | |
357 | ||
60c5eb7d | 358 | <!-- ignore: requires external crates --> |
532ac7d7 XL |
359 | ```rust,ignore |
360 | //// Definitions in the `helper_macro` crate. | |
361 | #[macro_export] | |
362 | macro_rules! helped { | |
363 | // () => { helper!() } // This might lead to an error due to 'helper' not being in scope. | |
364 | () => { $crate::helper!() } | |
365 | } | |
366 | ||
367 | #[macro_export] | |
368 | macro_rules! helper { | |
369 | () => { () } | |
370 | } | |
371 | ||
372 | //// Usage in another crate. | |
373 | // Note that `helper_macro::helper` is not imported! | |
374 | use helper_macro::helped; | |
375 | ||
376 | fn unit() { | |
377 | helped!(); | |
378 | } | |
379 | ``` | |
380 | ||
381 | Note that, because `$crate` refers to the current crate, it must be used with a | |
382 | fully qualified module path when referring to non-macro items: | |
383 | ||
384 | ```rust | |
385 | pub mod inner { | |
386 | #[macro_export] | |
387 | macro_rules! call_foo { | |
388 | () => { $crate::inner::foo() }; | |
389 | } | |
390 | ||
391 | pub fn foo() {} | |
392 | } | |
393 | ``` | |
394 | ||
395 | Additionally, even though `$crate` allows a macro to refer to items within its | |
396 | own crate when expanding, its use has no effect on visibility. An item or macro | |
397 | referred to must still be visible from the invocation site. In the following | |
398 | example, any attempt to invoke `call_foo!()` from outside its crate will fail | |
399 | because `foo()` is not public. | |
400 | ||
401 | ```rust | |
402 | #[macro_export] | |
403 | macro_rules! call_foo { | |
404 | () => { $crate::foo() }; | |
405 | } | |
406 | ||
407 | fn foo() {} | |
408 | ``` | |
409 | ||
410 | > **Version & Edition Differences**: Prior to Rust 1.30, `$crate` and | |
411 | > `local_inner_macros` (below) were unsupported. They were added alongside | |
412 | > path-based imports of macros (described above), to ensure that helper macros | |
413 | > did not need to be manually imported by users of a macro-exporting crate. | |
414 | > Crates written for earlier versions of Rust that use helper macros need to be | |
415 | > modified to use `$crate` or `local_inner_macros` to work well with path-based | |
416 | > imports. | |
417 | ||
418 | When a macro is exported, the `#[macro_export]` attribute can have the | |
419 | `local_inner_macros` keyword added to automatically prefix all contained macro | |
420 | invocations with `$crate::`. This is intended primarily as a tool to migrate | |
421 | code written before `$crate` was added to the language to work with Rust 2018's | |
422 | path-based imports of macros. Its use is discouraged in new code. | |
423 | ||
424 | ```rust | |
425 | #[macro_export(local_inner_macros)] | |
426 | macro_rules! helped { | |
427 | () => { helper!() } // Automatically converted to $crate::helper!(). | |
428 | } | |
429 | ||
430 | #[macro_export] | |
431 | macro_rules! helper { | |
432 | () => { () } | |
433 | } | |
434 | ``` | |
435 | ||
436 | ## Follow-set Ambiguity Restrictions | |
437 | ||
438 | The parser used by the macro system is reasonably powerful, but it is limited in | |
439 | order to prevent ambiguity in current or future versions of the language. In | |
440 | particular, in addition to the rule about ambiguous expansions, a nonterminal | |
441 | matched by a metavariable must be followed by a token which has been decided can | |
442 | be safely used after that kind of match. | |
443 | ||
444 | As an example, a macro matcher like `$i:expr [ , ]` could in theory be accepted | |
445 | in Rust today, since `[,]` cannot be part of a legal expression and therefore | |
446 | the parse would always be unambiguous. However, because `[` can start trailing | |
447 | expressions, `[` is not a character which can safely be ruled out as coming | |
448 | after an expression. If `[,]` were accepted in a later version of Rust, this | |
449 | matcher would become ambiguous or would misparse, breaking working code. | |
450 | Matchers like `$i:expr,` or `$i:expr;` would be legal, however, because `,` and | |
451 | `;` are legal expression separators. The specific rules are: | |
452 | ||
453 | * `expr` and `stmt` may only be followed by one of: `=>`, `,`, or `;`. | |
17df50a5 | 454 | * `pat` and `pat_param` may only be followed by one of: `=>`, `,`, `=`, `|`, `if`, or `in`. |
532ac7d7 XL |
455 | * `path` and `ty` may only be followed by one of: `=>`, `,`, `=`, `|`, `;`, |
456 | `:`, `>`, `>>`, `[`, `{`, `as`, `where`, or a macro variable of `block` | |
457 | fragment specifier. | |
458 | * `vis` may only be followed by one of: `,`, an identifier other than a | |
459 | non-raw `priv`, any token that can begin a type, or a metavariable with a | |
460 | `ident`, `ty`, or `path` fragment specifier. | |
461 | * All other fragment specifiers have no restrictions. | |
462 | ||
463 | When repetitions are involved, then the rules apply to every possible number of | |
464 | expansions, taking separators into account. This means: | |
465 | ||
466 | * If the repetition includes a separator, that separator must be able to | |
467 | follow the contents of the repetition. | |
468 | * If the repetition can repeat multiple times (`*` or `+`), then the contents | |
469 | must be able to follow themselves. | |
470 | * The contents of the repetition must be able to follow whatever comes | |
471 | before, and whatever comes after must be able to follow the contents of the | |
472 | repetition. | |
473 | * If the repetition can match zero times (`*` or `?`), then whatever comes | |
474 | after must be able to follow whatever comes before. | |
475 | ||
476 | ||
477 | For more detail, see the [formal specification]. | |
478 | ||
479 | [Hygiene]: #hygiene | |
416331ca XL |
480 | [IDENTIFIER]: identifiers.md |
481 | [IDENTIFIER_OR_KEYWORD]: identifiers.md | |
482 | [LIFETIME_TOKEN]: tokens.md#lifetimes-and-loop-labels | |
532ac7d7 XL |
483 | [Metavariables]: #metavariables |
484 | [Repetitions]: #repetitions | |
e74abb32 | 485 | [_Attr_]: attributes.md |
416331ca XL |
486 | [_BlockExpression_]: expressions/block-expr.md |
487 | [_DelimTokenTree_]: macros.md | |
488 | [_Expression_]: expressions.md | |
489 | [_Item_]: items.md | |
490 | [_LiteralExpression_]: expressions/literal-expr.md | |
416331ca | 491 | [_MetaListIdents_]: attributes.md#meta-item-attribute-syntax |
cdc7bbd5 | 492 | [_PatternNoTopAlt_]: patterns.md |
416331ca XL |
493 | [_Statement_]: statements.md |
494 | [_TokenTree_]: macros.md#macro-invocation | |
495 | [_Token_]: tokens.md | |
496 | [_TypePath_]: paths.md#paths-in-types | |
497 | [_Type_]: types.md#type-expressions | |
498 | [_Visibility_]: visibility-and-privacy.md | |
499 | [formal specification]: macro-ambiguity.md | |
500 | [token]: tokens.md | |
5869c6ff | 501 | [`macro_use` prelude]: names/preludes.md#macro_use-prelude |