]> git.proxmox.com Git - rustc.git/blame - src/doc/reference/src/macros-by-example.md
New upstream version 1.54.0+dfsg1
[rustc.git] / src / doc / reference / src / macros-by-example.md
CommitLineData
8bb4bdeb
XL
1# Macros By Example
2
13cf67c4
XL
3> **<sup>Syntax</sup>**\
4> _MacroRulesDefinition_ :\
5> &nbsp;&nbsp; `macro_rules` `!` [IDENTIFIER] _MacroRulesDef_
6>
7> _MacroRulesDef_ :\
8> &nbsp;&nbsp; &nbsp;&nbsp; `(` _MacroRules_ `)` `;`\
9> &nbsp;&nbsp; | `[` _MacroRules_ `]` `;`\
10> &nbsp;&nbsp; | `{` _MacroRules_ `}`
11>
12> _MacroRules_ :\
13> &nbsp;&nbsp; _MacroRule_ ( `;` _MacroRule_ )<sup>\*</sup> `;`<sup>?</sup>
14>
15> _MacroRule_ :\
16> &nbsp;&nbsp; _MacroMatcher_ `=>` _MacroTranscriber_
17>
18> _MacroMatcher_ :\
19> &nbsp;&nbsp; &nbsp;&nbsp; `(` _MacroMatch_<sup>\*</sup> `)`\
20> &nbsp;&nbsp; | `[` _MacroMatch_<sup>\*</sup> `]`\
21> &nbsp;&nbsp; | `{` _MacroMatch_<sup>\*</sup> `}`
22>
23> _MacroMatch_ :\
24> &nbsp;&nbsp; &nbsp;&nbsp; [_Token_]<sub>_except $ and delimiters_</sub>\
25> &nbsp;&nbsp; | _MacroMatcher_\
26> &nbsp;&nbsp; | `$` [IDENTIFIER] `:` _MacroFragSpec_\
532ac7d7 27> &nbsp;&nbsp; | `$` `(` _MacroMatch_<sup>+</sup> `)` _MacroRepSep_<sup>?</sup> _MacroRepOp_
13cf67c4
XL
28>
29> _MacroFragSpec_ :\
532ac7d7 30> &nbsp;&nbsp; &nbsp;&nbsp; `block` | `expr` | `ident` | `item` | `lifetime` | `literal`\
17df50a5 31> &nbsp;&nbsp; | `meta` | `pat` | `pat_param` | `path` | `stmt` | `tt` | `ty` | `vis`
13cf67c4
XL
32>
33> _MacroRepSep_ :\
532ac7d7 34> &nbsp;&nbsp; [_Token_]<sub>_except delimiters and repetition operators_</sub>
13cf67c4 35>
dc9dc135
XL
36> _MacroRepOp_ :\
37> &nbsp;&nbsp; `*` | `+` | `?`
13cf67c4
XL
38>
39> _MacroTranscriber_ :\
40> &nbsp;&nbsp; [_DelimTokenTree_]
41
8bb4bdeb
XL
42`macro_rules` allows users to define syntax extension in a declarative way. We
43call such extensions "macros by example" or simply "macros".
44
532ac7d7
XL
45Each macro by example has a name, and one or more _rules_. Each rule has two
46parts: a _matcher_, describing the syntax that it matches, and a _transcriber_,
47describing the syntax that will replace a successfully matched invocation. Both
48the matcher and the transcriber must be surrounded by delimiters. Macros can
49expand to expressions, statements, items (including traits, impls, and foreign
50items), types, or patterns.
51
52## Transcribing
53
54When a macro is invoked, the macro expander looks up macro invocations by name,
55and tries each macro rule in turn. It transcribes the first successful match; if
56this results in an error, then future matches are not tried. When matching, no
57lookahead is performed; if the compiler cannot unambiguously determine how to
58parse the macro invocation one token at a time, then it is an error. In the
59following example, the compiler does not look ahead past the identifier to see
60if the following token is a `)`, even though that would allow it to parse the
61invocation unambiguously:
62
63```rust,compile_fail
64macro_rules! ambiguity {
65 ($($i:ident)* $j:ident) => { };
66}
67
68ambiguity!(error); // Error: local ambiguity
69```
70
71In both the matcher and the transcriber, the `$` token is used to invoke special
72behaviours from the macro engine (described below in [Metavariables] and
73[Repetitions]). Tokens that aren't part of such an invocation are matched and
74transcribed literally, with one exception. The exception is that the outer
75delimiters for the matcher will match any pair of delimiters. Thus, for
76instance, the matcher `(())` will match `{()}` but not `{{}}`. The character
77`$` cannot be matched or transcribed literally.
78
79When forwarding a matched fragment to another macro-by-example, matchers in
80the second macro will see an opaque AST of the fragment type. The second macro
81can't use literal tokens to match the fragments in the matcher, only a
82fragment specifier of the same type. The `ident`, `lifetime`, and `tt`
83fragment types are an exception, and *can* be matched by literal tokens. The
84following illustrates this restriction:
85
86```rust,compile_fail
87macro_rules! foo {
88 ($l:expr) => { bar!($l); }
89// ERROR: ^^ no rules expected this token in macro call
90}
91
92macro_rules! bar {
93 (3) => {}
94}
95
96foo!(3);
97```
98
99The following illustrates how tokens can be directly matched after matching a
100`tt` fragment:
101
102```rust
103// compiles OK
104macro_rules! foo {
105 ($l:tt) => { bar!($l); }
106}
107
108macro_rules! bar {
109 (3) => {}
110}
111
112foo!(3);
113```
114
115## Metavariables
116
117In the matcher, `$` _name_ `:` _fragment-specifier_ matches a Rust syntax
118fragment of the kind specified and binds it to the metavariable `$`_name_. Valid
119fragment 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_]&nbsp;(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
137In the transcriber, metavariables are referred to simply by `$`_name_, since
138the fragment kind is specified in the matcher. Metavariables are replaced with
139the syntax element that matched them. The keyword metavariable `$crate` can be
140used to refer to the current crate; see [Hygiene] below. Metavariables can be
141transcribed more than once or not at all.
142
143## Repetitions
144
145In both the matcher and transcriber, repetitions are indicated by placing the
146tokens to be repeated inside `$(`…`)`, followed by a repetition operator,
147optionally with a separator token between. The separator token can be any token
148other than a delimiter or one of the repetition operators, but `;` and `,` are
149the most common. For instance, `$( $i:ident ),*` represents any number of
150identifiers separated by commas. Nested repetitions are permitted.
151
152The 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
158Since `?` represents at most one occurrence, it cannot be used with a
159separator.
160
161The repeated fragment both matches and transcribes to the specified number of
162the fragment, separated by the separator token. Metavariables are matched to
163every repetition of their corresponding fragment. For instance, the `$( $i:ident
164),*` example above matches `$i` to all of the identifiers in the list.
165
166During transcription, additional restrictions apply to repetitions so that the
167compiler knows how to expand them properly:
168
1691. 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
1752. 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
187For historical reasons, the scoping of macros by example does not work entirely
188like items. Macros have two forms of scope: textual scope, and path-based scope.
532ac7d7
XL
189Textual scope is based on the order that things appear in source files, or even
190across multiple files, and is the default scoping. It is explained further below.
191Path-based scope works exactly the same way that item scoping does. The scoping,
192exporting, and importing of macros is controlled largely by attributes.
193
194When a macro is invoked by an unqualified identifier (not part of a multi-part
195path), it is first looked up in textual scoping. If this does not yield any
196results, then it is looked up in path-based scoping. If the macro's name is
197qualified 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
201use lazy_static::lazy_static; // Path-based import.
202
203macro_rules! lazy_static { // Textual definition.
204 (lazy) => {};
205}
206
207lazy_static!{lazy} // Textual lookup finds our macro first.
208self::lazy_static!{} // Path-based lookup ignores our macro, finds imported one.
209```
210
211### Textual Scope
212
213Textual scope is based largely on the order that things appear in source files,
214and works similarly to the scope of local variables declared with `let` except
215it also applies at the module level. When `macro_rules!` is used to define a
216macro, the macro enters the scope after the definition (note that it can still
217be used recursively, since names are looked up from the invocation site), up
218until its surrounding scope, typically a module, is closed. This can enter child
219modules and even span across multiple files:
220
60c5eb7d 221<!-- ignore: requires external modules -->
532ac7d7
XL
222```rust,ignore
223//// src/lib.rs
224mod 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
239m!{} // OK: appears after declaration of m in src/lib.rs
240```
241
242It is not an error to define a macro multiple times; the most recent declaration
243will shadow the previous one unless it has gone out of scope.
244
245```rust
246macro_rules! m {
247 (1) => {};
248}
249
250m!(1);
251
252mod 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
267m!(1);
268```
13cf67c4 269
532ac7d7
XL
270Macros can be declared and used locally inside functions as well, and work
271similarly:
272
273```rust
274fn 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
288The *`macro_use` attribute* has two purposes. First, it can be used to make a
289module's macro scope not end when the module is closed, by applying it to a
290module:
291
292```rust
293#[macro_use]
294mod inner {
295 macro_rules! m {
296 () => {};
297 }
298}
299
300m!();
301```
302
303Second, it can be used to import macros from another crate, by attaching it to
304an `extern crate` declaration appearing in the crate's root module. Macros
5869c6ff 305imported this way are imported into the [`macro_use` prelude], not textually,
532ac7d7
XL
306which means that they can be shadowed by any other name. While macros imported
307by `#[macro_use]` can be used before the import statement, in case of a
308conflict, the last macro imported wins. Optionally, a list of macros to import
309can be specified using the [_MetaListIdents_] syntax; this is not supported
310when `#[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.
315extern crate lazy_static;
316
dc9dc135 317lazy_static!{}
532ac7d7
XL
318// self::lazy_static!{} // Error: lazy_static is not defined in `self`
319```
320
321Macros to be imported with `#[macro_use]` must be exported with
322`#[macro_export]`, which is described below.
323
324### Path-Based Scope
325
326By 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
328be referred to normally as such:
329
330```rust
331self::m!();
332m!(); // OK: Path-based lookup finds m in the current module.
333
334mod inner {
335 super::m!();
336 crate::m!();
337}
338
339mod mac {
340 #[macro_export]
341 macro_rules! m {
342 () => {};
343 }
344}
345```
346
347Macros labeled with `#[macro_export]` are always `pub` and can be referred to
348by other crates, either by path or by `#[macro_use]` as described above.
349
350## Hygiene
351
352By default, all identifiers referred to in a macro are expanded as-is, and are
353looked up at the macro's invocation site. This can lead to issues if a macro
354refers to an item or macro which isn't in scope at the invocation site. To
355alleviate this, the `$crate` metavariable can be used at the start of a path to
356force 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]
362macro_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]
368macro_rules! helper {
369 () => { () }
370}
371
372//// Usage in another crate.
373// Note that `helper_macro::helper` is not imported!
374use helper_macro::helped;
375
376fn unit() {
377 helped!();
378}
379```
380
381Note that, because `$crate` refers to the current crate, it must be used with a
382fully qualified module path when referring to non-macro items:
383
384```rust
385pub mod inner {
386 #[macro_export]
387 macro_rules! call_foo {
388 () => { $crate::inner::foo() };
389 }
390
391 pub fn foo() {}
392}
393```
394
395Additionally, even though `$crate` allows a macro to refer to items within its
396own crate when expanding, its use has no effect on visibility. An item or macro
397referred to must still be visible from the invocation site. In the following
398example, any attempt to invoke `call_foo!()` from outside its crate will fail
399because `foo()` is not public.
400
401```rust
402#[macro_export]
403macro_rules! call_foo {
404 () => { $crate::foo() };
405}
406
407fn 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
418When a macro is exported, the `#[macro_export]` attribute can have the
419`local_inner_macros` keyword added to automatically prefix all contained macro
420invocations with `$crate::`. This is intended primarily as a tool to migrate
421code written before `$crate` was added to the language to work with Rust 2018's
422path-based imports of macros. Its use is discouraged in new code.
423
424```rust
425#[macro_export(local_inner_macros)]
426macro_rules! helped {
427 () => { helper!() } // Automatically converted to $crate::helper!().
428}
429
430#[macro_export]
431macro_rules! helper {
432 () => { () }
433}
434```
435
436## Follow-set Ambiguity Restrictions
437
438The parser used by the macro system is reasonably powerful, but it is limited in
439order to prevent ambiguity in current or future versions of the language. In
440particular, in addition to the rule about ambiguous expansions, a nonterminal
441matched by a metavariable must be followed by a token which has been decided can
442be safely used after that kind of match.
443
444As an example, a macro matcher like `$i:expr [ , ]` could in theory be accepted
445in Rust today, since `[,]` cannot be part of a legal expression and therefore
446the parse would always be unambiguous. However, because `[` can start trailing
447expressions, `[` is not a character which can safely be ruled out as coming
448after an expression. If `[,]` were accepted in a later version of Rust, this
449matcher would become ambiguous or would misparse, breaking working code.
450Matchers 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
463When repetitions are involved, then the rules apply to every possible number of
464expansions, 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
477For 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