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