The Rust Reference › Tokens › Literals › C string and raw C string literals › Raw C string literals

* A _byte escape_ escape starts with `U+0078` (`x`) and is followed by exactly two _hex digits_. It denotes the byte equal to the provided hex value.
* A _24-bit code point escape_ starts with `U+0075` (`u`) and is followed by up to six _hex digits_ surrounded by braces `U+007B` (`{`) and `U+007D` (`}`). It denotes the Unicode code point equal to the provided hex value, encoded as UTF-8.
* A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF), `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively.
* The _backslash escape_ is the character `U+005C` (`\`) which must be escaped in order to denote its ASCII encoding `0x5C`.
A C string represents bytes with no defined encoding, but a C string literal may contain Unicode characters above `U+007F`. Such characters will be replaced with the bytes of that character's UTF-8 representation.
The following C string literals are equivalent:
```rust
c"æ";        // LATIN SMALL LETTER AE (U+00E6)
c"\u{00E6}";
c"\xC3\xA6";
```
[!EDITION-2021]
C string literals are accepted in the 2021 edition or later. In earlier editions the token `c""` is lexed as `c ""`.

Tokens
Literals
C string and raw C string literals
Raw C string literals


The Rust Reference › Tokens › Literals › C string and raw C string literals › Raw C string literals

```grammar,lexer
RAW_C_STRING_LITERAL ->
      `cr` `"` ^ RAW_C_STRING_CONTENT `"` SUFFIX?
    | `cr` `#`{n:1..=255} ^ `"` RAW_C_STRING_CONTENT_HASHED `"` `#`{n} SUFFIX?

RAW_C_STRING_CONTENT -> (!`"` ~[CR NUL] )*

RAW_C_STRING_CONTENT_HASHED -> (!(`"` `#`{n}) ~[CR NUL] )*
```
Raw C string literals do not process any escapes. They start with the character `U+0063` (`c`), followed by `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character.
The _raw C string body_ can contain any sequence of Unicode characters other than `U+0000` (NUL) and `U+000D` (CR). It is terminated only by another `U+0022` (double-quote) character, followed by the same number of `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote) character.
All characters contained in the raw C string body represent themselves in UTF-8 encoding. The characters `U+0022` (double-quote) (except when followed by at least as many `U+0023` (`#`) characters as were used to start the raw C string literal) or `U+005C` (`\`) do not have any special meaning.


The Rust Reference › Tokens › Literals › C string and raw C string literals › Examples for C string and raw C string literals

[!EDITION-2021]
Raw C string literals are accepted in the 2021 edition or later. In earlier editions the token `cr""` is lexed as `cr ""`, and `cr#""#` is lexed as `cr #""#` (which is non-grammatical).
```rust
c"foo"; cr"foo";                     // foo
c"\"foo\""; cr#""foo""#;             // "foo"

c"foo #\"# bar";
cr##"foo #"# bar"##;                 // foo #"# bar

c"\x52"; c"R"; cr"R";                // R
c"\\x52"; cr"\x52";                  // \x52
```


The Rust Reference › Tokens › Literals › Number literals › Integer literals

A _number literal_ is either an _integer literal_ or a _floating-point literal_. The grammar for recognizing the two kinds of literals is mixed.
```grammar,lexer
INTEGER_LITERAL ->
    ( BIN_LITERAL | OCT_LITERAL | HEX_LITERAL | DEC_LITERAL )
    ^ !RESERVED_FLOAT SUFFIX?

DEC_LITERAL -> DEC_DIGIT (DEC_DIGIT|`_`)*

BIN_LITERAL -> `0b` ^ `_`* BIN_DIGIT (BIN_DIGIT|`_`)* ![`e` `E` `2`-`9`]

OCT_LITERAL -> `0o` ^ `_`* OCT_DIGIT (OCT_DIGIT|`_`)* ![`e` `E` `8`-`9`]

HEX_LITERAL -> `0x` ^ `_`* HEX_DIGIT (HEX_DIGIT|`_`)*

BIN_DIGIT -> [`0`-`1`]

OCT_DIGIT -> [`0`-`7`]

DEC_DIGIT -> [`0`-`9`]

HEX_DIGIT -> [`0`-`9` `a`-`f` `A`-`F`]

RESERVED_FLOAT -> `.` !(`.` | `_` | XID_Start)
```
An _integer literal_ has one of four forms:
* A _decimal literal_ starts with a *decimal digit* and continues with any mixture of *decimal digits* and _underscores_.
* A _hex literal_ starts with the character sequence `U+0030` `U+0078` (`0x`) and continues as any mixture (with at least one digit) of hex digits and underscores.
* An _octal literal_ starts with the character sequence `U+0030` `U+006F` (`0o`) and continues as any mixture (with at least one digit) of octal digits and underscores.

Tokens
Literals
Number literals
Integer literals


The Rust Reference › Tokens › Literals › Number literals › Integer literals

* A _binary literal_ starts with the character sequence `U+0030` `U+0062` (`0b`) and continues as any mixture (with at least one digit) of binary digits and underscores.
Like any literal, an integer literal may be followed (immediately, without any spaces) by a suffix as described above. The suffix may not begin with `e` or `E`, as that would be interpreted as the exponent of a floating-point literal. See [Integer literal expressions] for the effect of these suffixes.
Examples of integer literals which are accepted as literal expressions:
```rust
123;
123i32;
123u32;
123_u32;

0xff;
0xff_u8;
0x01_f32; // integer 7986, not floating-point 1.0
0x01_e3;  // integer 483, not floating-point 1000.0

0o70;
0o70_i16;

0b1111_1111_1001_0000;
0b1111_1111_1001_0000i64;
0b________1;

0usize;

// These are too big for their type, but are accepted as literal expressions.
128_i8;
256_u8;

// This is an integer literal, accepted as a floating-point literal expression.
5f32;
```
Note that `-1i8`, for example, is analyzed as two tokens: `-` followed by `1i8`.
Examples of integer literals which are not accepted as literal expressions:


The Rust Reference › Tokens › Literals › Number literals › Tuple index

```rust
0invalidSuffix;
123AFB43;
0b010a;
0xAB_CD_EF_GH;
0b1111_f32;
```
Certain integer literal forms are invalid. To avoid ambiguity, the tokenizer rejects them rather than splitting them into separate tokens.
```rust,compile_fail
0b0102;  // This is not `0b010` followed by `2`.
0o1279;  // This is not `0o127` followed by `9`.
0x80.0;  // This is not `0x80` followed by `.` and `0`.
0b101e;  // This is not a suffixed literal or `0b101` followed by `e`.
0b;      // This is not an integer literal or `0` followed by `b`.
0b_;     // This is not an integer literal or `0` followed by `b_`.
2em;     // This is not a suffixed literal or `2` followed by `em`.
2.0em;   // This is not a suffixed literal or `2.0` followed by `em`.
```
It is an error to have an unsuffixed binary or octal literal followed without intervening whitespace by a decimal digit outside the range for its radix.
It is an error to have an unsuffixed binary, octal, or hexadecimal literal followed without intervening whitespace by a period character (subject to the same restrictions on what may follow the period as in floating-point literals).
It is an error to have an unsuffixed binary or octal literal followed without intervening whitespace by the character `e` or `E`.
It is an error for a radix prefix to not be followed, after any optional leading underscores, by at least one valid digit for its radix.

Tokens
Literals
Number literals
Tuple index


The Rust Reference › Tokens › Literals › Number literals › Floating-point literals

```grammar,lexer
TUPLE_INDEX -> DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL
```
A tuple index is used to refer to the fields of [tuples], [tuple structs], and [tuple enum variants].
Tuple indices are compared with the literal token directly. Tuple indices start with `0` and each successive index increments the value by `1` as a decimal value. Thus, only decimal values will match, and the value must not have any extra `0` prefix characters.
Tuple indices may not include any suffixes (such as `usize`).
```rust,compile_fail
let example = ("dog", "cat", "horse");
let dog = example.0;
let cat = example.1;
// The following examples are invalid.
let cat = example.01;  // ERROR no field named `01`
let horse = example.0b10;  // ERROR no field named `0b10`
let unicorn = example.0usize; // ERROR suffixes on a tuple index are invalid
let underscore = example.0_0; // ERROR no field `0_0` on type `(&str, &str, &str)`
```
```grammar,lexer
FLOAT_LITERAL ->
      DEC_LITERAL (`.` DEC_LITERAL)? FLOAT_EXPONENT SUFFIX?
    | DEC_LITERAL `.` DEC_LITERAL SUFFIX?
    | DEC_LITERAL `.` !(`.` | `_` | XID_Start)

FLOAT_EXPONENT ->
    (`e`|`E`) ^ (`+`|`-`)? `_`* DEC_DIGIT (DEC_DIGIT|`_`)*
```
A _floating-point literal_ has one of two forms:
* A _decimal literal_ followed by a period character `U+002E` (`.`). This is optionally followed by another decimal literal, with an optional _exponent_.
* A single _decimal literal_ followed by an _exponent_.

Tokens
Literals
Number literals
Floating-point literals


The Rust Reference › Tokens › Literals › Number literals › Floating-point literals

Like integer literals, a floating-point literal may be followed by a suffix, so long as the pre-suffix part does not end with `U+002E` (`.`). The suffix may not begin with `e` or `E` if the literal does not include an exponent. See [Floating-point literal expressions] for the effect of these suffixes.
Examples of floating-point literals which are accepted as literal expressions:
```rust
123.0f64;
0.1f64;
0.1f32;
12E+99_f64;
let x: f64 = 2.;
```
This last example is different because it is not possible to use the suffix syntax with a floating point literal ending in a period. `2.f64` would attempt to call a method named `f64` on `2`.
Note that `-1.0`, for example, is analyzed as two tokens: `-` followed by `1.0`.
Examples of floating-point literals which are not accepted as literal expressions:
```rust
2.0f80;
2e5f80;
2e5e6;
2.0e5e6;
1.3e10u64;
```
It is an error for a floating-point literal to have an exponent with no digits.
```rust,compile_fail
2e;   // This is not a floating-point literal or `2` followed by `e`.
2.0e; // This is not a floating-point literal or `2.0` followed by `e`.
```


The Rust Reference › Tokens › Lifetimes and loop labels

```grammar,lexer
LIFETIME_TOKEN ->
      RAW_LIFETIME
    | `'` IDENTIFIER_OR_KEYWORD !`'`

LIFETIME_OR_LABEL ->
      RAW_LIFETIME
    | `'` NON_KEYWORD_IDENTIFIER !`'`

RAW_LIFETIME ->
    `'r#` ^ IDENTIFIER_OR_KEYWORD !`'`

RESERVED_RAW_LIFETIME -> `'r#` (`_` | `crate` | `self` | `Self` | `super`) !(`'` | XID_Continue)
```
Lifetime parameters and [loop labels] use LIFETIME_OR_LABEL tokens. Any LIFETIME_TOKEN will be accepted by the lexer, and for example, can be used in macros.
A raw lifetime is like a normal lifetime, but its identifier is prefixed by `r#`. (Note that the `r#` prefix is not included as part of the actual lifetime.)
Unlike a normal lifetime, a raw lifetime may be any strict or reserved keyword except the ones listed above for `RAW_LIFETIME`.
It is an error to use the [RESERVED_RAW_LIFETIME] token.
[!EDITION-2021]
Raw lifetimes are accepted in the 2021 edition or later. In earlier editions the token `'r#lt` is lexed as `'r # lt`.


The Rust Reference › Tokens › Punctuation

Punctuation tokens are used as operators, separators, and other parts of the grammar.
```grammar,lexer
PUNCTUATION ->
      `...`
    | `..=`
    | `<<=`
    | `>>=`
    | `!=`
    | `%=`
    | `&&`
    | `&=`
    | `*=`
    | `+=`
    | `-=`
    | `->`
    | `..`
    | `/=`
    | `::`
    | `<-`
    | `<<`
    | `<=`
    | `==`
    | `=>`
    | `>=`
    | `>>`
    | `^=`
    | `|=`
    | `||`
    | `!`
    | `#`
    | `$`
    | `%`
    | `&`
    | `(`
    | `)`
    | `*`
    | `+`
    | `,`
    | `-`
    | `.`
    | `/`
    | `:`
    | `;`
    | `<`
    | `=`
    | `>`
    | `?`
    | `@`
    | `[`
    | `]`
    | `^`
    | `{`
    | `|`
    | `}`
    | `~`
```
See the [syntax index] for links to how punctuation characters are used.


The Rust Reference › Tokens › Delimiters

Bracket punctuation is used in various parts of the grammar. An open bracket must always be paired with a close bracket. Brackets and the tokens within them are referred to as "token trees" in [macros].  The three types of brackets are:
| Bracket | Type            |
|---------|-----------------|
| `{` `}` | Curly braces    |
| `[` `]` | Square brackets |
| `(` `)` | Parentheses     |


The Rust Reference › Tokens › Reserved tokens

Several token forms are reserved for future use or to avoid confusion. It is an error for the source input to match one of these forms.
```grammar,lexer
RESERVED_TOKEN ->
      RESERVED_GUARDED_STRING_LITERAL
    | RESERVED_POUNDS
    | RESERVED_RAW_IDENTIFIER
    | RESERVED_RAW_LIFETIME
    | RESERVED_TOKEN_DOUBLE_QUOTE
    | RESERVED_TOKEN_LIFETIME
    | RESERVED_TOKEN_POUND
    | RESERVED_TOKEN_SINGLE_QUOTE
```


The Rust Reference › Tokens › Reserved prefixes

```grammar,lexer
RESERVED_TOKEN_DOUBLE_QUOTE ->
    IDENTIFIER_OR_KEYWORD _except `b` or `c` or `r` or `br` or `cr`_ `"`

RESERVED_TOKEN_SINGLE_QUOTE ->
    IDENTIFIER_OR_KEYWORD _except `b`_ `'`

RESERVED_TOKEN_POUND ->
    IDENTIFIER_OR_KEYWORD _except `r` or `br` or `cr`_ `#`

RESERVED_TOKEN_LIFETIME ->
    `'` IDENTIFIER_OR_KEYWORD _except `r`_ `#`
```
Some lexical forms known as _reserved prefixes_ are reserved for future use.
Source input which would otherwise be lexically interpreted as a non-raw identifier (or a keyword) which is immediately followed by a `#`, `'`, or `"` character (without intervening whitespace) is identified as a reserved prefix.
Note that raw identifiers, raw string literals, and raw byte string literals may contain a `#` character but are not interpreted as containing a reserved prefix.
Similarly the `r`, `b`, `br`, `c`, and `cr` prefixes used in raw string literals, byte literals, byte string literals, raw byte string literals, C string literals, and raw C string literals are not interpreted as reserved prefixes.
Source input which would otherwise be lexically interpreted as a non-raw lifetime (or a keyword) which is immediately followed by a `#` character (without intervening whitespace) is identified as a reserved lifetime prefix.
[!EDITION-2021]
Starting with the 2021 edition, reserved prefixes are reported as an error by the lexer (in particular, they cannot be passed to macros).
Before the 2021 edition, reserved prefixes are accepted by the lexer and interpreted as multiple tokens (for example, one token for the identifier or keyword, followed by a `#` token).


The Rust Reference › Tokens › Reserved prefixes

Examples accepted in all editions:
```rust
macro_rules! lexes {($($_:tt)*) => {}}
lexes!{a #foo}
lexes!{continue 'foo}
lexes!{match "..." {}}
lexes!{r#let#foo}         // three tokens: r#let # foo
lexes!{'prefix #lt}
```
Examples accepted before the 2021 edition but rejected later:
```rust,edition2018
macro_rules! lexes {($($_:tt)*) => {}}
lexes!{a#foo}
lexes!{continue'foo}
lexes!{match"..." {}}
lexes!{'prefix#lt}
```


The Rust Reference › Tokens › Reserved guards

```grammar,lexer
RESERVED_GUARDED_STRING_LITERAL -> `#`+ STRING_LITERAL

RESERVED_POUNDS -> `#`{2..}
```
The reserved guards are syntax reserved for future use, and will generate a compile error if used.
The *reserved guarded string literal* is a token of one or more `U+0023` (`#`) immediately followed by a [STRING_LITERAL].
The *reserved pounds* is a token of two or more `U+0023` (`#`).
[!EDITION-2024]
Before the 2024 edition, reserved guards are accepted by the lexer and interpreted as multiple tokens. For example, the `#"foo"#` form is interpreted as three tokens. `##` is interpreted as two tokens.


The Rust Reference › Macros

The functionality and syntax of Rust can be extended with custom definitions called macros. They are given names, and invoked through a consistent syntax: `some_extension!(...)`.
There are two ways to define new macros:
* [Macros by example] define new syntax in a higher-level, declarative way.
* [Procedural macros] define function-like macros, custom derives, and custom attributes using functions that operate on input tokens.


The Rust Reference › Macros › Macro invocation

```grammar,macros
MacroInvocation ->
    SimplePath `!` DelimTokenTree

DelimTokenTree ->
      `(` TokenTree* `)`
    | `[` TokenTree* `]`
    | `{` TokenTree* `}`

TokenTree ->
    Token _except delimiters_ | DelimTokenTree

MacroInvocationSemi ->
      SimplePath `!` `(` TokenTree* `)` `;`
    | SimplePath `!` `[` TokenTree* `]` `;`
    | SimplePath `!` `{` TokenTree* `}`
```
A macro invocation expands a macro at compile time and replaces the invocation with the result of the macro. Macros may be invoked in the following situations:
* [Expressions] and [statements]
* [Patterns]
* [Types]
* [Items] including [associated items]
* [`macro_rules`] transcribers
* [External blocks]
When used as an item or a statement, the [MacroInvocationSemi] form is used where a semicolon is required at the end when not using curly braces. [Visibility qualifiers] are never allowed before a macro invocation or [`macro_rules`] definition.


The Rust Reference › Macros › Macro invocation

```rust
// Used as an expression.
let x = vec![1,2,3];

// Used as a statement.
println!("Hello!");

// Used in a pattern.
macro_rules! pat {
    ($i:ident) => (Some($i))
}

if let pat!(x) = Some(1) {
    assert_eq!(x, 1);
}

// Used in a type.
macro_rules! Tuple {
    { $A:ty, $B:ty } => { ($A, $B) };
}

type N2 = Tuple!(i32, i32);

// Used as an item.
thread_local!(static FOO: RefCell<u32> = RefCell::new(1));

// Used as an associated item.
macro_rules! const_maker {
    ($t:ty, $v:tt) => { const CONST: $t = $v; };
}
trait T {
    const_maker!{i32, 7}
}

// Macro calls within macros.
macro_rules! example {
    () => { println!("Macro call in a macro!") };
}
// Outer macro `example` is expanded, then inner macro `println` is expanded.
example!();
```
Macros invocations can be resolved via two kinds of scopes:
- Textual Scope
  - Textual scope `macro_rules`
- Path-based scope
  - Path-based scope `macro_rules`
  - [Procedural macros]


The Rust Reference › Macros by example

```grammar,macros
MacroRulesDefinition ->
    `macro_rules` `!` IDENTIFIER MacroRulesDef

MacroRulesDef ->
      `(` MacroRules `)` `;`
    | `[` MacroRules `]` `;`
    | `{` MacroRules `}`

MacroRules ->
    MacroRule ( `;` MacroRule )* `;`?

MacroRule ->
    MacroMatcher `=>` MacroTranscriber

MacroMatcher ->
      `(` MacroMatch* `)`
    | `[` MacroMatch* `]`
    | `{` MacroMatch* `}`

MacroMatch ->
      Token _except `$` and delimiters_
    | MacroMatcher
    | `$` ( IDENTIFIER_OR_KEYWORD _except `crate`_ | RAW_IDENTIFIER ) `:` MacroFragSpec
    | `$` `(` MacroMatch+ `)` MacroRepSep? MacroRepOp

MacroFragSpec ->
      `block` | `expr` | `expr_2021` | `ident` | `item` | `lifetime` | `literal`
    | `meta` | `pat` | `pat_param` | `path` | `stmt` | `tt` | `ty` | `vis`

MacroRepSep -> Token _except delimiters and [MacroRepOp]_

MacroRepOp -> `*` | `+` | `?`

MacroTranscriber -> DelimTokenTree
```
`macro_rules` allows users to define syntax extension in a declarative way.  We call such extensions "macros by example" or simply "macros".


The Rust Reference › Macros by example

Each macro by example has a name, and one or more _rules_. Each rule has two parts: a _matcher_, describing the syntax that it matches, and a _transcriber_, describing the syntax that will replace a successfully matched invocation. Both the matcher and the transcriber must be surrounded by delimiters. Macros can expand to expressions, statements, items (including traits, impls, and foreign items), types, or patterns.


The Rust Reference › Macros by example › Transcribing

When a macro is invoked, the macro expander looks up macro invocations by name, and tries each macro rule in turn. It transcribes the first successful match; if this results in an error, then future matches are not tried.
When matching, no lookahead is performed; if the compiler cannot unambiguously determine how to parse the macro invocation one token at a time, then it is an error. In the following example, the compiler does not look ahead past the identifier to see if the following token is a `)`, even though that would allow it to parse the invocation unambiguously:
```rust,compile_fail
macro_rules! ambiguity {
    ($($i:ident)* $j:ident) => { };
}

ambiguity!(error); // Error: local ambiguity
```
In both the matcher and the transcriber, the `$` token is used to invoke special behaviours from the macro engine (described below in [Metavariables] and [Repetitions]). Tokens that aren't part of such an invocation are matched and transcribed literally, with one exception. The exception is that the outer delimiters for the matcher will match any pair of delimiters. Thus, for instance, the matcher `(())` will match `{()}` but not `{{}}`. The character `$` cannot be matched or transcribed literally.


The Rust Reference › Macros by example › Transcribing › Forwarding a matched fragment

When forwarding a matched fragment to another macro-by-example, matchers in the second macro will see an opaque AST of the fragment type. The second macro can't use literal tokens to match the fragments in the matcher, only a fragment specifier of the same type. The `ident`, `lifetime`, and `tt` fragment types are an exception, and *can* be matched by literal tokens. The following illustrates this restriction:
```rust,compile_fail
macro_rules! foo {
    ($l:expr) => { bar!($l); }
// ERROR:               ^^ no rules expected this token in macro call
}

macro_rules! bar {
    (3) => {}
}

foo!(3);
```
The following illustrates how tokens can be directly matched after matching a `tt` fragment:
```rust
// compiles OK
macro_rules! foo {
    ($l:tt) => { bar!($l); }
}

macro_rules! bar {
    (3) => {}
}

foo!(3);
```

Macros by example
Transcribing
Forwarding a matched fragment


The Rust Reference › Macros by example › Metavariables

In the matcher, `$` _name_ `:` _fragment-specifier_ matches a Rust syntax fragment of the kind specified and binds it to the metavariable `$`_name_.
Valid fragment specifiers are:
  * `block`: a [BlockExpressionNoInnerAttributes]
  * `expr`: an [Expression]
  * `expr_2021`: an [Expression] except [UnderscoreExpression] and [ConstBlockExpression] (see [macro.decl.meta.edition2024])
  * `ident`: an [IDENTIFIER_OR_KEYWORD] except `_`, [RAW_IDENTIFIER], or [`$crate`]
  * `item`: an [Item]
  * `lifetime`: a [LIFETIME_TOKEN]
  * `literal`: matches `-`<sup>?</sup>[LiteralExpression]
  * `meta`: an [Attr], the contents of an attribute
  * `pat`: a [Pattern] (see [macro.decl.meta.edition2021])
  * `pat_param`: a [PatternNoTopAlt]
  * `path`: a [TypePath]
  * `stmt`: a Statement without the trailing semicolon (except for item statements that require semicolons)
  * `tt`: a [TokenTree] (a single [token] or tokens in matching delimiters `()`, `[]`, or `{}`)
  * `ty`: a Type
  * `vis`: a possibly empty [Visibility] qualifier
In the transcriber, metavariables are referred to simply by `$`_name_, since the fragment kind is specified in the matcher. Metavariables are replaced with the syntax element that matched them. Metavariables can be transcribed more than once or not at all.
The keyword metavariable [`$crate`] can be used to refer to the current crate.


The Rust Reference › Macros by example › Metavariables

[!EDITION-2021]
Starting with the 2021 edition, `pat` fragment-specifiers match top-level or-patterns (that is, they accept [Pattern]).
Before the 2021 edition, they match exactly the same fragments as `pat_param` (that is, they accept [PatternNoTopAlt]).
The relevant edition is the one in effect for the `macro_rules!` definition.
[!EDITION-2024]
Before the 2024 edition, `expr` fragment specifiers do not match [UnderscoreExpression] or [ConstBlockExpression] at the top level. They are allowed within subexpressions.
The `expr_2021` fragment specifier exists to maintain backwards compatibility with editions before 2024.


The Rust Reference › Macros by example › Repetitions

In both the matcher and transcriber, repetitions are indicated by placing the tokens to be repeated inside `$(`…`)`, followed by a repetition operator, optionally with a separator token between.
The separator token can be any token other than a delimiter or one of the repetition operators, but `;` and `,` are the most common. For instance, `$( $i:ident ),*` represents any number of identifiers separated by commas. Nested repetitions are permitted.
The repetition operators are:
- `*` --- indicates any number of repetitions.
- `+` --- indicates any number but at least one.
- `?` --- indicates an optional fragment with zero or one occurrence.
Since `?` represents at most one occurrence, it cannot be used with a separator.
The repeated fragment both matches and transcribes to the specified number of the fragment, separated by the separator token. Metavariables are matched to every repetition of their corresponding fragment. For instance, the `$( $i:ident ),*` example above matches `$i` to all of the identifiers in the list.
During transcription, additional restrictions apply to repetitions so that the compiler knows how to expand them properly:


The Rust Reference › Macros by example › Repetitions

1.  A metavariable must appear in exactly the same number, kind, and nesting order of repetitions in the transcriber as it did in the matcher. So for the matcher `$( $i:ident ),*`, the transcribers `=> { $i }`, `=> { $( $( $i )* )* }`, and `=> { $( $i )+ }` are all illegal, but `=> { $( $i );* }` is correct and replaces a comma-separated list of identifiers with a semicolon-separated list.
2.  Each repetition in the transcriber must contain at least one metavariable to decide how many times to expand it. If multiple metavariables appear in the same repetition, they must be bound to the same number of fragments. For instance, `( $( $i:ident ),* ; $( $j:ident ),* ) => (( $( ($i,$j) ),* ))` must bind the same number of `$i` fragments as `$j` fragments. This means that invoking the macro with `(a, b, c; d, e, f)` is legal and expands to `((a,d), (b,e), (c,f))`, but `(a, b, c; d, e)` is illegal because it does not have the same number. This requirement applies to every layer of nested repetitions.


The Rust Reference › Macros by example › Scoping, exporting, and importing

For historical reasons, the scoping of macros by example does not work entirely like items. Macros have two forms of scope: textual scope, and path-based scope. Textual scope is based on the order that things appear in source files, or even across multiple files, and is the default scoping. It is explained further below. Path-based scope works exactly the same way that item scoping does. The scoping, exporting, and importing of macros is controlled largely by attributes.
When a macro is invoked by an unqualified identifier (not part of a multi-part path), it is first looked up in textual scoping. If this does not yield any results, then it is looked up in path-based scoping. If the macro's name is qualified with a path, then it is only looked up in path-based scoping.
```rust,ignore
use lazy_static::lazy_static; // Path-based import.

macro_rules! lazy_static { // Textual definition.
    (lazy) => {};
}

lazy_static!{lazy} // Textual lookup finds our macro first.
self::lazy_static!{} // Path-based lookup ignores our macro, finds imported one.
```

Macros by example
Scoping, exporting, and importing


The Rust Reference › Macros by example › Scoping, exporting, and importing › Textual scope

Textual scope is based largely on the order that things appear in source files, and works similarly to the scope of local variables declared with `let` except it also applies at the module level. When `macro_rules!` is used to define a macro, the macro enters the scope after the definition (note that it can still be used recursively, since names are looked up from the invocation site), up until its surrounding scope, typically a module, is closed. This can enter child modules and even span across multiple files:
```rust,ignore
//// src/lib.rs
mod has_macro {
    // m!{} // Error: m is not in scope.

    macro_rules! m {
        () => {};
    }
    m!{} // OK: appears after declaration of m.

    mod uses_macro;
}

// m!{} // Error: m is not in scope.

//// src/has_macro/uses_macro.rs

m!{} // OK: appears after declaration of m in src/lib.rs
```
It is not an error to define a macro multiple times; the most recent declaration will shadow the previous one unless it has gone out of scope.
```rust
macro_rules! m {
    (1) => {};
}

m!(1);

mod inner {
    m!(1);

    macro_rules! m {
        (2) => {};
    }
    // m!(1); // Error: no rule matches '1'
    m!(2);

    macro_rules! m {
        (3) => {};
    }
    m!(3);
}

m!(1);
```
Macros can be declared and used locally inside functions as well, and work similarly:
```rust
fn foo() {
    // m!(); // Error: m is not in scope.
    macro_rules! m {
        () => {};
    }
    m!();
}

// m!(); // Error: m is not in scope.
```
Textual scope name bindings for macros shadow path-based scope bindings to macros.

Macros by example
Scoping, exporting, and importing
Textual scope


The Rust Reference › Macros by example › Scoping, exporting, and importing › Textual scope

```rust
macro_rules! m2 {
    () => {
        println!("m2");
    };
}

// Resolves to path-based candidate from use declaration below.
m!(); // prints "m2\n"

// Introduce second candidate for `m` with textual scope.
//
// This shadows path-based candidate from below for the rest of this
// example.
macro_rules! m {
    () => {
        println!("m");
    };
}

// Introduce `m2` macro as path-based candidate.
//
// This item is in scope for this entire example, not just below the
// use declaration.
use m2 as m;

// Resolves to the textual macro candidate from above the use
// declaration.
m!(); // prints "m\n"
```
For areas where shadowing is not allowed, see [name resolution ambiguities].


The Rust Reference › Macros by example › Scoping, exporting, and importing › Path-based scope

By default, a macro has no path-based scope. Macros can gain path-based scope in two ways:
- [Use declaration re-export]
- [`macro_export`]
Macros can be re-exported to give them path-based scope from a module other than the crate root.
```rust
mac::m!(); // OK: Path-based lookup finds `m` in the mac module.

mod mac {
    // Introduce macro `m` with textual scope.
    macro_rules! m {
        () => {};
    }

    // Reexport with path-based scope from within `m`'s textual scope.
    pub(crate) use m;
}
```
Macros have an implicit visibility of `pub(crate)`. `#[macro_export]` changes the implicit visibility to `pub`.
```rust
// Implicit visibility is `pub(crate)`.
macro_rules! private_m {
    () => {};
}

// Implicit visibility is `pub`.
#[macro_export]
macro_rules! pub_m {
    () => {};
}

pub(crate) use private_m as private_macro; // OK.
pub use pub_m as pub_macro; // OK.
```
```rust,compile_fail,E0364
pub use private_m; // ERROR: `private_m` is only public within
                   // the crate and cannot be re-exported outside.
```

Macros by example
Scoping, exporting, and importing
Path-based scope


The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_use` attribute

The *`macro_use` attribute* has two purposes: it may be used on modules to extend the scope of macros defined within them, and it may be used on `extern crate` to import macros from another crate into the [`macro_use` prelude].
```rust
#[macro_use]
mod inner {
    macro_rules! m {
        () => {};
    }
}
m!();
```
```rust,ignore
#[macro_use]
extern crate log;
```
When used on modules, the `macro_use` attribute uses the [MetaWord] syntax.
When used on `extern crate`, it uses the [MetaWord] and [MetaListIdents] syntaxes. For more on how these syntaxes may be used, see [macro.decl.scope.macro_use.prelude].
The `macro_use` attribute may be applied to modules or `extern crate`.
`rustc` ignores use in other positions but lints against it. This may become an error in the future.
The `macro_use` attribute may not be used on [`extern crate self`].
The `macro_use` attribute may be used any number of times on a form.
Multiple instances of `macro_use` in the [MetaListIdents] syntax may be specified. The union of all specified macros will be imported.
On modules, `rustc` lints against any [MetaWord] `macro_use` attributes following the first.

Macros by example
Scoping, exporting, and importing
The `macro_use` attribute


The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_use` attribute

On `extern crate`, `rustc` lints against any `macro_use` attributes that have no effect due to not importing any macros not already imported by another `macro_use` attribute. If two or more [MetaListIdents] `macro_use` attributes import the same macro, the first is linted against. If any [MetaWord] `macro_use` attributes are present, all [MetaListIdents] `macro_use` attributes are linted against. If two or more [MetaWord] `macro_use` attributes are present, the ones following the first are linted against.
When `macro_use` is used on a module, the module's macro scope extends beyond the module's lexical scope.
```rust
#[macro_use]
mod inner {
    macro_rules! m {
        () => {};
    }
}
m!(); // OK
```
Specifying `macro_use` on an `extern crate` declaration in the crate root imports exported macros from that crate.
Macros imported this way are imported into the [`macro_use` prelude], not textually, which means that they can be shadowed by any other name. Macros imported by `macro_use` can be used before the import statement.
`rustc` currently prefers the last macro imported in case of conflict. Don't rely on this. This behavior is unusual, as imports in Rust are generally order-independent. This behavior of `macro_use` may change in the future.
For details, see Rust issue #148025.
When using the [MetaWord] syntax, all exported macros are imported. When using the [MetaListIdents] syntax, only the specified macros are imported.


The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_use` attribute

```rust,ignore
#[macro_use(lazy_static)] // Or `#[macro_use]` to import all macros.
extern crate lazy_static;

lazy_static!{}
// self::lazy_static!{} // ERROR: lazy_static is not defined in `self`.
```
Macros to be imported with `macro_use` must be exported with `macro_export`.


The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_export` attribute

The *`macro_export` attribute* exports the macro from the crate and makes it available in the root of the crate for path-based resolution.
```rust
self::m!();
//  ^^^^ OK: Path-based lookup finds `m` in the current module.
m!(); // As above.

mod inner {
    super::m!();
    crate::m!();
}

mod mac {
    #[macro_export]
    macro_rules! m {
        () => {};
    }
}
```
The `macro_export` attribute uses the [MetaWord] and [MetaListIdents] syntaxes. With the [MetaListIdents] syntax, it accepts a single `local_inner_macros` value.
The `macro_export` attribute may be applied to `macro_rules` definitions.
`rustc` ignores use in other positions but lints against it. This may become an error in the future.
Only the first use of `macro_export` on a macro has effect.
`rustc` lints against any use following the first.
By default, macros only have textual scope and cannot be resolved by path. When the `macro_export` attribute is used, the macro is made available in the crate root and can be referred to by its path.
Without `macro_export`, macros only have textual scope, so path-based resolution of the macro fails.
```rust,compile_fail,E0433
macro_rules! m {
    () => {};
}
self::m!(); // ERROR
crate::m!(); // ERROR
```
With `macro_export`, path-based resolution works.
```rust
#[macro_export]
macro_rules! m {
    () => {};
}
self::m!(); // OK
crate::m!(); // OK
```

Macros by example
Scoping, exporting, and importing
The `macro_export` attribute


The Rust Reference › Macros by example › Scoping, exporting, and importing › The `macro_export` attribute

The `macro_export` attribute causes a macro to be exported from the crate root so that it can be referred to in other crates by path.
Given the following in a `log` crate:
```rust
#[macro_export]
macro_rules! warn {
    ($message:expr) => { eprintln!("WARN: {}", $message) };
}
```
From another crate, you can refer to the macro by path:
```rust,ignore
fn main() {
    log::warn!("example warning");
}
```
`macro_export` allows the use of `macro_use` on an `extern crate` to import the macro into the [`macro_use` prelude].
Given the following in a `log` crate:
```rust
#[macro_export]
macro_rules! warn {
    ($message:expr) => { eprintln!("WARN: {}", $message) };
}
```
Using `macro_use` in a dependent crate allows you to use the macro from the prelude:
```rust,ignore
#[macro_use]
extern crate log;

pub mod util {
    pub fn do_thing() {
        // Resolved via macro prelude.
        warn!("example warning");
    }
}
```
Adding `local_inner_macros` to the `macro_export` attribute causes all single-segment macro invocations in the macro definition to have an implicit `$crate::` prefix.
This is intended primarily as a tool to migrate code written before [`$crate`] was added to the language to work with Rust 2018's path-based imports of macros. Its use is discouraged in new code.
```rust
#[macro_export(local_inner_macros)]
macro_rules! helped {
    () => { helper!() } // Automatically converted to $crate::helper!().
}

#[macro_export]
macro_rules! helper {
    () => { () }
}
```


The Rust Reference › Macros by example › Hygiene

Macros by example have _mixed-site hygiene_. This means that [loop labels], [block labels], and local variables are looked up at the macro definition site while other symbols are looked up at the macro invocation site. For example:
```rust
let x = 1;
fn func() {
    unreachable!("this is never called")
}

macro_rules! check {
    () => {
        assert_eq!(x, 1); // Uses `x` from the definition site.
        func();           // Uses `func` from the invocation site.
    };
}

{
    let x = 2;
    fn func() { /* does not panic */ }
    check!();
}
```
Labels and local variables defined in macro expansion are not shared between invocations, so this code doesn’t compile:
```rust,compile_fail,E0425
macro_rules! m {
    (define) => {
        let x = 1;
    };
    (refer) => {
        dbg!(x);
    };
}

m!(define);
m!(refer);
```
A special case is the `$crate` metavariable. It refers to the crate defining the macro, and can be used at the start of the path to look up items or macros which are not in scope at the invocation site.
```rust,ignore
//// Definitions in the `helper_macro` crate.
#[macro_export]
macro_rules! helped {
    // () => { helper!() } // This might lead to an error due to 'helper' not being in scope.
    () => { $crate::helper!() }
}

#[macro_export]
macro_rules! helper {
    () => { () }
}

//// Usage in another crate.
// Note that `helper_macro::helper` is not imported!
use helper_macro::helped;

fn unit() {
    helped!();
}
```


The Rust Reference › Macros by example › Hygiene

Note that, because `$crate` refers to the current crate, it must be used with a fully qualified module path when referring to non-macro items:
```rust
pub mod inner {
    #[macro_export]
    macro_rules! call_foo {
        () => { $crate::inner::foo() };
    }

    pub fn foo() {}
}
```
Additionally, even though `$crate` allows a macro to refer to items within its own crate when expanding, its use has no effect on visibility. An item or macro referred to must still be visible from the invocation site. In the following example, any attempt to invoke `call_foo!()` from outside its crate will fail because `foo()` is not public.
```rust
#[macro_export]
macro_rules! call_foo {
    () => { $crate::foo() };
}

fn foo() {}
```
Prior to Rust 1.30, `$crate` and `local_inner_macros` were unsupported. They were added alongside path-based imports of macros, to ensure that helper macros did not need to be manually imported by users of a macro-exporting crate. Crates written for earlier versions of Rust that use helper macros need to be modified to use `$crate` or `local_inner_macros` to work well with path-based imports.


The Rust Reference › Macros by example › Follow-set ambiguity restrictions

The parser used by the macro system is reasonably powerful, but it is limited in order to prevent ambiguity in current or future versions of the language.
In particular, in addition to the rule about ambiguous expansions, a nonterminal matched by a metavariable must be followed by a token which has been decided can be safely used after that kind of match.
As an example, a macro matcher like `$i:expr [ , ]` could in theory be accepted in Rust today, since `[,]` cannot be part of a legal expression and therefore the parse would always be unambiguous. However, because `[` can start trailing expressions, `[` is not a character which can safely be ruled out as coming after an expression. If `[,]` were accepted in a later version of Rust, this matcher would become ambiguous or would misparse, breaking working code. Matchers like `$i:expr,` or `$i:expr;` would be legal, however, because `,` and `;` are legal expression separators. The specific rules are:
  * `expr` and `stmt` may only be followed by one of: `=>`, `,`, or `;`.
  * `pat_param` may only be followed by one of: `=>`, `,`, `=`, `|`, `if`, or `in`.
  * `pat` may only be followed by one of: `=>`, `,`, `=`, `if`, or `in`.
  * `path` and `ty` may only be followed by one of: `=>`, `,`, `=`, `|`, `;`, `:`, `>`, `>>`, `[`, `{`, `as`, `where`, or a macro variable of `block` fragment specifier.

Macros by example
Follow-set ambiguity restrictions


The Rust Reference › Macros by example › Follow-set ambiguity restrictions

* `vis` may only be followed by one of: `,`, an identifier other than a non-raw `priv`, any token that can begin a type, or a metavariable with a `ident`, `ty`, or `path` fragment specifier.
  * All other fragment specifiers have no restrictions.
[!EDITION-2021]
Before the 2021 edition, `pat` may also be followed by `|`.
When repetitions are involved, then the rules apply to every possible number of expansions, taking separators into account. This means:
  * If the repetition includes a separator, that separator must be able to follow the contents of the repetition.
  * If the repetition can repeat multiple times (`*` or `+`), then the contents must be able to follow themselves.
  * The contents of the repetition must be able to follow whatever comes before, and whatever comes after must be able to follow the contents of the repetition.
  * If the repetition can match zero times (`*` or `?`), then whatever comes after must be able to follow whatever comes before.
For more detail, see the [formal specification].


The Rust Reference › Procedural macros

*Procedural macros* allow creating syntax extensions as execution of a function. Procedural macros come in one of three flavors:
* [Function-like macros] - `custom!(...)`
* [Derive macros] - `#[derive(CustomDerive)]`
* [Attribute macros] - `#[CustomAttribute]`
Procedural macros allow you to run code at compile time that operates over Rust syntax, both consuming and producing Rust syntax. You can sort of think of procedural macros as functions from an AST to another AST.
Procedural macros must be defined in the root of a crate with the [crate type] of `proc-macro`. The macros may not be used from the crate where they are defined, and can only be used when imported in another crate.
When using Cargo, Procedural macro crates are defined with the `proc-macro` key in your manifest:
```toml
[lib]
proc-macro = true
```
As functions, they must either return syntax, panic, or loop endlessly. Returned syntax either replaces or adds the syntax depending on the kind of procedural macro. Panics are caught by the compiler and are turned into a compiler error. Endless loops are not caught by the compiler which hangs the compiler.
Procedural macros run during compilation, and thus have the same resources that the compiler has. For example, standard input, error, and output are the same that the compiler has access to. Similarly, file access is the same. Because of this, procedural macros have the same security concerns that [Cargo's build scripts] have.
Procedural macros have two ways of reporting errors. The first is to panic. The second is to emit a [`compile_error`] macro invocation.


The Rust Reference › Procedural macros › The `proc_macro` crate

Procedural macro crates almost always will link to the compiler-provided [`proc_macro` crate]. The `proc_macro` crate provides types required for writing procedural macros and facilities to make it easier.
This crate primarily contains a [`TokenStream`] type. Procedural macros operate over *token streams* instead of AST nodes, which is a far more stable interface over time for both the compiler and for procedural macros to target. A *token stream* is roughly equivalent to `Vec<TokenTree>` where a `TokenTree` can roughly be thought of as lexical token. For example `foo` is an `Ident` token, `.` is a `Punct` token, and `1.2` is a `Literal` token. The `TokenStream` type, unlike `Vec<TokenTree>`, is cheap to clone.
All tokens have an associated `Span`. A `Span` is an opaque value that cannot be modified but can be manufactured. `Span`s represent an extent of source code within a program and are primarily used for error reporting. While you cannot modify a `Span` itself, you can always change the `Span` *associated* with any token, such as through getting a `Span` from another token.

Procedural macros
The `proc_macro` crate


The Rust Reference › Procedural macros › Procedural macro hygiene

Procedural macros are *unhygienic*. This means they behave as if the output token stream was simply written inline to the code it's next to. This means that it's affected by external items and also affects external imports.
Macro authors need to be careful to ensure their macros work in as many contexts as possible given this limitation. This often includes using absolute paths to items in libraries (for example, `::std::option::Option` instead of `Option`) or by ensuring that generated functions have names that are unlikely to clash with other functions (like `__internal_foo` instead of `foo`).

Procedural macros
Procedural macro hygiene


The Rust Reference › Procedural macros › The `proc_macro` attribute

The *`proc_macro` attribute* defines a function-like procedural macro.
This macro definition ignores its input and emits a function `answer` into its scope.
```rust,ignore
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro]
pub fn make_answer(_item: TokenStream) -> TokenStream {
    "fn answer() -> u32 { 42 }".parse().unwrap()
}
```
We can use it in a binary crate to print "42" to standard output.
```rust,ignore
extern crate proc_macro_examples;
use proc_macro_examples::make_answer;

make_answer!();

fn main() {
    println!("{}", answer());
}
```
The `proc_macro` attribute uses the [MetaWord] syntax.
The `proc_macro` attribute may only be applied to a `pub` function of type `fn(TokenStream) -> TokenStream` where [`TokenStream`] comes from the [`proc_macro` crate]. It must have the "Rust" ABI. No other function qualifiers are allowed. It must be located in the root of the crate.
The `proc_macro` attribute may only be specified once on a function.
The `proc_macro` attribute publicly defines the macro in the [macro namespace] in the root of the crate with the same name as the function.
A function-like macro invocation of a function-like procedural macro will pass what is inside the delimiters of the macro invocation as the input [`TokenStream`] argument and replace the entire macro invocation with the output [`TokenStream`] of the function.
Function-like procedural macros may be invoked in any macro invocation position, which includes:
- [Statements]
- [Expressions]
- [Patterns]
- [Type expressions]
- [Item] positions, including items in [`extern` blocks]
- Inherent and trait [implementations]
- [Trait definitions]

Procedural macros
The `proc_macro` attribute


The Rust Reference › Procedural macros › The `proc_macro_derive` attribute

Applying the *`proc_macro_derive` [attribute]* to a function defines a *derive macro* that can be invoked by the [`derive` attribute]. These macros are given the token stream of a [struct], [enum], or [union] definition and can emit new [items] after it. They can also declare and use [derive macro helper attributes].
This derive macro ignores its input and appends tokens that define a function.
```rust,ignore
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_derive(AnswerFn)]
pub fn derive_answer_fn(_item: TokenStream) -> TokenStream {
    "fn answer() -> u32 { 42 }".parse().unwrap()
}
```
To use it, we might write:
```rust,ignore
extern crate proc_macro_examples;
use proc_macro_examples::AnswerFn;

#[derive(AnswerFn)]
struct Struct;

fn main() {
    assert_eq!(42, answer());
}
```
The syntax for the `proc_macro_derive` attribute is:
```grammar,attributes
@root ProcMacroDeriveAttribute ->
    `proc_macro_derive` `(` DeriveMacroName ( `,` DeriveMacroAttributes )? `,`? `)`

DeriveMacroName -> IDENTIFIER

DeriveMacroAttributes ->
    `attributes` `(` ( IDENTIFIER (`,` IDENTIFIER)* `,`?)? `)`
```
The name of the derive macro is given by [DeriveMacroName]. The optional `attributes` argument is described in [macro.proc.derive.attributes].

Procedural macros
The `proc_macro_derive` attribute


The Rust Reference › Procedural macros › The `proc_macro_derive` attribute

The `proc_macro_derive` attribute may only be applied to a `pub` function with the Rust ABI defined in the root of the crate with a type of `fn(TokenStream) -> TokenStream`  where [`TokenStream`] comes from the [`proc_macro` crate]. The function may be `const` and may use `extern` to explicitly specify the Rust ABI, but it may not use any other qualifiers (e.g. it may not be `async` or `unsafe`).
The `proc_macro_derive` attribute may be used only once on a function.
The `proc_macro_derive` attribute publicly defines the derive macro in the [macro namespace] in the root of the crate.
The input [`TokenStream`] is the token stream of the item to which the `derive` attribute is applied. The output [`TokenStream`] must be a (possibly empty) set of items. These items are appended following the input item within the same [module] or [block].


The Rust Reference › Procedural macros › The `proc_macro_derive` attribute › Derive macro helper attributes

Derive macros can declare *derive macro helper attributes* to be used within the scope of the [item] to which the derive macro is applied. These [attributes] are [inert]. While their purpose is to be used by the macro that declared them, they can be seen by any macro.
A helper attribute for a derive macro is declared by adding its identifier to the `attributes` list in the `proc_macro_derive` attribute.
This declares a helper attribute and then ignores it.
```rust,ignore
#[proc_macro_derive(WithHelperAttr, attributes(helper))]
pub fn derive_with_helper_attr(_item: TokenStream) -> TokenStream {
    TokenStream::new()
}
```
To use it, we might write:
```rust,ignore
#[derive(WithHelperAttr)]
struct Struct {
    #[helper] field: (),
}
```
When a derive macro invocation is applied to an item, the helper attributes introduced by that derive macro become in scope 1) for attributes that are applied to that item and are applied lexically after the derive macro invocation and 2) for attributes that are applied to fields and variants inside of the item.
rustc currently allows derive helpers to be used before the macro that introduces them. Such derive helpers used out of order may not shadow other attribute macros. This behavior is deprecated and slated for removal.
```rust,ignore
#[helper] // Deprecated, hard error in the future.
#[derive(WithHelperAttr)]
struct Struct {
    field: (),
}
```
For more details, see Rust issue #79202.

Procedural macros
The `proc_macro_derive` attribute
Derive macro helper attributes


The Rust Reference › Procedural macros › The `proc_macro_attribute` attribute

The *`proc_macro_attribute` attribute* defines an *attribute macro* which can be used as an outer attribute.
This attribute macro takes the input stream and emits it as-is, effectively being a no-op attribute.
```rust,ignore

#[proc_macro_attribute]
pub fn return_as_is(_attr: TokenStream, item: TokenStream) -> TokenStream {
    item
}
```
This shows, in the output of the compiler, the stringified [`TokenStream`s] that attribute macros see.
```rust,ignore
// my-macro/src/lib.rs
#[proc_macro_attribute]
pub fn show_streams(attr: TokenStream, item: TokenStream) -> TokenStream {
    println!("attr: \"{attr}\"");
    println!("item: \"{item}\"");
    item
}
```
```rust,ignore
// src/lib.rs
extern crate my_macro;

use my_macro::show_streams;

// Example: Basic function.
#[show_streams]
fn invoke1() {}
// out: attr: ""
// out: item: "fn invoke1() {}"

// Example: Attribute with input.
#[show_streams(bar)]
fn invoke2() {}
// out: attr: "bar"
// out: item: "fn invoke2() {}"

// Example: Multiple tokens in the input.
#[show_streams(multiple => tokens)]
fn invoke3() {}
// out: attr: "multiple => tokens"
// out: item: "fn invoke3() {}"

// Example: Delimiters in the input.
#[show_streams { delimiters }]
fn invoke4() {}
// out: attr: "delimiters"
// out: item: "fn invoke4() {}"
```
The `proc_macro_attribute` attribute uses the [MetaWord] syntax.

Procedural macros
The `proc_macro_attribute` attribute


The Rust Reference › Procedural macros › The `proc_macro_attribute` attribute

The `proc_macro_attribute` attribute may only be applied to a `pub` function of type `fn(TokenStream, TokenStream) -> TokenStream` where [`TokenStream`] comes from the [`proc_macro` crate]. It must have the "Rust" ABI. No other function qualifiers are allowed. It must be located in the root of the crate.
The `proc_macro_attribute` attribute may only be specified once on a function.
The `proc_macro_attribute` attribute defines the attribute in the [macro namespace] in the root of the crate with the same name as the function.
Attribute macros can only be used on:
- [Items]
- Items in [`extern` blocks]
- Inherent and trait [implementations]
- [Trait definitions]
For any [outline modules] present in the macro's input, only the tokens of the module declaration are passed; the file contents of the module are not loaded or included in the input.
The first [`TokenStream`] parameter is the delimited token tree following the attribute's name but not including the outer delimiters. If the applied attribute contains only the attribute name or the attribute name followed by empty delimiters, the [`TokenStream`] is empty.
The second [`TokenStream`] is the rest of the [item], including other [attributes] on the [item].
The item to which the attribute is applied is replaced by the zero or more items in the returned [`TokenStream`].


The Rust Reference › Procedural macros › Declarative macro tokens and procedural macro tokens

Declarative `macro_rules` macros and procedural macros use similar, but different definitions for tokens (or rather [`TokenTree`s].)
Token trees in `macro_rules` (corresponding to `tt` matchers) are defined as
- Delimited groups (`(...)`, `{...}`, etc)
- All operators supported by the language, both single-character and multi-character ones (`+`, `+=`).
    - Note that this set doesn't include the single quote `'`.
- Literals (`"string"`, `1`, etc)
    - Note that negation (e.g. `-1`) is never a part of such literal tokens, but a separate operator token.
- Identifiers, including keywords (`ident`, `r#ident`, `fn`)
- Lifetimes (`'ident`)
- Metavariable substitutions in `macro_rules` (e.g. `$my_expr` in `macro_rules! mac { ($my_expr: expr) => { $my_expr } }` after the `mac`'s expansion, which will be considered a single token tree regardless of the passed expression)
Token trees in procedural macros are defined as
- Delimited groups (`(...)`, `{...}`, etc)
- All punctuation characters used in operators supported by the language (`+`, but not `+=`), and also the single quote `'` character (typically used in lifetimes, see below for lifetime splitting and joining behavior)
- Literals (`"string"`, `1`, etc)
    - Negation (e.g. `-1`) is supported as a part of integer and floating point literals.
- Identifiers, including keywords (`ident`, `r#ident`, `fn`)
Mismatches between these two definitions are accounted for when token streams are passed to and from procedural macros. Note that the conversions below may happen lazily, so they might not happen if the tokens are not actually inspected.


The Rust Reference › Procedural macros › Declarative macro tokens and procedural macro tokens

When passed to a proc-macro
- All multi-character operators are broken into single characters.
- Lifetimes are broken into a `'` character and an identifier.
- The keyword metavariable [`$crate`] is passed as a single identifier.
- All other metavariable substitutions are represented as their underlying token streams.
    - Such token streams may be wrapped into delimited groups ([`Group`]) with implicit delimiters ([`Delimiter::None`]) when it's necessary for preserving parsing priorities.
    - `tt` and `ident` substitutions are never wrapped into such groups and always represented as their underlying token trees.
When emitted from a proc macro
- Punctuation characters are glued into multi-character operators when applicable.
- Single quotes `'` joined with identifiers are glued into lifetimes.
- Negative literals are converted into two tokens (the `-` and the literal) possibly wrapped into a delimited group ([`Group`]) with implicit delimiters ([`Delimiter::None`]) when it's necessary for preserving parsing priorities.
Note that neither declarative nor procedural macros support doc comment tokens (e.g. `/// Doc`), so they are always converted to token streams representing their equivalent `#[doc = r"str"]` attributes when passed to macros.


The Rust Reference › Crates and source files

```grammar,items
@root Crate ->
    InnerAttribute*
    Item*
```
Although Rust, like any other language, can be implemented by an interpreter as well as a compiler, the only existing implementation is a compiler, and the language has always been designed to be compiled. For these reasons, this section assumes a compiler.
Rust's semantics obey a *phase distinction* between compile-time and run-time.[^phase-distinction] Semantic rules that have a *static interpretation* govern the success or failure of compilation, while semantic rules that have a *dynamic interpretation* govern the behavior of the program at run-time.
The compilation model centers on artifacts called _crates_. Each compilation processes a single crate in source form, and if successful, produces a single crate in binary form: either an executable or some sort of library.[^cratesourcefile]
A _crate_ is a unit of compilation and linking, as well as versioning, distribution, and runtime loading. A crate contains a _tree_ of nested [module] scopes. The top level of this tree is a module that is anonymous (from the point of view of paths within the module) and any item within a crate has a canonical [module path] denoting its location within the crate's module tree.
The Rust compiler is always invoked with a single source file as input, and always produces a single output crate. The processing of that source file may result in other source files being loaded as modules. Source files have the extension `.rs`.
A Rust source file describes a module, the name and location of which — in the module tree of the current crate — are defined from outside the source file: either by an explicit Module item in a referencing source file, or by the name of the crate itself.
Every source file is a module, but not every module needs its own source file: module definitions can be nested within one file.


The Rust Reference › Crates and source files

Each source file contains a sequence of zero or more [Item] definitions, and may optionally begin with any number of [attributes] that apply to the containing module, most of which influence the behavior of the compiler.
The anonymous crate module can have additional attributes that apply to the crate as a whole.
The file's contents may be preceded by a [shebang].
```rust
// Specify the crate name.
#![crate_name = "projx"]

// Specify the type of output artifact.
#![crate_type = "lib"]

// Turn on a warning.
// This can be done in any module, not just the anonymous crate module.
#![warn(non_camel_case_types)]
```


The Rust Reference › Crates and source files › Main functions

A crate that contains a `main` [function] can be compiled to an executable.
If a `main` function is present, it must take no arguments, must not declare any [trait or lifetime bounds], must not have any [where clauses], and its return type must implement the [`Termination`] trait.
```rust
fn main() {}
```
```rust
fn main() -> ! {
    std::process::exit(0);
}
```
```rust
fn main() -> impl std::process::Termination {
    std::process::ExitCode::SUCCESS
}
```
The `main` function may be an import, e.g. from an external crate or from the current one.
```rust
mod foo {
    pub fn bar() {
        println!("Hello, world!");
    }
}
use foo::bar as main;
```
Types with implementations of [`Termination`] in the standard library include:
* `()`
* [`!`]
* [`Infallible`]
* [`ExitCode`]
* `Result<T, E> where T: Termination, E: Debug`


The Rust Reference › Crates and source files › Main functions › Uncaught foreign unwinding

When a "foreign" unwind (e.g. an exception thrown from C++ code, or a `panic!` in Rust code using a different panic handler) propagates beyond the `main` function, the process will be safely terminated. This may take the form of an abort, in which case it is not guaranteed that any `Drop` calls will be executed, and the error output may be less informative than if the runtime had been terminated by a "native" Rust `panic`.
For more information, see the panic documentation.

Crates and source files
Main functions
Uncaught foreign unwinding


The Rust Reference › Crates and source files › Main functions › The `no_main` attribute

The *`no_main` [attribute]* may be applied at the crate level to disable emitting the `main` symbol for an executable binary. This is useful when some other object being linked to defines `main`.

Crates and source files
Main functions
The `no_main` attribute


The Rust Reference › Crates and source files › The `crate_name` attribute

The *`crate_name` [attribute]* may be applied at the crate level to specify the name of the crate with the [MetaNameValueStr] syntax.
```rust
#![crate_name = "mycrate"]
```
The crate name must not be empty, and must only contain [Unicode alphanumeric] or `_` (U+005F) characters.
[^phase-distinction]: This distinction would also exist in an interpreter. Static checks like syntactic analysis, type checking, and lints should happen before the program is executed regardless of when it is executed.
[^cratesourcefile]: A crate is somewhat analogous to an *assembly* in the ECMA-335 CLI model, a *library* in the SML/NJ Compilation Manager, a *unit* in the Owens and Flatt module system, or a *configuration* in Mesa.

Crates and source files
The `crate_name` attribute


The Rust Reference › Conditional compilation

```grammar,configuration
ConfigurationPredicate ->
      ConfigurationOption
    | ConfigurationAll
    | ConfigurationAny
    | ConfigurationNot
    | `true`
    | `false`

ConfigurationOption ->
    IDENTIFIER ( `=` ( STRING_LITERAL | RAW_STRING_LITERAL ) )?

ConfigurationAll ->
    `all` `(` ConfigurationPredicateList? `)`

ConfigurationAny ->
    `any` `(` ConfigurationPredicateList? `)`

ConfigurationNot ->
    `not` `(` ConfigurationPredicate `)`

ConfigurationPredicateList ->
    ConfigurationPredicate (`,` ConfigurationPredicate)* `,`?
```
*Conditionally compiled source code* is source code that is compiled only under certain conditions.
Source code can be made conditionally compiled using the [`cfg`] and [`cfg_attr`] [attributes] and the built-in [`cfg!`] and [`cfg_select!`] [macros].
Whether to compile can depend on the target architecture of the compiled crate, arbitrary values passed to the compiler, and other things further described below.
Each form of conditional compilation takes a _configuration predicate_ that evaluates to true or false. The predicate is one of the following:
* A configuration option. The predicate is true if the option is set, and false if it is unset.
* `all()` with a comma-separated list of configuration predicates. It is true if all of the given predicates are true, or if the list is empty.
* `any()` with a comma-separated list of configuration predicates. It is true if at least one of the given predicates is true. If there are no predicates, it is false.
* `not()` with a configuration predicate. It is true if its predicate is false and false if its predicate is true.
* `true` or `false` literals, which are always true or false respectively.
_Configuration options_ are either names or key-value pairs, and are either set or unset.
Names are written as a single identifier, such as `unix`.


The Rust Reference › Conditional compilation

Key-value pairs are written as an identifier, `=`, and then a string, such as `target_arch = "x86_64"`.
Whitespace around the `=` is ignored, so `foo="bar"` and `foo = "bar"` are equivalent.
Keys do not need to be unique. For example, both `feature = "std"` and `feature = "serde"` can be set at the same time.


The Rust Reference › Conditional compilation › Set configuration options

Which configuration options are set is determined statically during the compilation of the crate.
Some options are _compiler-set_ based on data about the compilation.
Other options are _arbitrarily-set_ based on input passed to the compiler outside of the code.
It is not possible to set a configuration option from within the source code of the crate being compiled.
For `rustc`, arbitrary-set configuration options are set using the [`--cfg`] flag. Configuration values for a specified target can be displayed with `rustc --print cfg --target $TARGET`.
Configuration options with the key `feature` are a convention used by Cargo for specifying compile-time options and optional dependencies.

Conditional compilation
Set configuration options


The Rust Reference › Conditional compilation › Set configuration options › `target_arch`

Key-value option set once with the target's CPU architecture. The value is similar to the first element of the platform's target triple, but not identical.
Example values:
* `"x86"`
* `"x86_64"`
* `"mips"`
* `"powerpc"`
* `"powerpc64"`
* `"arm"`
* `"aarch64"`

Conditional compilation
Set configuration options
`target_arch`


The Rust Reference › Conditional compilation › Set configuration options › `target_feature`

Key-value option set for each platform feature available for the current compilation target.
Example values:
* `"avx"`
* `"avx2"`
* `"crt-static"`
* `"rdrand"`
* `"sse"`
* `"sse2"`
* `"sse4.1"`
See the [`target_feature` attribute] for more details on the available features.
An additional feature of `crt-static` is available to the `target_feature` option to indicate that a [static C runtime] is available.

Conditional compilation
Set configuration options
`target_feature`


The Rust Reference › Conditional compilation › Set configuration options › `target_os`

Key-value option set once with the target's operating system. This value is similar to the second and third element of the platform's target triple.
Example values:
* `"windows"`
* `"macos"`
* `"ios"`
* `"linux"`
* `"android"`
* `"freebsd"`
* `"dragonfly"`
* `"openbsd"`
* `"netbsd"`
* `"none"` (typical for embedded targets)

Conditional compilation
Set configuration options
`target_os`


The Rust Reference › Conditional compilation › Set configuration options › `target_family`

Key-value option providing a more generic description of a target, such as the family of the operating systems or architectures that the target generally falls into. Any number of `target_family` key-value pairs can be set.
Example values:
* `"unix"`
* `"windows"`
* `"wasm"`
* Both `"unix"` and `"wasm"`

Conditional compilation
Set configuration options
`target_family`


The Rust Reference › Conditional compilation › Set configuration options › `unix` and `windows`

`unix` is set if `target_family = "unix"` is set.
`windows` is set if `target_family = "windows"` is set.

Conditional compilation
Set configuration options
`unix` and `windows`


The Rust Reference › Conditional compilation › Set configuration options › `target_env`

Key-value option set with further disambiguating information about the target platform with information about the ABI or `libc` used. For historical reasons, this value is only defined as not the empty-string when actually needed for disambiguation. Thus, for example, on many GNU platforms, this value will be empty. This value is similar to the fourth element of the platform's target triple. One difference is that embedded ABIs such as `gnueabihf` will simply define `target_env` as `"gnu"`.
Example values:
* `""`
* `"gnu"`
* `"msvc"`
* `"musl"`
* `"sgx"`
* `"sim"`
* `"macabi"`

Conditional compilation
Set configuration options
`target_env`


The Rust Reference › Conditional compilation › Set configuration options › `target_abi`

Key-value option set to further disambiguate the target with information about the target ABI.
For historical reasons, this value is only defined as not the empty-string when actually needed for disambiguation. Thus, for example, on many GNU platforms, this value will be empty.
Example values:
* `""`
* `"llvm"`
* `"eabihf"`
* `"abi64"`

Conditional compilation
Set configuration options
`target_abi`


The Rust Reference › Conditional compilation › Set configuration options › `target_endian`

Key-value option set once with either a value of "little" or "big" depending on the endianness of the target's CPU.

Conditional compilation
Set configuration options
`target_endian`


The Rust Reference › Conditional compilation › Set configuration options › `target_pointer_width`

Key-value option set once with the target's pointer width in bits.
Example values:
* `"16"`
* `"32"`
* `"64"`

Conditional compilation
Set configuration options
`target_pointer_width`


The Rust Reference › Conditional compilation › Set configuration options › `target_vendor`

Key-value option set once with the vendor of the target.
Example values:
* `"apple"`
* `"fortanix"`
* `"pc"`
* `"unknown"`

Conditional compilation
Set configuration options
`target_vendor`


The Rust Reference › Conditional compilation › Set configuration options › `target_has_atomic`

Key-value option set for each bit width that the target supports atomic loads, stores, and compare-and-swap operations.
When this cfg is present, all of the stable [`core::sync::atomic`] APIs are available for the relevant atomic width.
Possible values:
* `"8"`
* `"16"`
* `"32"`
* `"64"`
* `"128"`
* `"ptr"`

Conditional compilation
Set configuration options
`target_has_atomic`


The Rust Reference › Conditional compilation › Set configuration options › `target_has_atomic_primitive_alignment`

Key-value option set for each bit width where the atomic type has the same alignment as the corresponding integer type.
The alignment is usually the same for a given bit width. However, on some targets such as 32-bit x86, 64-bit atomic types such as `AtomicI64` have an alignment of 8 bytes while `i64` is only aligned to 4 bytes. In this situation, `target_has_atomic_primitive_alignment = "64"` is not set.
Possible values:
* `"8"`
* `"16"`
* `"32"`
* `"64"`
* `"128"`
* `"ptr"`

Conditional compilation
Set configuration options
`target_has_atomic_primitive_alignment`


The Rust Reference › Conditional compilation › Set configuration options › `test`

Enabled when compiling the test harness. Done with `rustc` by using the [`--test`] flag. See [Testing] for more on testing support.

Conditional compilation
Set configuration options
`test`


The Rust Reference › Conditional compilation › Set configuration options › `debug_assertions`

Enabled by default when compiling without optimizations. This can be used to enable extra debugging code in development but not in production.  For example, it controls the behavior of the standard library's [`debug_assert!`] macro.

Conditional compilation
Set configuration options
`debug_assertions`


The Rust Reference › Conditional compilation › Set configuration options › `proc_macro`

Set when the crate being compiled is being compiled with the `proc_macro` [crate type].

Conditional compilation
Set configuration options
`proc_macro`


The Rust Reference › Conditional compilation › Set configuration options › `panic`

Key-value option set depending on the [panic strategy]. Note that more values may be added in the future.
Example values:
* `"abort"`
* `"unwind"`

Conditional compilation
Set configuration options
`panic`


The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg` attribute

The *`cfg` [attribute]* conditionally includes the form to which it is attached based on a configuration predicate.
```rust
// The function is only included in the build when compiling for macOS
#[cfg(target_os = "macos")]
fn macos_only() {
  // ...
}

// This function is only included when either foo or bar is defined
#[cfg(any(foo, bar))]
fn needs_foo_or_bar() {
  // ...
}

// This function is only included when compiling for a unixish OS with a 32-bit
// architecture
#[cfg(all(unix, target_pointer_width = "32"))]
fn on_32bit_unix() {
  // ...
}

// This function is only included when foo is not defined
#[cfg(not(foo))]
fn needs_not_foo() {
  // ...
}

// This function is only included when the panic strategy is set to unwind
#[cfg(panic = "unwind")]
fn when_unwinding() {
  // ...
}
```
The syntax for the `cfg` attribute is:
```grammar,configuration
@root CfgAttribute -> `cfg` `(` ConfigurationPredicate `)`
```
The `cfg` attribute may be used anywhere attributes are allowed.
The `cfg` attribute may be used any number of times on a form. The form to which the attributes are attached will not be included if any of the `cfg` predicates are false except as described in [cfg.attr.crate-level-attrs].
If the predicates are true, the form is rewritten to not have the `cfg` attributes on it. If any predicate is false, the form is removed from the source code.
When a crate-level `cfg` has a false predicate, the crate itself still exists. Any crate attributes preceding the `cfg` are kept, and any crate attributes following the `cfg` are removed as well as removing all of the following crate contents.

Conditional compilation
Forms of conditional compilation
The `cfg` attribute


The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg` attribute

The behavior of not removing the preceding attributes allows you to do things such as include `#![no_std]` to avoid linking `std` even if a `#![cfg(...)]` has otherwise removed the contents of the crate. For example:
```rust,ignore
// This `no_std` attribute is kept even though the crate-level `cfg`
// attribute is false.
#![no_std]
#![cfg(false)]

// This function is not included.
pub fn example() {}
```


The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg_attr` attribute

The *`cfg_attr` [attribute]* conditionally includes attributes based on a configuration predicate.
The following module will either be found at `linux.rs` or `windows.rs` based on the target.
```rust,ignore
#[cfg_attr(target_os = "linux", path = "linux.rs")]
#[cfg_attr(windows, path = "windows.rs")]
mod os;
```
The syntax for the `cfg_attr` attribute is:
```grammar,configuration
@root CfgAttrAttribute -> `cfg_attr` `(` ConfigurationPredicate `,` CfgAttrs? `)`

CfgAttrs -> Attr (`,` Attr)* `,`?
```
The `cfg_attr` attribute may be used anywhere attributes are allowed.
The `cfg_attr` attribute may be used any number of times on a form.
The [`crate_type`] and [`crate_name`] attributes cannot be used with `cfg_attr`.
When the configuration predicate is true, `cfg_attr` expands out to the attributes listed after the predicate.
Zero, one, or more attributes may be listed. Multiple attributes will each be expanded into separate attributes.
```rust,ignore
#[cfg_attr(feature = "magic", sparkles, crackles)]
fn bewitched() {}

// When the `magic` feature flag is enabled, the above will expand to:
#[sparkles]
#[crackles]
fn bewitched() {}
```
The `cfg_attr` can expand to another `cfg_attr`. For example, `#[cfg_attr(target_os = "linux", cfg_attr(feature = "multithreaded", some_other_attribute))]` is valid. This example would be equivalent to `#[cfg_attr(all(target_os = "linux", feature = "multithreaded"), some_other_attribute)]`.

Conditional compilation
Forms of conditional compilation
The `cfg_attr` attribute


The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg` macro

The built-in `cfg` macro takes in a single configuration predicate and evaluates to the `true` literal when the predicate is true and the `false` literal when it is false.
For example:
```rust
let machine_kind = if cfg!(unix) {
  "unix"
} else if cfg!(windows) {
  "windows"
} else {
  "unknown"
};

println!("I'm running on a {} machine!", machine_kind);
```

Conditional compilation
Forms of conditional compilation
The `cfg` macro


The Rust Reference › Conditional compilation › Forms of conditional compilation › The `cfg_select` macro

The built-in `cfg_select!` macro can be used to select code at compile-time based on multiple configuration predicates.
```rust
cfg_select! {
    unix => {
        fn foo() { /* unix specific functionality */ }
    }
    target_pointer_width = "32" => {
        fn foo() { /* non-unix, 32-bit functionality */ }
    }
    _ => {
        fn foo() { /* fallback implementation */ }
    }
}

let is_unix_str = cfg_select! {
    unix => "unix",
    _ => "not unix",
};
```
```grammar,configuration
@root CfgSelect -> CfgSelectArms?

CfgSelectArms ->
    CfgSelectConfigurationPredicate `=>`
    (
        `{` ^ TokenTree `}` `,`? CfgSelectArms?
      | ExpressionWithBlockNoAttrs `,`? CfgSelectArms?
      | ExpressionWithoutBlockNoAttrs ( `,` CfgSelectArms? )?
    )

CfgSelectConfigurationPredicate ->
    ConfigurationPredicate | `_`
```
`cfg_select` expands to the payload of the first arm whose configuration predicate evaluates to true.
If the entire payload is wrapped in curly braces, the braces are removed during expansion.
The configuration predicate `_` always evaluates to true.
It is a compile error if none of the predicates evaluate to true.
Each right-hand side must be a syntactically valid expansion for the position in which the macro is invoked.

Conditional compilation
Forms of conditional compilation
The `cfg_select` macro


The Rust Reference › Items

```grammar,items
Item ->
    OuterAttribute* ( VisItem | MacroItem )

VisItem ->
    Visibility?
    (
        Module
      | ExternCrate
      | UseDeclaration
      | Function
      | TypeAlias
      | Struct
      | Enumeration
      | Union
      | ConstantItem
      | StaticItem
      | Trait
      | Implementation
      | ExternBlock
    )

MacroItem ->
      MacroInvocationSemi
    | MacroRulesDefinition
```
An _item_ is a component of a crate. Items are organized within a crate by a nested set of [modules]. Every crate has a single "outermost" anonymous module; all further items within the crate have [paths] within the module tree of the crate.
Items are entirely determined at compile-time, generally remain fixed during execution, and may reside in read-only memory.
There are several kinds of items:
* [modules]
* [`extern crate` declarations]
* [`use` declarations]
* [function definitions]
* [type alias definitions]
* [struct definitions]
* [enumeration definitions]
* [union definitions]
* [constant items]
* [static items]
* [trait definitions]
* [implementations]
* [`extern` blocks]
Items may be declared in the [root of the crate], a module, or a [block expression].
A subset of items, called [associated items], may be declared in [traits] and [implementations].
A subset of items, called external items, may be declared in [`extern` blocks].
Items may be defined in any order, with the exception of [`macro_rules`] which has its own scoping behavior.
[Name resolution] of item names allows items to be defined before or after where the item is referred to in the module or block.
See [item scopes] for information on the scoping rules of items.


The Rust Reference › Modules

```grammar,items
Module ->
      `unsafe`? `mod` IDENTIFIER `;`
    | `unsafe`? `mod` IDENTIFIER `{`
        InnerAttribute*
        Item*
      `}`
```
A module is a container for zero or more [items].
A _module item_ is a module, surrounded in braces, named, and prefixed with the keyword `mod`. A module item introduces a new, named module into the tree of modules making up a crate.
Modules can nest arbitrarily.
An example of a module:
```rust
mod math {
    type Complex = (f64, f64);
    fn sin(f: f64) -> f64 {
        /* ... */
    }
    fn cos(f: f64) -> f64 {
        /* ... */
    }
    fn tan(f: f64) -> f64 {
        /* ... */
    }
}
```
Modules are defined in the [type namespace] of the module or block where they are located.
It is an error to define multiple items with the same name in the same namespace within a module. See the [scopes chapter] for more details on restrictions and shadowing behavior.
The `unsafe` keyword is syntactically allowed to appear before the `mod` keyword, but it is rejected at a semantic level. This allows macros to consume the syntax and make use of the `unsafe` keyword, before removing it from the token stream.


The Rust Reference › Modules › Module source filenames

A module without a body is loaded from an external file. When the module does not have a `path` attribute, the path to the file mirrors the logical [module path].
Ancestor module path components are directories, and the module's contents are in a file with the name of the module plus the `.rs` extension. For example, the following module structure can have this corresponding filesystem structure:
Module Path               | Filesystem Path  | File Contents
------------------------- | ---------------  | -------------
`crate`                   | `lib.rs`         | `mod util;`
`crate::util`             | `util.rs`        | `mod config;`
`crate::util::config`     | `util/config.rs` |
Module filenames may also be the name of the module as a directory with the contents in a file named `mod.rs` within that directory. The above example can alternately be expressed with `crate::util`'s contents in a file named `util/mod.rs`. It is not allowed to have both `util.rs` and `util/mod.rs`.
Prior to `rustc` 1.30, using `mod.rs` files was the way to load a module with nested children. It is encouraged to use the new naming convention as it is more consistent, and avoids having many files named `mod.rs` within a project.


The Rust Reference › Modules › Module source filenames › The `path` attribute

The directories and files used for loading external file modules can be influenced with the `path` attribute.
For `path` attributes on modules not inside inline module blocks, the file path is relative to the directory the source file is located. For example, the following code snippet would use the paths shown based on where it is located:
```rust,ignore
#[path = "foo.rs"]
mod c;
```
Source File    | `c`'s File Location | `c`'s Module Path
-------------- | ------------------- | ----------------------
`src/a/b.rs`   | `src/a/foo.rs`      | `crate::a::b::c`
`src/a/mod.rs` | `src/a/foo.rs`      | `crate::a::c`
For `path` attributes inside inline module blocks, the relative location of the file path depends on the kind of source file the `path` attribute is located in. "mod-rs" source files are root modules (such as `lib.rs` or `main.rs`) and modules with files named `mod.rs`. "non-mod-rs" source files are all other module files. Paths for `path` attributes inside inline module blocks in a mod-rs file are relative to the directory of the mod-rs file including the inline module components as directories. For non-mod-rs files, it is the same except the path starts with a directory with the name of the non-mod-rs module. For example, the following code snippet would use the paths shown based on where it is located:
```rust,ignore
mod inline {
    #[path = "other.rs"]
    mod inner;
}
```

Modules
Module source filenames
The `path` attribute


The Rust Reference › Modules › Module source filenames › The `path` attribute

Source File    | `inner`'s File Location   | `inner`'s Module Path
-------------- | --------------------------| ----------------------------
`src/a/b.rs`   | `src/a/b/inline/other.rs` | `crate::a::b::inline::inner`
`src/a/mod.rs` | `src/a/inline/other.rs`   | `crate::a::inline::inner`
An example of combining the above rules of `path` attributes on inline modules and nested modules within (applies to both mod-rs and non-mod-rs files):
```rust,ignore
#[path = "thread_files"]
mod thread {
    // Load the `local_data` module from `thread_files/tls.rs` relative to
    // this source file's directory.
    #[path = "tls.rs"]
    mod local_data;
}
```


The Rust Reference › Modules › Attributes on modules

Modules, like all items, accept outer attributes. They also accept inner attributes: either after `{` for a module with a body, or at the beginning of the source file, after the optional BOM and shebang.
The built-in attributes that have meaning on a module are [`cfg`], [`deprecated`], [`doc`], [the lint check attributes], [`path`], and [`no_implicit_prelude`]. Modules also accept macro attributes.


The Rust Reference › Extern crate declarations

```grammar,items
ExternCrate -> `extern` `crate` CrateRef AsClause? `;`

CrateRef -> IDENTIFIER | `self`

AsClause -> `as` ( IDENTIFIER | `_` )
```
An _`extern crate` declaration_ specifies a dependency on an external crate.
The external crate is then bound into the declaring scope as the given [identifier] in the [type namespace].
Additionally, if the `extern crate` appears in the crate root, then the crate name is also added to the [extern prelude], making it automatically in scope in all modules.
The `as` clause can be used to bind the imported crate to a different name.
The external crate is resolved to a specific `soname` at compile time, and a runtime linkage requirement to that `soname` is passed to the linker for loading at runtime. The `soname` is resolved at compile time by scanning the compiler's library path and matching the optional `crate_name` provided against the [`crate_name` attributes] that were declared on the external crate when it was compiled. If no `crate_name` is provided, a default `name` attribute is assumed, equal to the [identifier] given in the `extern crate` declaration.
The `self` crate may be imported which creates a binding to the current crate. In this case the `as` clause must be used to specify the name to bind it to.
Three examples of `extern crate` declarations:
```rust,ignore
extern crate pcre;

extern crate std; // equivalent to: extern crate std as std;

extern crate std as ruststd; // linking to 'std' under another name
```


The Rust Reference › Extern crate declarations

When naming Rust crates, hyphens are disallowed. However, Cargo packages may make use of them. In such case, when `Cargo.toml` doesn't specify a crate name, Cargo will transparently replace `-` with `_` (Refer to [RFC 940] for more details).
Here is an example:
```rust,ignore
// Importing the Cargo package hello-world
extern crate hello_world; // hyphen replaced with an underscore
```


The Rust Reference › Extern crate declarations › Underscore imports

An external crate dependency can be declared without binding its name in scope by using an underscore with the form `extern crate foo as _`. This may be useful for crates that only need to be linked, but are never referenced, and will avoid being reported as unused.
The [`macro_use` attribute] works as usual and imports the macro names into the [`macro_use` prelude].

Extern crate declarations
Underscore imports


The Rust Reference › Extern crate declarations › The `no_link` attribute

The *`no_link` attribute* may be applied to an `extern crate` item to prevent linking the crate.
This is helpful, e.g., when only the macros of a crate are needed.
```rust,ignore
#[no_link]
extern crate other_crate;

other_crate::some_macro!();
```
The `no_link` attribute uses the [MetaWord] syntax.
The `no_link` attribute may only be applied to an `extern crate` declaration.
`rustc` ignores use in other positions but lints against it. This may become an error in the future.
Only the first use of `no_link` on an `extern crate` declaration has effect.
`rustc` lints against any use following the first. This may become an error in the future.

Extern crate declarations
The `no_link` attribute


The Rust Reference › Use declarations

```grammar,items
UseDeclaration -> `use` UseTree `;`

UseTree ->
      (SimplePath? `::`)? `*`
    | (SimplePath? `::`)? `{` (UseTree ( `,`  UseTree )* `,`?)? `}`
    | SimplePath ( `as` ( IDENTIFIER | `_` ) )?
```
A _use declaration_ creates one or more local name bindings synonymous with some other [path]. Usually a `use` declaration is used to shorten the path required to refer to a module item. These declarations may appear in [modules] and [blocks], usually at the top. A `use` declaration is also sometimes called an _import_, or, if it is public, a _re-export_.
Use declarations support a number of convenient shortcuts:
* Simultaneously binding a list of paths with a common prefix, using the brace syntax `use a::b::{c, d, e::f, g::h::i};`
* Simultaneously binding a list of paths with a common prefix and their common parent module, using the `self` keyword, such as `use a::b::{self, c, d::e};`
* Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`. This can also be used with the last two features: `use a::b::{self as ab, c as abc}`.
* Binding all paths matching a given prefix, using the asterisk wildcard syntax `use a::b::*;`.
* Nesting groups of the previous features multiple times, such as `use a::b::{self as ab, c, d::{*, e::f}};`
An example of `use` declarations:


The Rust Reference › Use declarations

```rust
use std::collections::hash_map::{self, HashMap};

fn foo<T>(_: T){}
fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}

fn main() {
    // use declarations can also exist inside of functions
    use std::option::Option::{Some, None};

    // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
    // std::option::Option::None]);'
    foo(vec![Some(1.0f64), None]);

    // Both `hash_map` and `HashMap` are in scope.
    let map1 = HashMap::new();
    let map2 = hash_map::HashMap::new();
    bar(map1, map2);
}
```


The Rust Reference › Use declarations › `use` Visibility

Like items, `use` declarations are private to the containing module, by default. Also like items, a `use` declaration can be public, if qualified by the `pub` keyword. Such a `use` declaration serves to _re-export_ a name. A public `use` declaration can therefore _redirect_ some public name to a different target definition: even a definition with a private canonical path, inside a different module.
If a sequence of such redirections form a cycle or cannot be resolved unambiguously, they represent a compile-time error.
An example of re-exporting:
```rust
mod quux {
    pub use self::foo::{bar, baz};
    pub mod foo {
        pub fn bar() {}
        pub fn baz() {}
    }
}

fn main() {
    quux::bar();
    quux::baz();
}
```
In this example, the module `quux` re-exports two public names defined in `foo`.


The Rust Reference › Use declarations › `use` Paths

The [paths] that are allowed in a `use` item follow the [SimplePath] grammar and are similar to the paths that may be used in an expression. They may create bindings for:
* Nameable [items]
* [Enum variants]
* [Built-in types]
* [Attributes]
* [Derive macros]
* [`macro_rules`]
They cannot import [associated items], [generic parameters], [local variables], paths with [`Self`], or [tool attributes]. More restrictions are described below.
`use` will create bindings for all [namespaces] from the imported entities, with the exception that a `self` import will only import from the type namespace (as described below). For example, the following illustrates creating bindings for the same name in two namespaces:
```rust
mod stuff {
    pub struct Foo(pub i32);
}

// Imports the `Foo` type and the `Foo` constructor.
use stuff::Foo;

fn example() {
    let ctor = Foo; // Uses `Foo` from the value namespace.
    let x: Foo = ctor(123); // Uses `Foo` From the type namespace.
}
```
[!EDITION-2018]
In the 2015 edition, `use` paths are relative to the crate root. For example:
```rust,edition2015
mod foo {
    pub mod example { pub mod iter {} }
    pub mod baz { pub fn foobaz() {} }
}
mod bar {
    // Resolves `foo` from the crate root.
    use foo::example::iter;
    // The `::` prefix explicitly resolves `foo`
    // from the crate root.
    use ::foo::baz::foobaz;
}

```


The Rust Reference › Use declarations › `use` Paths

The 2015 edition does not allow use declarations to reference the [extern prelude]. Thus, [`extern crate`] declarations are still required in 2015 to reference an external crate in a `use` declaration. Beginning with the 2018 edition, `use` declarations can specify an external crate dependency the same way `extern crate` can.


The Rust Reference › Use declarations › `as` renames

The `as` keyword can be used to change the name of an imported entity. For example:
```rust
// Creates a non-public alias `bar` for the function `foo`.
use inner::foo as bar;

mod inner {
    pub fn foo() {}
}
```


The Rust Reference › Use declarations › Brace syntax

Braces can be used in the last segment of the path to import multiple entities from the previous segment, or, if there are no previous segments, from the current scope. Braces can be nested, creating a tree of paths, where each grouping of segments is logically combined with its parent to create a full path.
```rust
// Creates bindings to:
// - `std::collections::BTreeSet`
// - `std::collections::hash_map`
// - `std::collections::hash_map::HashMap`
use std::collections::{BTreeSet, hash_map::{self, HashMap}};
```
An empty brace does not import anything, though the leading path is validated that it is accessible.
[!EDITION-2018]
In the 2015 edition, paths are relative to the crate root, so an import such as `use {foo, bar};` will import the names `foo` and `bar` from the crate root, whereas starting in 2018, those names are relative to the current scope.


The Rust Reference › Use declarations › `self` imports

The keyword `self` may be used within [brace syntax] to create a binding of the parent entity under its own name.
```rust
mod stuff {
    pub fn foo() {}
    pub fn bar() {}
}
mod example {
    // Creates a binding for `stuff` and `foo`.
    use crate::stuff::{self, foo};
    pub fn baz() {
        foo();
        stuff::bar();
    }
}
```
`self` may also be used as the first segment of a path. The use of `self` as the first segment and inside a `use` brace is logically the same; it means the current module of the parent segment, or the current module if there is no parent segment. See [`self`] in the paths chapter for more information on the meaning of a leading `self`.
`self` may appear as the last segment of a `use` path, preceded by `::`. A path of the form `P::self` is equivalent to `P::{self}`, and `P::self as name` is equivalent to `P::{self as name}`.
```rust
mod m {
    pub enum E { V1, V2 }
}
use m::self as _; // Equivalent to `use m::{self as _};`.
use m::E::self; // Equivalent to `use m::E::{self};`.
```
See [paths.qualifiers.mod-self.trailing] for restrictions on the preceding path.
When `self` is used within [brace syntax], the path preceding the brace group must resolve to a [module], [enumeration], or [trait].


The Rust Reference › Use declarations › `self` imports

```rust
mod m {
    pub enum E { V1, V2 }
    pub trait Tr { fn f(&self); }
}
use m::{self as _}; // OK: Modules can be parents of `self`.
use m::E::{self, V1}; // OK: Enums can be parents of `self`.
use m::Tr::{self}; // OK: Traits can be parents of `self`.
```
```rust,compile_fail,E0432
struct S {}
use S::{self as _}; // ERROR: Structs cannot be parents of `self`.
```
`self` only creates a binding from the [type namespace] of the parent entity. For example, in the following, only the `foo` mod is imported:
```rust,compile_fail
mod bar {
    pub mod foo {}
    pub fn foo() {}
}

// This only imports the module `foo`. The function `foo` lives in
// the value namespace and is not imported.
use bar::foo::{self};

fn main() {
    foo(); //~ ERROR `foo` is a module
}
```


The Rust Reference › Use declarations › Glob imports

The `*` character may be used as the last segment of a `use` path to import all importable entities from the entity of the preceding segment. For example:
```rust
// Creates a non-public alias to `bar`.
use foo::*;

mod foo {
    fn i_am_private() {}
    enum Example {
        V1,
        V2,
    }
    pub fn bar() {
        // Creates local aliases to `V1` and `V2`
        // of the `Example` enum.
        use Example::*;
        let x = V1;
    }
}
```
Items and named imports are allowed to shadow names from glob imports in the same [namespace]. That is, if there is a name already defined by another item in the same namespace, the glob import will be shadowed. For example:
```rust
// This creates a binding to the `clashing::Foo` tuple struct
// constructor, but does not import its type because that would
// conflict with the `Foo` struct defined here.
//
// Note that the order of definition here is unimportant.
use clashing::*;
struct Foo {
    field: f32,
}

fn do_stuff() {
    // Uses the constructor from `clashing::Foo`.
    let f1 = Foo(123);
    // The struct expression uses the type from
    // the `Foo` struct defined above.
    let f2 = Foo { field: 1.0 };
    // `Bar` is also in scope due to the glob import.
    let z = Bar {};
}

mod clashing {
    pub struct Foo(pub i32);
    pub struct Bar {}
}
```
For areas where shadowing is not allowed, see [name resolution ambiguities].
`*` cannot be used as the first or intermediate segments.
`*` cannot be used to import a module's contents into itself (such as `use self::*;`).


The Rust Reference › Use declarations › Glob imports

[!EDITION-2018]
In the 2015 edition, paths are relative to the crate root, so an import such as `use *;` is valid, and it means to import everything from the crate root. This cannot be used in the crate root itself.