]> git.lizzy.rs Git - rust.git/blob - src/doc/reference.md
Rollup merge of #24750 - withoutboats:patch-1, r=steveklabnik
[rust.git] / src / doc / reference.md
1 % The Rust Reference
2
3 # Introduction
4
5 This document is the primary reference for the Rust programming language. It
6 provides three kinds of material:
7
8   - Chapters that informally describe each language construct and their use.
9   - Chapters that informally describe the memory model, concurrency model,
10     runtime services, linkage model and debugging facilities.
11   - Appendix chapters providing rationale and references to languages that
12     influenced the design.
13
14 This document does not serve as an introduction to the language. Background
15 familiarity with the language is assumed. A separate [book] is available to
16 help acquire such background familiarity.
17
18 This document also does not serve as a reference to the [standard] library
19 included in the language distribution. Those libraries are documented
20 separately by extracting documentation attributes from their source code. Many
21 of the features that one might expect to be language features are library
22 features in Rust, so what you're looking for may be there, not here.
23
24 You may also be interested in the [grammar].
25
26 [book]: book/index.html
27 [standard]: std/index.html
28 [grammar]: grammar.html
29
30 # Notation
31
32 Rust's grammar is defined over Unicode codepoints, each conventionally denoted
33 `U+XXXX`, for 4 or more hexadecimal digits `X`. _Most_ of Rust's grammar is
34 confined to the ASCII range of Unicode, and is described in this document by a
35 dialect of Extended Backus-Naur Form (EBNF), specifically a dialect of EBNF
36 supported by common automated LL(k) parsing tools such as `llgen`, rather than
37 the dialect given in ISO 14977. The dialect can be defined self-referentially
38 as follows:
39
40 ```{.ebnf .notation}
41 grammar : rule + ;
42 rule    : nonterminal ':' productionrule ';' ;
43 productionrule : production [ '|' production ] * ;
44 production : term * ;
45 term : element repeats ;
46 element : LITERAL | IDENTIFIER | '[' productionrule ']' ;
47 repeats : [ '*' | '+' ] NUMBER ? | NUMBER ? | '?' ;
48 ```
49
50 Where:
51
52 - Whitespace in the grammar is ignored.
53 - Square brackets are used to group rules.
54 - `LITERAL` is a single printable ASCII character, or an escaped hexadecimal
55   ASCII code of the form `\xQQ`, in single quotes, denoting the corresponding
56   Unicode codepoint `U+00QQ`.
57 - `IDENTIFIER` is a nonempty string of ASCII letters and underscores.
58 - The `repeat` forms apply to the adjacent `element`, and are as follows:
59   - `?` means zero or one repetition
60   - `*` means zero or more repetitions
61   - `+` means one or more repetitions
62   - NUMBER trailing a repeat symbol gives a maximum repetition count
63   - NUMBER on its own gives an exact repetition count
64
65 This EBNF dialect should hopefully be familiar to many readers.
66
67 ## Unicode productions
68
69 A few productions in Rust's grammar permit Unicode codepoints outside the ASCII
70 range. We define these productions in terms of character properties specified
71 in the Unicode standard, rather than in terms of ASCII-range codepoints. The
72 section [Special Unicode Productions](#special-unicode-productions) lists these
73 productions.
74
75 ## String table productions
76
77 Some rules in the grammar — notably [unary
78 operators](#unary-operator-expressions), [binary
79 operators](#binary-operator-expressions), and [keywords](#keywords) — are
80 given in a simplified form: as a listing of a table of unquoted, printable
81 whitespace-separated strings. These cases form a subset of the rules regarding
82 the [token](#tokens) rule, and are assumed to be the result of a
83 lexical-analysis phase feeding the parser, driven by a DFA, operating over the
84 disjunction of all such string table entries.
85
86 When such a string enclosed in double-quotes (`"`) occurs inside the grammar,
87 it is an implicit reference to a single member of such a string table
88 production. See [tokens](#tokens) for more information.
89
90 # Lexical structure
91
92 ## Input format
93
94 Rust input is interpreted as a sequence of Unicode codepoints encoded in UTF-8.
95 Most Rust grammar rules are defined in terms of printable ASCII-range
96 codepoints, but a small number are defined in terms of Unicode properties or
97 explicit codepoint lists. [^inputformat]
98
99 [^inputformat]: Substitute definitions for the special Unicode productions are
100   provided to the grammar verifier, restricted to ASCII range, when verifying the
101   grammar in this document.
102
103 ## Special Unicode Productions
104
105 The following productions in the Rust grammar are defined in terms of Unicode
106 properties: `ident`, `non_null`, `non_star`, `non_eol`, `non_slash_or_star`,
107 `non_single_quote` and `non_double_quote`.
108
109 ### Identifiers
110
111 The `ident` production is any nonempty Unicode string of the following form:
112
113 - The first character has property `XID_start`
114 - The remaining characters have property `XID_continue`
115
116 that does _not_ occur in the set of [keywords](#keywords).
117
118 > **Note**: `XID_start` and `XID_continue` as character properties cover the
119 > character ranges used to form the more familiar C and Java language-family
120 > identifiers.
121
122 ### Delimiter-restricted productions
123
124 Some productions are defined by exclusion of particular Unicode characters:
125
126 - `non_null` is any single Unicode character aside from `U+0000` (null)
127 - `non_eol` is `non_null` restricted to exclude `U+000A` (`'\n'`)
128 - `non_star` is `non_null` restricted to exclude `U+002A` (`*`)
129 - `non_slash_or_star` is `non_null` restricted to exclude `U+002F` (`/`) and `U+002A` (`*`)
130 - `non_single_quote` is `non_null` restricted to exclude `U+0027`  (`'`)
131 - `non_double_quote` is `non_null` restricted to exclude `U+0022` (`"`)
132
133 ## Comments
134
135 ```{.ebnf .gram}
136 comment : block_comment | line_comment ;
137 block_comment : "/*" block_comment_body * "*/" ;
138 block_comment_body : [block_comment | character] * ;
139 line_comment : "//" non_eol * ;
140 ```
141
142 Comments in Rust code follow the general C++ style of line and block-comment
143 forms. Nested block comments are supported.
144
145 Line comments beginning with exactly _three_ slashes (`///`), and block
146 comments beginning with exactly one repeated asterisk in the block-open
147 sequence (`/**`), are interpreted as a special syntax for `doc`
148 [attributes](#attributes). That is, they are equivalent to writing
149 `#[doc="..."]` around the body of the comment (this includes the comment
150 characters themselves, ie `/// Foo` turns into `#[doc="/// Foo"]`).
151
152 Line comments beginning with `//!` and block comments beginning with `/*!` are
153 doc comments that apply to the parent of the comment, rather than the item
154 that follows.  That is, they are equivalent to writing `#![doc="..."]` around
155 the body of the comment. `//!` comments are usually used to display
156 information on the crate index page.
157
158 Non-doc comments are interpreted as a form of whitespace.
159
160 ## Whitespace
161
162 ```{.ebnf .gram}
163 whitespace_char : '\x20' | '\x09' | '\x0a' | '\x0d' ;
164 whitespace : [ whitespace_char | comment ] + ;
165 ```
166
167 The `whitespace_char` production is any nonempty Unicode string consisting of
168 any of the following Unicode characters: `U+0020` (space, `' '`), `U+0009`
169 (tab, `'\t'`), `U+000A` (LF, `'\n'`), `U+000D` (CR, `'\r'`).
170
171 Rust is a "free-form" language, meaning that all forms of whitespace serve only
172 to separate _tokens_ in the grammar, and have no semantic significance.
173
174 A Rust program has identical meaning if each whitespace element is replaced
175 with any other legal whitespace element, such as a single space character.
176
177 ## Tokens
178
179 ```{.ebnf .gram}
180 simple_token : keyword | unop | binop ;
181 token : simple_token | ident | literal | symbol | whitespace token ;
182 ```
183
184 Tokens are primitive productions in the grammar defined by regular
185 (non-recursive) languages. "Simple" tokens are given in [string table
186 production](#string-table-productions) form, and occur in the rest of the
187 grammar as double-quoted strings. Other tokens have exact rules given.
188
189 ### Keywords
190
191 <p id="keyword-table-marker"></p>
192
193 |          |          |          |          |         |
194 |----------|----------|----------|----------|---------|
195 | abstract | alignof  | as       | become   | box     |
196 | break    | const    | continue | crate    | do      |
197 | else     | enum     | extern   | false    | final   |
198 | fn       | for      | if       | impl     | in      |
199 | let      | loop     | macro    | match    | mod     |
200 | move     | mut      | offsetof | override | priv    |
201 | proc     | pub      | pure     | ref      | return  |
202 | Self     | self     | sizeof   | static   | struct  |
203 | super    | trait    | true     | type     | typeof  |
204 | unsafe   | unsized  | use      | virtual  | where   |
205 | while    | yield    |          |          |         |
206
207
208 Each of these keywords has special meaning in its grammar, and all of them are
209 excluded from the `ident` rule.
210
211 Note that some of these keywords are reserved, and do not currently do
212 anything.
213
214 ### Literals
215
216 A literal is an expression consisting of a single token, rather than a sequence
217 of tokens, that immediately and directly denotes the value it evaluates to,
218 rather than referring to it by name or some other evaluation rule. A literal is
219 a form of constant expression, so is evaluated (primarily) at compile time.
220
221 ```{.ebnf .gram}
222 lit_suffix : ident;
223 literal : [ string_lit | char_lit | byte_string_lit | byte_lit | num_lit ] lit_suffix ?;
224 ```
225
226 The optional suffix is only used for certain numeric literals, but is
227 reserved for future extension, that is, the above gives the lexical
228 grammar, but a Rust parser will reject everything but the 12 special
229 cases mentioned in [Number literals](#number-literals) below.
230
231 #### Examples
232
233 ##### Characters and strings
234
235 |                                              | Example         | `#` sets   | Characters  | Escapes             |
236 |----------------------------------------------|-----------------|------------|-------------|---------------------|
237 | [Character](#character-literals)             | `'H'`           | `N/A`      | All Unicode | `\'` & [Byte](#byte-escapes) & [Unicode](#unicode-escapes) |
238 | [String](#string-literals)                   | `"hello"`       | `N/A`      | All Unicode | `\"` & [Byte](#byte-escapes) & [Unicode](#unicode-escapes) |
239 | [Raw](#raw-string-literals)                  | `r#"hello"#`    | `0...`     | All Unicode | `N/A`                                                      |
240 | [Byte](#byte-literals)                       | `b'H'`          | `N/A`      | All ASCII   | `\'` & [Byte](#byte-escapes)                               |
241 | [Byte string](#byte-string-literals)         | `b"hello"`      | `N/A`      | All ASCII   | `\"` & [Byte](#byte-escapes)                               |
242 | [Raw byte string](#raw-byte-string-literals) | `br#"hello"#`   | `0...`     | All ASCII   | `N/A`                                                      |
243
244 ##### Byte escapes
245
246 |   | Name |
247 |---|------|
248 | `\x7F` | 8-bit character code (exactly 2 digits) |
249 | `\n` | Newline |
250 | `\r` | Carriage return |
251 | `\t` | Tab |
252 | `\\` | Backslash |
253
254 ##### Unicode escapes
255 |   | Name |
256 |---|------|
257 | `\u{7FFF}` | 24-bit Unicode character code (up to 6 digits) |
258
259 ##### Numbers
260
261 | [Number literals](#number-literals)`*` | Example | Exponentiation | Suffixes |
262 |----------------------------------------|---------|----------------|----------|
263 | Decimal integer | `98_222` | `N/A` | Integer suffixes |
264 | Hex integer | `0xff` | `N/A` | Integer suffixes |
265 | Octal integer | `0o77` | `N/A` | Integer suffixes |
266 | Binary integer | `0b1111_0000` | `N/A` | Integer suffixes |
267 | Floating-point | `123.0E+77` | `Optional` | Floating-point suffixes |
268
269 `*` All number literals allow `_` as a visual separator: `1_234.0E+18f64`
270
271 ##### Suffixes
272 | Integer | Floating-point |
273 |---------|----------------|
274 | `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `is` (`isize`), `us` (`usize`) | `f32`, `f64` |
275
276 #### Character and string literals
277
278 ```{.ebnf .gram}
279 char_lit : '\x27' char_body '\x27' ;
280 string_lit : '"' string_body * '"' | 'r' raw_string ;
281
282 char_body : non_single_quote
283           | '\x5c' [ '\x27' | common_escape | unicode_escape ] ;
284
285 string_body : non_double_quote
286             | '\x5c' [ '\x22' | common_escape | unicode_escape ] ;
287 raw_string : '"' raw_string_body '"' | '#' raw_string '#' ;
288
289 common_escape : '\x5c'
290               | 'n' | 'r' | 't' | '0'
291               | 'x' hex_digit 2
292
293 unicode_escape : 'u' '{' hex_digit+ 6 '}';
294
295 hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
296           | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
297           | dec_digit ;
298 oct_digit : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' ;
299 dec_digit : '0' | nonzero_dec ;
300 nonzero_dec: '1' | '2' | '3' | '4'
301            | '5' | '6' | '7' | '8' | '9' ;
302 ```
303
304 ##### Character literals
305
306 A _character literal_ is a single Unicode character enclosed within two
307 `U+0027` (single-quote) characters, with the exception of `U+0027` itself,
308 which must be _escaped_ by a preceding `U+005C` character (`\`).
309
310 ##### String literals
311
312 A _string literal_ is a sequence of any Unicode characters enclosed within two
313 `U+0022` (double-quote) characters, with the exception of `U+0022` itself,
314 which must be _escaped_ by a preceding `U+005C` character (`\`), or a _raw
315 string literal_.
316
317 A multi-line string literal may be defined by terminating each line with a
318 `U+005C` character (`\`) immediately before the newline. This causes the
319 `U+005C` character, the newline, and all whitespace at the beginning of the
320 next line to be ignored.
321
322 ```rust
323 let a = "foobar";
324 let b = "foo\
325          bar";
326
327 assert_eq!(a,b);
328 ```
329
330 ##### Character escapes
331
332 Some additional _escapes_ are available in either character or non-raw string
333 literals. An escape starts with a `U+005C` (`\`) and continues with one of the
334 following forms:
335
336 * An _8-bit codepoint escape_ escape starts with `U+0078` (`x`) and is
337   followed by exactly two _hex digits_. It denotes the Unicode codepoint
338   equal to the provided hex value.
339 * A _24-bit codepoint escape_ starts with `U+0075` (`u`) and is followed
340   by up to six _hex digits_ surrounded by braces `U+007B` (`{`) and `U+007D`
341   (`}`). It denotes the Unicode codepoint equal to the provided hex value.
342 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
343   (`r`), or `U+0074` (`t`), denoting the unicode values `U+000A` (LF),
344   `U+000D` (CR) or `U+0009` (HT) respectively.
345 * The _backslash escape_ is the character `U+005C` (`\`) which must be
346   escaped in order to denote *itself*.
347
348 ##### Raw string literals
349
350 Raw string literals do not process any escapes. They start with the character
351 `U+0072` (`r`), followed by zero or more of the character `U+0023` (`#`) and a
352 `U+0022` (double-quote) character. The _raw string body_ is not defined in the
353 EBNF grammar above: it can contain any sequence of Unicode characters and is
354 terminated only by another `U+0022` (double-quote) character, followed by the
355 same number of `U+0023` (`#`) characters that preceded the opening `U+0022`
356 (double-quote) character.
357
358 All Unicode characters contained in the raw string body represent themselves,
359 the characters `U+0022` (double-quote) (except when followed by at least as
360 many `U+0023` (`#`) characters as were used to start the raw string literal) or
361 `U+005C` (`\`) do not have any special meaning.
362
363 Examples for string literals:
364
365 ```
366 "foo"; r"foo";                     // foo
367 "\"foo\""; r#""foo""#;             // "foo"
368
369 "foo #\"# bar";
370 r##"foo #"# bar"##;                // foo #"# bar
371
372 "\x52"; "R"; r"R";                 // R
373 "\\x52"; r"\x52";                  // \x52
374 ```
375
376 #### Byte and byte string literals
377
378 ```{.ebnf .gram}
379 byte_lit : "b\x27" byte_body '\x27' ;
380 byte_string_lit : "b\x22" string_body * '\x22' | "br" raw_byte_string ;
381
382 byte_body : ascii_non_single_quote
383           | '\x5c' [ '\x27' | common_escape ] ;
384
385 byte_string_body : ascii_non_double_quote
386             | '\x5c' [ '\x22' | common_escape ] ;
387 raw_byte_string : '"' raw_byte_string_body '"' | '#' raw_byte_string '#' ;
388
389 ```
390
391 ##### Byte literals
392
393 A _byte literal_ is a single ASCII character (in the `U+0000` to `U+007F`
394 range) enclosed within two `U+0027` (single-quote) characters, with the
395 exception of `U+0027` itself, which must be _escaped_ by a preceding U+005C
396 character (`\`), or a single _escape_. It is equivalent to a `u8` unsigned
397 8-bit integer _number literal_.
398
399 ##### Byte string literals
400
401 A non-raw _byte string literal_ is a sequence of ASCII characters and _escapes_,
402 preceded by the characters `U+0062` (`b`) and `U+0022` (double-quote), and
403 followed by the character `U+0022`. If the character `U+0022` is present within
404 the literal, it must be _escaped_ by a preceding `U+005C` (`\`) character.
405 Alternatively, a byte string literal can be a _raw byte string literal_, defined
406 below. A byte string literal is equivalent to a `&'static [u8]` borrowed array
407 of unsigned 8-bit integers.
408
409 Some additional _escapes_ are available in either byte or non-raw byte string
410 literals. An escape starts with a `U+005C` (`\`) and continues with one of the
411 following forms:
412
413 * An _byte escape_ escape starts with `U+0078` (`x`) and is
414   followed by exactly two _hex digits_. It denotes the byte
415   equal to the provided hex value.
416 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
417   (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF),
418   `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively.
419 * The _backslash escape_ is the character `U+005C` (`\`) which must be
420   escaped in order to denote its ASCII encoding `0x5C`.
421
422 ##### Raw byte string literals
423
424 Raw byte string literals do not process any escapes. They start with the
425 character `U+0062` (`b`), followed by `U+0072` (`r`), followed by zero or more
426 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character. The
427 _raw string body_ is not defined in the EBNF grammar above: it can contain any
428 sequence of ASCII characters and is terminated only by another `U+0022`
429 (double-quote) character, followed by the same number of `U+0023` (`#`)
430 characters that preceded the opening `U+0022` (double-quote) character. A raw
431 byte string literal can not contain any non-ASCII byte.
432
433 All characters contained in the raw string body represent their ASCII encoding,
434 the characters `U+0022` (double-quote) (except when followed by at least as
435 many `U+0023` (`#`) characters as were used to start the raw string literal) or
436 `U+005C` (`\`) do not have any special meaning.
437
438 Examples for byte string literals:
439
440 ```
441 b"foo"; br"foo";                     // foo
442 b"\"foo\""; br#""foo""#;             // "foo"
443
444 b"foo #\"# bar";
445 br##"foo #"# bar"##;                 // foo #"# bar
446
447 b"\x52"; b"R"; br"R";                // R
448 b"\\x52"; br"\x52";                  // \x52
449 ```
450
451 #### Number literals
452
453 ```{.ebnf .gram}
454 num_lit : nonzero_dec [ dec_digit | '_' ] * float_suffix ?
455         | '0' [       [ dec_digit | '_' ] * float_suffix ?
456               | 'b'   [ '1' | '0' | '_' ] +
457               | 'o'   [ oct_digit | '_' ] +
458               | 'x'   [ hex_digit | '_' ] +  ] ;
459
460 float_suffix : [ exponent | '.' dec_lit exponent ? ] ? ;
461
462 exponent : ['E' | 'e'] ['-' | '+' ] ? dec_lit ;
463 dec_lit : [ dec_digit | '_' ] + ;
464 ```
465
466 A _number literal_ is either an _integer literal_ or a _floating-point
467 literal_. The grammar for recognizing the two kinds of literals is mixed.
468
469 ##### Integer literals
470
471 An _integer literal_ has one of four forms:
472
473 * A _decimal literal_ starts with a *decimal digit* and continues with any
474   mixture of *decimal digits* and _underscores_.
475 * A _hex literal_ starts with the character sequence `U+0030` `U+0078`
476   (`0x`) and continues as any mixture of hex digits and underscores.
477 * An _octal literal_ starts with the character sequence `U+0030` `U+006F`
478   (`0o`) and continues as any mixture of octal digits and underscores.
479 * A _binary literal_ starts with the character sequence `U+0030` `U+0062`
480   (`0b`) and continues as any mixture of binary digits and underscores.
481
482 Like any literal, an integer literal may be followed (immediately,
483 without any spaces) by an _integer suffix_, which forcibly sets the
484 type of the literal. The integer suffix must be the name of one of the
485 integral types: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`,
486 `isize`, or `usize`.
487
488 The type of an _unsuffixed_ integer literal is determined by type inference.
489 If an integer type can be _uniquely_ determined from the surrounding program
490 context, the unsuffixed integer literal has that type. If the program context
491 underconstrains the type, it defaults to the signed 32-bit integer `i32`; if
492 the program context overconstrains the type, it is considered a static type
493 error.
494
495 Examples of integer literals of various forms:
496
497 ```
498 123i32;                            // type i32
499 123u32;                            // type u32
500 123_u32;                           // type u32
501 0xff_u8;                           // type u8
502 0o70_i16;                          // type i16
503 0b1111_1111_1001_0000_i32;         // type i32
504 0usize;                            // type usize
505 ```
506
507 ##### Floating-point literals
508
509 A _floating-point literal_ has one of two forms:
510
511 * A _decimal literal_ followed by a period character `U+002E` (`.`). This is
512   optionally followed by another decimal literal, with an optional _exponent_.
513 * A single _decimal literal_ followed by an _exponent_.
514
515 By default, a floating-point literal has a generic type, and, like integer
516 literals, the type must be uniquely determined from the context. There are two valid
517 _floating-point suffixes_, `f32` and `f64` (the 32-bit and 64-bit floating point
518 types), which explicitly determine the type of the literal.
519
520 Examples of floating-point literals of various forms:
521
522 ```
523 123.0f64;        // type f64
524 0.1f64;          // type f64
525 0.1f32;          // type f32
526 12E+99_f64;      // type f64
527 let x: f64 = 2.; // type f64
528 ```
529
530 This last example is different because it is not possible to use the suffix
531 syntax with a floating point literal ending in a period. `2.f64` would attempt
532 to call a method named `f64` on `2`.
533
534 The representation semantics of floating-point numbers are described in
535 ["Machine Types"](#machine-types).
536
537 #### Boolean literals
538
539 The two values of the boolean type are written `true` and `false`.
540
541 ### Symbols
542
543 ```{.ebnf .gram}
544 symbol : "::" | "->"
545        | '#' | '[' | ']' | '(' | ')' | '{' | '}'
546        | ',' | ';' ;
547 ```
548
549 Symbols are a general class of printable [token](#tokens) that play structural
550 roles in a variety of grammar productions. They are catalogued here for
551 completeness as the set of remaining miscellaneous printable tokens that do not
552 otherwise appear as [unary operators](#unary-operator-expressions), [binary
553 operators](#binary-operator-expressions), or [keywords](#keywords).
554
555
556 ## Paths
557
558 ```{.ebnf .gram}
559 expr_path : [ "::" ] ident [ "::" expr_path_tail ] + ;
560 expr_path_tail : '<' type_expr [ ',' type_expr ] + '>'
561                | expr_path ;
562
563 type_path : ident [ type_path_tail ] + ;
564 type_path_tail : '<' type_expr [ ',' type_expr ] + '>'
565                | "::" type_path ;
566 ```
567
568 A _path_ is a sequence of one or more path components _logically_ separated by
569 a namespace qualifier (`::`). If a path consists of only one component, it may
570 refer to either an [item](#items) or a [variable](#variables) in a local control
571 scope. If a path has multiple components, it refers to an item.
572
573 Every item has a _canonical path_ within its crate, but the path naming an item
574 is only meaningful within a given crate. There is no global namespace across
575 crates; an item's canonical path merely identifies it within the crate.
576
577 Two examples of simple paths consisting of only identifier components:
578
579 ```{.ignore}
580 x;
581 x::y::z;
582 ```
583
584 Path components are usually [identifiers](#identifiers), but the trailing
585 component of a path may be an angle-bracket-enclosed list of type arguments. In
586 [expression](#expressions) context, the type argument list is given after a
587 final (`::`) namespace qualifier in order to disambiguate it from a relational
588 expression involving the less-than symbol (`<`). In type expression context,
589 the final namespace qualifier is omitted.
590
591 Two examples of paths with type arguments:
592
593 ```
594 # struct HashMap<K, V>(K,V);
595 # fn f() {
596 # fn id<T>(t: T) -> T { t }
597 type T = HashMap<i32,String>; // Type arguments used in a type expression
598 let x  = id::<i32>(10);       // Type arguments used in a call expression
599 # }
600 ```
601
602 Paths can be denoted with various leading qualifiers to change the meaning of
603 how it is resolved:
604
605 * Paths starting with `::` are considered to be global paths where the
606   components of the path start being resolved from the crate root. Each
607   identifier in the path must resolve to an item.
608
609 ```rust
610 mod a {
611     pub fn foo() {}
612 }
613 mod b {
614     pub fn foo() {
615         ::a::foo(); // call a's foo function
616     }
617 }
618 # fn main() {}
619 ```
620
621 * Paths starting with the keyword `super` begin resolution relative to the
622   parent module. Each further identifier must resolve to an item.
623
624 ```rust
625 mod a {
626     pub fn foo() {}
627 }
628 mod b {
629     pub fn foo() {
630         super::a::foo(); // call a's foo function
631     }
632 }
633 # fn main() {}
634 ```
635
636 * Paths starting with the keyword `self` begin resolution relative to the
637   current module. Each further identifier must resolve to an item.
638
639 ```rust
640 fn foo() {}
641 fn bar() {
642     self::foo();
643 }
644 # fn main() {}
645 ```
646
647 # Syntax extensions
648
649 A number of minor features of Rust are not central enough to have their own
650 syntax, and yet are not implementable as functions. Instead, they are given
651 names, and invoked through a consistent syntax: `some_extension!(...)`.
652
653 Users of `rustc` can define new syntax extensions in two ways:
654
655 * [Compiler plugins][plugin] can include arbitrary
656   Rust code that manipulates syntax trees at compile time.
657
658 * [Macros](book/macros.html) define new syntax in a higher-level,
659   declarative way.
660
661 ## Macros
662
663 ```{.ebnf .gram}
664 expr_macro_rules : "macro_rules" '!' ident '(' macro_rule * ')' ;
665 macro_rule : '(' matcher * ')' "=>" '(' transcriber * ')' ';' ;
666 matcher : '(' matcher * ')' | '[' matcher * ']'
667         | '{' matcher * '}' | '$' ident ':' ident
668         | '$' '(' matcher * ')' sep_token? [ '*' | '+' ]
669         | non_special_token ;
670 transcriber : '(' transcriber * ')' | '[' transcriber * ']'
671             | '{' transcriber * '}' | '$' ident
672             | '$' '(' transcriber * ')' sep_token? [ '*' | '+' ]
673             | non_special_token ;
674 ```
675
676 `macro_rules` allows users to define syntax extension in a declarative way.  We
677 call such extensions "macros by example" or simply "macros" â€” to be distinguished
678 from the "procedural macros" defined in [compiler plugins][plugin].
679
680 Currently, macros can expand to expressions, statements, items, or patterns.
681
682 (A `sep_token` is any token other than `*` and `+`. A `non_special_token` is
683 any token other than a delimiter or `$`.)
684
685 The macro expander looks up macro invocations by name, and tries each macro
686 rule in turn. It transcribes the first successful match. Matching and
687 transcription are closely related to each other, and we will describe them
688 together.
689
690 ### Macro By Example
691
692 The macro expander matches and transcribes every token that does not begin with
693 a `$` literally, including delimiters. For parsing reasons, delimiters must be
694 balanced, but they are otherwise not special.
695
696 In the matcher, `$` _name_ `:` _designator_ matches the nonterminal in the Rust
697 syntax named by _designator_. Valid designators are `item`, `block`, `stmt`,
698 `pat`, `expr`, `ty` (type), `ident`, `path`, `tt` (either side of the `=>`
699 in macro rules). In the transcriber, the designator is already known, and so
700 only the name of a matched nonterminal comes after the dollar sign.
701
702 In both the matcher and transcriber, the Kleene star-like operator indicates
703 repetition. The Kleene star operator consists of `$` and parens, optionally
704 followed by a separator token, followed by `*` or `+`. `*` means zero or more
705 repetitions, `+` means at least one repetition. The parens are not matched or
706 transcribed. On the matcher side, a name is bound to _all_ of the names it
707 matches, in a structure that mimics the structure of the repetition encountered
708 on a successful match. The job of the transcriber is to sort that structure
709 out.
710
711 The rules for transcription of these repetitions are called "Macro By Example".
712 Essentially, one "layer" of repetition is discharged at a time, and all of them
713 must be discharged by the time a name is transcribed. Therefore, `( $( $i:ident
714 ),* ) => ( $i )` is an invalid macro, but `( $( $i:ident ),* ) => ( $( $i:ident
715 ),*  )` is acceptable (if trivial).
716
717 When Macro By Example encounters a repetition, it examines all of the `$`
718 _name_ s that occur in its body. At the "current layer", they all must repeat
719 the same number of times, so ` ( $( $i:ident ),* ; $( $j:ident ),* ) => ( $(
720 ($i,$j) ),* )` is valid if given the argument `(a,b,c ; d,e,f)`, but not
721 `(a,b,c ; d,e)`. The repetition walks through the choices at that layer in
722 lockstep, so the former input transcribes to `( (a,d), (b,e), (c,f) )`.
723
724 Nested repetitions are allowed.
725
726 ### Parsing limitations
727
728 The parser used by the macro system is reasonably powerful, but the parsing of
729 Rust syntax is restricted in two ways:
730
731 1. The parser will always parse as much as possible. If it attempts to match
732    `$i:expr [ , ]` against `8 [ , ]`, it will attempt to parse `i` as an array
733    index operation and fail. Adding a separator can solve this problem.
734 2. The parser must have eliminated all ambiguity by the time it reaches a `$`
735    _name_ `:` _designator_. This requirement most often affects name-designator
736    pairs when they occur at the beginning of, or immediately after, a `$(...)*`;
737    requiring a distinctive token in front can solve the problem.
738
739 # Crates and source files
740
741 Rust is a *compiled* language. Its semantics obey a *phase distinction* between
742 compile-time and run-time. Those semantic rules that have a *static
743 interpretation* govern the success or failure of compilation. Those semantics
744 that have a *dynamic interpretation* govern the behavior of the program at
745 run-time.
746
747 The compilation model centers on artifacts called _crates_. Each compilation
748 processes a single crate in source form, and if successful, produces a single
749 crate in binary form: either an executable or a library.[^cratesourcefile]
750
751 [^cratesourcefile]: A crate is somewhat analogous to an *assembly* in the
752     ECMA-335 CLI model, a *library* in the SML/NJ Compilation Manager, a *unit*
753     in the Owens and Flatt module system, or a *configuration* in Mesa.
754
755 A _crate_ is a unit of compilation and linking, as well as versioning,
756 distribution and runtime loading. A crate contains a _tree_ of nested
757 [module](#modules) scopes. The top level of this tree is a module that is
758 anonymous (from the point of view of paths within the module) and any item
759 within a crate has a canonical [module path](#paths) denoting its location
760 within the crate's module tree.
761
762 The Rust compiler is always invoked with a single source file as input, and
763 always produces a single output crate. The processing of that source file may
764 result in other source files being loaded as modules. Source files have the
765 extension `.rs`.
766
767 A Rust source file describes a module, the name and location of which &mdash;
768 in the module tree of the current crate &mdash; are defined from outside the
769 source file: either by an explicit `mod_item` in a referencing source file, or
770 by the name of the crate itself.
771
772 Each source file contains a sequence of zero or more `item` definitions, and
773 may optionally begin with any number of `attributes` that apply to the
774 containing module. Attributes on the anonymous crate module define important
775 metadata that influences the behavior of the compiler.
776
777 ```no_run
778 // Crate name
779 #![crate_name = "projx"]
780
781 // Specify the output type
782 #![crate_type = "lib"]
783
784 // Turn on a warning
785 #![warn(non_camel_case_types)]
786 ```
787
788 A crate that contains a `main` function can be compiled to an executable. If a
789 `main` function is present, its return type must be [`unit`](#primitive-types)
790 and it must take no arguments.
791
792 # Items and attributes
793
794 Crates contain [items](#items), each of which may have some number of
795 [attributes](#attributes) attached to it.
796
797 ## Items
798
799 ```{.ebnf .gram}
800 item : extern_crate_decl | use_decl | mod_item | fn_item | type_item
801      | struct_item | enum_item | static_item | trait_item | impl_item
802      | extern_block ;
803 ```
804
805 An _item_ is a component of a crate. Items are organized within a crate by a
806 nested set of [modules](#modules). Every crate has a single "outermost"
807 anonymous module; all further items within the crate have [paths](#paths)
808 within the module tree of the crate.
809
810 Items are entirely determined at compile-time, generally remain fixed during
811 execution, and may reside in read-only memory.
812
813 There are several kinds of item:
814
815 * [`extern crate` declarations](#extern-crate-declarations)
816 * [`use` declarations](#use-declarations)
817 * [modules](#modules)
818 * [functions](#functions)
819 * [type definitions](#type-definitions)
820 * [structures](#structures)
821 * [enumerations](#enumerations)
822 * [static items](#static-items)
823 * [traits](#traits)
824 * [implementations](#implementations)
825
826 Some items form an implicit scope for the declaration of sub-items. In other
827 words, within a function or module, declarations of items can (in many cases)
828 be mixed with the statements, control blocks, and similar artifacts that
829 otherwise compose the item body. The meaning of these scoped items is the same
830 as if the item was declared outside the scope &mdash; it is still a static item
831 &mdash; except that the item's *path name* within the module namespace is
832 qualified by the name of the enclosing item, or is private to the enclosing
833 item (in the case of functions). The grammar specifies the exact locations in
834 which sub-item declarations may appear.
835
836 ### Type Parameters
837
838 All items except modules may be *parameterized* by type. Type parameters are
839 given as a comma-separated list of identifiers enclosed in angle brackets
840 (`<...>`), after the name of the item and before its definition. The type
841 parameters of an item are considered "part of the name", not part of the type
842 of the item. A referencing [path](#paths) must (in principle) provide type
843 arguments as a list of comma-separated types enclosed within angle brackets, in
844 order to refer to the type-parameterized item. In practice, the type-inference
845 system can usually infer such argument types from context. There are no
846 general type-parametric types, only type-parametric items. That is, Rust has
847 no notion of type abstraction: there are no first-class "forall" types.
848
849 ### Modules
850
851 ```{.ebnf .gram}
852 mod_item : "mod" ident ( ';' | '{' mod '}' );
853 mod : item * ;
854 ```
855
856 A module is a container for zero or more [items](#items).
857
858 A _module item_ is a module, surrounded in braces, named, and prefixed with the
859 keyword `mod`. A module item introduces a new, named module into the tree of
860 modules making up a crate. Modules can nest arbitrarily.
861
862 An example of a module:
863
864 ```
865 mod math {
866     type Complex = (f64, f64);
867     fn sin(f: f64) -> f64 {
868         /* ... */
869 # panic!();
870     }
871     fn cos(f: f64) -> f64 {
872         /* ... */
873 # panic!();
874     }
875     fn tan(f: f64) -> f64 {
876         /* ... */
877 # panic!();
878     }
879 }
880 ```
881
882 Modules and types share the same namespace. Declaring a named type with
883 the same name as a module in scope is forbidden: that is, a type definition,
884 trait, struct, enumeration, or type parameter can't shadow the name of a module
885 in scope, or vice versa.
886
887 A module without a body is loaded from an external file, by default with the
888 same name as the module, plus the `.rs` extension. When a nested submodule is
889 loaded from an external file, it is loaded from a subdirectory path that
890 mirrors the module hierarchy.
891
892 ```{.ignore}
893 // Load the `vec` module from `vec.rs`
894 mod vec;
895
896 mod thread {
897     // Load the `local_data` module from `thread/local_data.rs`
898     mod local_data;
899 }
900 ```
901
902 The directories and files used for loading external file modules can be
903 influenced with the `path` attribute.
904
905 ```{.ignore}
906 #[path = "thread_files"]
907 mod thread {
908     // Load the `local_data` module from `thread_files/tls.rs`
909     #[path = "tls.rs"]
910     mod local_data;
911 }
912 ```
913
914 ##### Extern crate declarations
915
916 ```{.ebnf .gram}
917 extern_crate_decl : "extern" "crate" crate_name
918 crate_name: ident | ( string_lit "as" ident )
919 ```
920
921 An _`extern crate` declaration_ specifies a dependency on an external crate.
922 The external crate is then bound into the declaring scope as the `ident`
923 provided in the `extern_crate_decl`.
924
925 The external crate is resolved to a specific `soname` at compile time, and a
926 runtime linkage requirement to that `soname` is passed to the linker for
927 loading at runtime. The `soname` is resolved at compile time by scanning the
928 compiler's library path and matching the optional `crateid` provided as a
929 string literal against the `crateid` attributes that were declared on the
930 external crate when it was compiled. If no `crateid` is provided, a default
931 `name` attribute is assumed, equal to the `ident` given in the
932 `extern_crate_decl`.
933
934 Three examples of `extern crate` declarations:
935
936 ```{.ignore}
937 extern crate pcre;
938
939 extern crate std; // equivalent to: extern crate std as std;
940
941 extern crate std as ruststd; // linking to 'std' under another name
942 ```
943
944 ##### Use declarations
945
946 ```{.ebnf .gram}
947 use_decl : "pub" ? "use" [ path "as" ident
948                           | path_glob ] ;
949
950 path_glob : ident [ "::" [ path_glob
951                           | '*' ] ] ?
952           | '{' path_item [ ',' path_item ] * '}' ;
953
954 path_item : ident | "self" ;
955 ```
956
957 A _use declaration_ creates one or more local name bindings synonymous with
958 some other [path](#paths). Usually a `use` declaration is used to shorten the
959 path required to refer to a module item. These declarations may appear at the
960 top of [modules](#modules) and [blocks](#blocks).
961
962 > **Note**: Unlike in many languages,
963 > `use` declarations in Rust do *not* declare linkage dependency with external crates.
964 > Rather, [`extern crate` declarations](#extern-crate-declarations) declare linkage dependencies.
965
966 Use declarations support a number of convenient shortcuts:
967
968 * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`
969 * Simultaneously binding a list of paths differing only in their final element,
970   using the glob-like brace syntax `use a::b::{c,d,e,f};`
971 * Binding all paths matching a given prefix, using the asterisk wildcard syntax
972   `use a::b::*;`
973 * Simultaneously binding a list of paths differing only in their final element
974   and their immediate parent module, using the `self` keyword, such as
975   `use a::b::{self, c, d};`
976
977 An example of `use` declarations:
978
979 ```rust
980 use std::option::Option::{Some, None};
981 use std::collections::hash_map::{self, HashMap};
982
983 fn foo<T>(_: T){}
984 fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}
985
986 fn main() {
987     // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
988     // std::option::Option::None]);'
989     foo(vec![Some(1.0f64), None]);
990
991     // Both `hash_map` and `HashMap` are in scope.
992     let map1 = HashMap::new();
993     let map2 = hash_map::HashMap::new();
994     bar(map1, map2);
995 }
996 ```
997
998 Like items, `use` declarations are private to the containing module, by
999 default. Also like items, a `use` declaration can be public, if qualified by
1000 the `pub` keyword. Such a `use` declaration serves to _re-export_ a name. A
1001 public `use` declaration can therefore _redirect_ some public name to a
1002 different target definition: even a definition with a private canonical path,
1003 inside a different module. If a sequence of such redirections form a cycle or
1004 cannot be resolved unambiguously, they represent a compile-time error.
1005
1006 An example of re-exporting:
1007
1008 ```
1009 # fn main() { }
1010 mod quux {
1011     pub use quux::foo::{bar, baz};
1012
1013     pub mod foo {
1014         pub fn bar() { }
1015         pub fn baz() { }
1016     }
1017 }
1018 ```
1019
1020 In this example, the module `quux` re-exports two public names defined in
1021 `foo`.
1022
1023 Also note that the paths contained in `use` items are relative to the crate
1024 root. So, in the previous example, the `use` refers to `quux::foo::{bar,
1025 baz}`, and not simply to `foo::{bar, baz}`. This also means that top-level
1026 module declarations should be at the crate root if direct usage of the declared
1027 modules within `use` items is desired. It is also possible to use `self` and
1028 `super` at the beginning of a `use` item to refer to the current and direct
1029 parent modules respectively. All rules regarding accessing declared modules in
1030 `use` declarations applies to both module declarations and `extern crate`
1031 declarations.
1032
1033 An example of what will and will not work for `use` items:
1034
1035 ```
1036 # #![allow(unused_imports)]
1037 use foo::baz::foobaz;    // good: foo is at the root of the crate
1038
1039 mod foo {
1040
1041     mod example {
1042         pub mod iter {}
1043     }
1044
1045     use foo::example::iter; // good: foo is at crate root
1046 //  use example::iter;      // bad:  core is not at the crate root
1047     use self::baz::foobaz;  // good: self refers to module 'foo'
1048     use foo::bar::foobar;   // good: foo is at crate root
1049
1050     pub mod bar {
1051         pub fn foobar() { }
1052     }
1053
1054     pub mod baz {
1055         use super::bar::foobar; // good: super refers to module 'foo'
1056         pub fn foobaz() { }
1057     }
1058 }
1059
1060 fn main() {}
1061 ```
1062
1063 ### Functions
1064
1065 A _function item_ defines a sequence of [statements](#statements) and an
1066 optional final [expression](#expressions), along with a name and a set of
1067 parameters. Functions are declared with the keyword `fn`. Functions declare a
1068 set of *input* [*variables*](#variables) as parameters, through which the caller
1069 passes arguments into the function, and the *output* [*type*](#types)
1070 of the value the function will return to its caller on completion.
1071
1072 A function may also be copied into a first-class *value*, in which case the
1073 value has the corresponding [*function type*](#function-types), and can be used
1074 otherwise exactly as a function item (with a minor additional cost of calling
1075 the function indirectly).
1076
1077 Every control path in a function logically ends with a `return` expression or a
1078 diverging expression. If the outermost block of a function has a
1079 value-producing expression in its final-expression position, that expression is
1080 interpreted as an implicit `return` expression applied to the final-expression.
1081
1082 An example of a function:
1083
1084 ```
1085 fn add(x: i32, y: i32) -> i32 {
1086     return x + y;
1087 }
1088 ```
1089
1090 As with `let` bindings, function arguments are irrefutable patterns, so any
1091 pattern that is valid in a let binding is also valid as an argument.
1092
1093 ```
1094 fn first((value, _): (i32, i32)) -> i32 { value }
1095 ```
1096
1097
1098 #### Generic functions
1099
1100 A _generic function_ allows one or more _parameterized types_ to appear in its
1101 signature. Each type parameter must be explicitly declared, in an
1102 angle-bracket-enclosed, comma-separated list following the function name.
1103
1104 ```{.ignore}
1105 fn iter<T>(seq: &[T], f: |T|) {
1106     for elt in seq.iter() { f(elt); }
1107 }
1108 fn map<T, U>(seq: &[T], f: |T| -> U) -> Vec<U> {
1109     let mut acc = vec![];
1110     for elt in seq.iter() { acc.push(f(elt)); }
1111     acc
1112 }
1113 ```
1114
1115 Inside the function signature and body, the name of the type parameter can be
1116 used as a type name.
1117
1118 When a generic function is referenced, its type is instantiated based on the
1119 context of the reference. For example, calling the `iter` function defined
1120 above on `[1, 2]` will instantiate type parameter `T` with `i32`, and require
1121 the closure parameter to have type `fn(i32)`.
1122
1123 The type parameters can also be explicitly supplied in a trailing
1124 [path](#paths) component after the function name. This might be necessary if
1125 there is not sufficient context to determine the type parameters. For example,
1126 `mem::size_of::<u32>() == 4`.
1127
1128 Since a parameter type is opaque to the generic function, the set of operations
1129 that can be performed on it is limited. Values of parameter type can only be
1130 moved, not copied.
1131
1132 ```
1133 fn id<T>(x: T) -> T { x }
1134 ```
1135
1136 Similarly, [trait](#traits) bounds can be specified for type parameters to
1137 allow methods with that trait to be called on values of that type.
1138
1139 #### Unsafety
1140
1141 Unsafe operations are those that potentially violate the memory-safety
1142 guarantees of Rust's static semantics.
1143
1144 The following language level features cannot be used in the safe subset of
1145 Rust:
1146
1147 - Dereferencing a [raw pointer](#pointer-types).
1148 - Reading or writing a [mutable static variable](#mutable-statics).
1149 - Calling an unsafe function (including an intrinsic or foreign function).
1150
1151 ##### Unsafe functions
1152
1153 Unsafe functions are functions that are not safe in all contexts and/or for all
1154 possible inputs. Such a function must be prefixed with the keyword `unsafe` and
1155 can only be called from an `unsafe` block or another `unsafe` function.
1156
1157 ##### Unsafe blocks
1158
1159 A block of code can be prefixed with the `unsafe` keyword, to permit calling
1160 `unsafe` functions or dereferencing raw pointers within a safe function.
1161
1162 When a programmer has sufficient conviction that a sequence of potentially
1163 unsafe operations is actually safe, they can encapsulate that sequence (taken
1164 as a whole) within an `unsafe` block. The compiler will consider uses of such
1165 code safe, in the surrounding context.
1166
1167 Unsafe blocks are used to wrap foreign libraries, make direct use of hardware
1168 or implement features not directly present in the language. For example, Rust
1169 provides the language features necessary to implement memory-safe concurrency
1170 in the language but the implementation of threads and message passing is in the
1171 standard library.
1172
1173 Rust's type system is a conservative approximation of the dynamic safety
1174 requirements, so in some cases there is a performance cost to using safe code.
1175 For example, a doubly-linked list is not a tree structure and can only be
1176 represented with reference-counted pointers in safe code. By using `unsafe`
1177 blocks to represent the reverse links as raw pointers, it can be implemented
1178 with only boxes.
1179
1180 ##### Behavior considered undefined
1181
1182 The following is a list of behavior which is forbidden in all Rust code,
1183 including within `unsafe` blocks and `unsafe` functions. Type checking provides
1184 the guarantee that these issues are never caused by safe code.
1185
1186 * Data races
1187 * Dereferencing a null/dangling raw pointer
1188 * Reads of [undef](http://llvm.org/docs/LangRef.html#undefined-values)
1189   (uninitialized) memory
1190 * Breaking the [pointer aliasing
1191   rules](http://llvm.org/docs/LangRef.html#pointer-aliasing-rules)
1192   with raw pointers (a subset of the rules used by C)
1193 * `&mut` and `&` follow LLVM’s scoped [noalias] model, except if the `&T`
1194   contains an `UnsafeCell<U>`. Unsafe code must not violate these aliasing
1195   guarantees.
1196 * Mutating an immutable value/reference without `UnsafeCell<U>`
1197 * Invoking undefined behavior via compiler intrinsics:
1198   * Indexing outside of the bounds of an object with `std::ptr::offset`
1199     (`offset` intrinsic), with
1200     the exception of one byte past the end which is permitted.
1201   * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64`
1202     intrinsics) on overlapping buffers
1203 * Invalid values in primitive types, even in private fields/locals:
1204   * Dangling/null references or boxes
1205   * A value other than `false` (0) or `true` (1) in a `bool`
1206   * A discriminant in an `enum` not included in the type definition
1207   * A value in a `char` which is a surrogate or above `char::MAX`
1208   * Non-UTF-8 byte sequences in a `str`
1209 * Unwinding into Rust from foreign code or unwinding from Rust into foreign
1210   code. Rust's failure system is not compatible with exception handling in
1211   other languages. Unwinding must be caught and handled at FFI boundaries.
1212
1213 [noalias]: http://llvm.org/docs/LangRef.html#noalias
1214
1215 ##### Behaviour not considered unsafe
1216
1217 This is a list of behaviour not considered *unsafe* in Rust terms, but that may
1218 be undesired.
1219
1220 * Deadlocks
1221 * Reading data from private fields (`std::repr`)
1222 * Leaks due to reference count cycles, even in the global heap
1223 * Exiting without calling destructors
1224 * Sending signals
1225 * Accessing/modifying the file system
1226 * Unsigned integer overflow (well-defined as wrapping)
1227 * Signed integer overflow (well-defined as two’s complement representation
1228   wrapping)
1229
1230 #### Diverging functions
1231
1232 A special kind of function can be declared with a `!` character where the
1233 output type would normally be. For example:
1234
1235 ```
1236 fn my_err(s: &str) -> ! {
1237     println!("{}", s);
1238     panic!();
1239 }
1240 ```
1241
1242 We call such functions "diverging" because they never return a value to the
1243 caller. Every control path in a diverging function must end with a `panic!()` or
1244 a call to another diverging function on every control path. The `!` annotation
1245 does *not* denote a type.
1246
1247 It might be necessary to declare a diverging function because as mentioned
1248 previously, the typechecker checks that every control path in a function ends
1249 with a [`return`](#return-expressions) or diverging expression. So, if `my_err`
1250 were declared without the `!` annotation, the following code would not
1251 typecheck:
1252
1253 ```
1254 # fn my_err(s: &str) -> ! { panic!() }
1255
1256 fn f(i: i32) -> i32 {
1257    if i == 42 {
1258      return 42;
1259    }
1260    else {
1261      my_err("Bad number!");
1262    }
1263 }
1264 ```
1265
1266 This will not compile without the `!` annotation on `my_err`, since the `else`
1267 branch of the conditional in `f` does not return an `i32`, as required by the
1268 signature of `f`. Adding the `!` annotation to `my_err` informs the
1269 typechecker that, should control ever enter `my_err`, no further type judgments
1270 about `f` need to hold, since control will never resume in any context that
1271 relies on those judgments. Thus the return type on `f` only needs to reflect
1272 the `if` branch of the conditional.
1273
1274 #### Extern functions
1275
1276 Extern functions are part of Rust's foreign function interface, providing the
1277 opposite functionality to [external blocks](#external-blocks). Whereas
1278 external blocks allow Rust code to call foreign code, extern functions with
1279 bodies defined in Rust code _can be called by foreign code_. They are defined
1280 in the same way as any other Rust function, except that they have the `extern`
1281 modifier.
1282
1283 ```
1284 // Declares an extern fn, the ABI defaults to "C"
1285 extern fn new_i32() -> i32 { 0 }
1286
1287 // Declares an extern fn with "stdcall" ABI
1288 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
1289 ```
1290
1291 Unlike normal functions, extern fns have an `extern "ABI" fn()`. This is the
1292 same type as the functions declared in an extern block.
1293
1294 ```
1295 # extern fn new_i32() -> i32 { 0 }
1296 let fptr: extern "C" fn() -> i32 = new_i32;
1297 ```
1298
1299 Extern functions may be called directly from Rust code as Rust uses large,
1300 contiguous stack segments like C.
1301
1302 ### Type aliases
1303
1304 A _type alias_ defines a new name for an existing [type](#types). Type
1305 aliases are declared with the keyword `type`. Every value has a single,
1306 specific type, but may implement several different traits, or be compatible with
1307 several different type constraints.
1308
1309 For example, the following defines the type `Point` as a synonym for the type
1310 `(u8, u8)`, the type of pairs of unsigned 8 bit integers.:
1311
1312 ```
1313 type Point = (u8, u8);
1314 let p: Point = (41, 68);
1315 ```
1316
1317 ### Structures
1318
1319 A _structure_ is a nominal [structure type](#structure-types) defined with the
1320 keyword `struct`.
1321
1322 An example of a `struct` item and its use:
1323
1324 ```
1325 struct Point {x: i32, y: i32}
1326 let p = Point {x: 10, y: 11};
1327 let px: i32 = p.x;
1328 ```
1329
1330 A _tuple structure_ is a nominal [tuple type](#tuple-types), also defined with
1331 the keyword `struct`. For example:
1332
1333 ```
1334 struct Point(i32, i32);
1335 let p = Point(10, 11);
1336 let px: i32 = match p { Point(x, _) => x };
1337 ```
1338
1339 A _unit-like struct_ is a structure without any fields, defined by leaving off
1340 the list of fields entirely. Such types will have a single value, just like
1341 the [unit value `()`](#unit-and-boolean-literals) of the unit type. For
1342 example:
1343
1344 ```
1345 struct Cookie;
1346 let c = [Cookie, Cookie, Cookie, Cookie];
1347 ```
1348
1349 The precise memory layout of a structure is not specified. One can specify a
1350 particular layout using the [`repr` attribute](#ffi-attributes).
1351
1352 ### Enumerations
1353
1354 An _enumeration_ is a simultaneous definition of a nominal [enumerated
1355 type](#enumerated-types) as well as a set of *constructors*, that can be used
1356 to create or pattern-match values of the corresponding enumerated type.
1357
1358 Enumerations are declared with the keyword `enum`.
1359
1360 An example of an `enum` item and its use:
1361
1362 ```
1363 enum Animal {
1364   Dog,
1365   Cat
1366 }
1367
1368 let mut a: Animal = Animal::Dog;
1369 a = Animal::Cat;
1370 ```
1371
1372 Enumeration constructors can have either named or unnamed fields:
1373
1374 ```rust
1375 enum Animal {
1376     Dog (String, f64),
1377     Cat { name: String, weight: f64 }
1378 }
1379
1380 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
1381 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
1382 ```
1383
1384 In this example, `Cat` is a _struct-like enum variant_,
1385 whereas `Dog` is simply called an enum variant.
1386
1387 Enums have a discriminant. You can assign them explicitly:
1388
1389 ```
1390 enum Foo {
1391     Bar = 123,
1392 }
1393 ```
1394
1395 If a discriminant isn't assigned, they start at zero, and add one for each
1396 variant, in order.
1397
1398 You can cast an enum to get this value:
1399
1400 ```
1401 # enum Foo { Bar = 123 }
1402 let x = Foo::Bar as u32; // x is now 123u32
1403 ```
1404
1405 This only works as long as none of the variants have data attached. If
1406 it were `Bar(i32)`, this is disallowed.
1407
1408 ### Constant items
1409
1410 ```{.ebnf .gram}
1411 const_item : "const" ident ':' type '=' expr ';' ;
1412 ```
1413
1414 A *constant item* is a named _constant value_ which is not associated with a
1415 specific memory location in the program. Constants are essentially inlined
1416 wherever they are used, meaning that they are copied directly into the relevant
1417 context when used. References to the same constant are not necessarily
1418 guaranteed to refer to the same memory address.
1419
1420 Constant values must not have destructors, and otherwise permit most forms of
1421 data. Constants may refer to the address of other constants, in which case the
1422 address will have the `static` lifetime. The compiler is, however, still at
1423 liberty to translate the constant many times, so the address referred to may not
1424 be stable.
1425
1426 Constants must be explicitly typed. The type may be `bool`, `char`, a number, or
1427 a type derived from those primitive types. The derived types are references with
1428 the `static` lifetime, fixed-size arrays, tuples, enum variants, and structs.
1429
1430 ```
1431 const BIT1: u32 = 1 << 0;
1432 const BIT2: u32 = 1 << 1;
1433
1434 const BITS: [u32; 2] = [BIT1, BIT2];
1435 const STRING: &'static str = "bitstring";
1436
1437 struct BitsNStrings<'a> {
1438     mybits: [u32; 2],
1439     mystring: &'a str
1440 }
1441
1442 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
1443     mybits: BITS,
1444     mystring: STRING
1445 };
1446 ```
1447
1448 ### Static items
1449
1450 ```{.ebnf .gram}
1451 static_item : "static" ident ':' type '=' expr ';' ;
1452 ```
1453
1454 A *static item* is similar to a *constant*, except that it represents a precise
1455 memory location in the program. A static is never "inlined" at the usage site,
1456 and all references to it refer to the same memory location. Static items have
1457 the `static` lifetime, which outlives all other lifetimes in a Rust program.
1458 Static items may be placed in read-only memory if they do not contain any
1459 interior mutability.
1460
1461 Statics may contain interior mutability through the `UnsafeCell` language item.
1462 All access to a static is safe, but there are a number of restrictions on
1463 statics:
1464
1465 * Statics may not contain any destructors.
1466 * The types of static values must ascribe to `Sync` to allow threadsafe access.
1467 * Statics may not refer to other statics by value, only by reference.
1468 * Constants cannot refer to statics.
1469
1470 Constants should in general be preferred over statics, unless large amounts of
1471 data are being stored, or single-address and mutability properties are required.
1472
1473 #### Mutable statics
1474
1475 If a static item is declared with the `mut` keyword, then it is allowed to
1476 be modified by the program. One of Rust's goals is to make concurrency bugs
1477 hard to run into, and this is obviously a very large source of race conditions
1478 or other bugs. For this reason, an `unsafe` block is required when either
1479 reading or writing a mutable static variable. Care should be taken to ensure
1480 that modifications to a mutable static are safe with respect to other threads
1481 running in the same process.
1482
1483 Mutable statics are still very useful, however. They can be used with C
1484 libraries and can also be bound from C libraries (in an `extern` block).
1485
1486 ```
1487 # fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 }
1488
1489 static mut LEVELS: u32 = 0;
1490
1491 // This violates the idea of no shared state, and this doesn't internally
1492 // protect against races, so this function is `unsafe`
1493 unsafe fn bump_levels_unsafe1() -> u32 {
1494     let ret = LEVELS;
1495     LEVELS += 1;
1496     return ret;
1497 }
1498
1499 // Assuming that we have an atomic_add function which returns the old value,
1500 // this function is "safe" but the meaning of the return value may not be what
1501 // callers expect, so it's still marked as `unsafe`
1502 unsafe fn bump_levels_unsafe2() -> u32 {
1503     return atomic_add(&mut LEVELS, 1);
1504 }
1505 ```
1506
1507 Mutable statics have the same restrictions as normal statics, except that the
1508 type of the value is not required to ascribe to `Sync`.
1509
1510 ### Traits
1511
1512 A _trait_ describes a set of method types.
1513
1514 Traits can include default implementations of methods, written in terms of some
1515 unknown [`self` type](#self-types); the `self` type may either be completely
1516 unspecified, or constrained by some other trait.
1517
1518 Traits are implemented for specific types through separate
1519 [implementations](#implementations).
1520
1521 ```
1522 # type Surface = i32;
1523 # type BoundingBox = i32;
1524 trait Shape {
1525     fn draw(&self, Surface);
1526     fn bounding_box(&self) -> BoundingBox;
1527 }
1528 ```
1529
1530 This defines a trait with two methods. All values that have
1531 [implementations](#implementations) of this trait in scope can have their
1532 `draw` and `bounding_box` methods called, using `value.bounding_box()`
1533 [syntax](#method-call-expressions).
1534
1535 Type parameters can be specified for a trait to make it generic. These appear
1536 after the trait name, using the same syntax used in [generic
1537 functions](#generic-functions).
1538
1539 ```
1540 trait Seq<T> {
1541    fn len(&self) -> u32;
1542    fn elt_at(&self, n: u32) -> T;
1543    fn iter<F>(&self, F) where F: Fn(T);
1544 }
1545 ```
1546
1547 Generic functions may use traits as _bounds_ on their type parameters. This
1548 will have two effects: only types that have the trait may instantiate the
1549 parameter, and within the generic function, the methods of the trait can be
1550 called on values that have the parameter's type. For example:
1551
1552 ```
1553 # type Surface = i32;
1554 # trait Shape { fn draw(&self, Surface); }
1555 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
1556     sh.draw(surface);
1557     sh.draw(surface);
1558 }
1559 ```
1560
1561 Traits also define an [trait object](#trait-objects) with the same name as the
1562 trait. Values of this type are created by [casting](#type-cast-expressions)
1563 pointer values (pointing to a type for which an implementation of the given
1564 trait is in scope) to pointers to the trait name, used as a type.
1565
1566 ```
1567 # trait Shape { fn dummy(&self) { } }
1568 # impl Shape for i32 { }
1569 # let mycircle = 0i32;
1570 let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>;
1571 ```
1572
1573 The resulting value is a box containing the value that was cast, along with
1574 information that identifies the methods of the implementation that was used.
1575 Values with a trait type can have [methods called](#method-call-expressions) on
1576 them, for any method in the trait, and can be used to instantiate type
1577 parameters that are bounded by the trait.
1578
1579 Trait methods may be static, which means that they lack a `self` argument.
1580 This means that they can only be called with function call syntax (`f(x)`) and
1581 not method call syntax (`obj.f()`). The way to refer to the name of a static
1582 method is to qualify it with the trait name, treating the trait name like a
1583 module. For example:
1584
1585 ```
1586 trait Num {
1587     fn from_i32(n: i32) -> Self;
1588 }
1589 impl Num for f64 {
1590     fn from_i32(n: i32) -> f64 { n as f64 }
1591 }
1592 let x: f64 = Num::from_i32(42);
1593 ```
1594
1595 Traits may inherit from other traits. For example, in
1596
1597 ```
1598 trait Shape { fn area(&self) -> f64; }
1599 trait Circle : Shape { fn radius(&self) -> f64; }
1600 ```
1601
1602 the syntax `Circle : Shape` means that types that implement `Circle` must also
1603 have an implementation for `Shape`. Multiple supertraits are separated by `+`,
1604 `trait Circle : Shape + PartialEq { }`. In an implementation of `Circle` for a
1605 given type `T`, methods can refer to `Shape` methods, since the typechecker
1606 checks that any type with an implementation of `Circle` also has an
1607 implementation of `Shape`.
1608
1609 In type-parameterized functions, methods of the supertrait may be called on
1610 values of subtrait-bound type parameters. Referring to the previous example of
1611 `trait Circle : Shape`:
1612
1613 ```
1614 # trait Shape { fn area(&self) -> f64; }
1615 # trait Circle : Shape { fn radius(&self) -> f64; }
1616 fn radius_times_area<T: Circle>(c: T) -> f64 {
1617     // `c` is both a Circle and a Shape
1618     c.radius() * c.area()
1619 }
1620 ```
1621
1622 Likewise, supertrait methods may also be called on trait objects.
1623
1624 ```{.ignore}
1625 # trait Shape { fn area(&self) -> f64; }
1626 # trait Circle : Shape { fn radius(&self) -> f64; }
1627 # impl Shape for i32 { fn area(&self) -> f64 { 0.0 } }
1628 # impl Circle for i32 { fn radius(&self) -> f64 { 0.0 } }
1629 # let mycircle = 0i32;
1630 let mycircle = Box::new(mycircle) as Box<Circle>;
1631 let nonsense = mycircle.radius() * mycircle.area();
1632 ```
1633
1634 ### Implementations
1635
1636 An _implementation_ is an item that implements a [trait](#traits) for a
1637 specific type.
1638
1639 Implementations are defined with the keyword `impl`.
1640
1641 ```
1642 # #[derive(Copy, Clone)]
1643 # struct Point {x: f64, y: f64};
1644 # type Surface = i32;
1645 # struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
1646 # trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; }
1647 # fn do_draw_circle(s: Surface, c: Circle) { }
1648 struct Circle {
1649     radius: f64,
1650     center: Point,
1651 }
1652
1653 impl Copy for Circle {}
1654
1655 impl Clone for Circle {
1656     fn clone(&self) -> Circle { *self }
1657 }
1658
1659 impl Shape for Circle {
1660     fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
1661     fn bounding_box(&self) -> BoundingBox {
1662         let r = self.radius;
1663         BoundingBox{x: self.center.x - r, y: self.center.y - r,
1664          width: 2.0 * r, height: 2.0 * r}
1665     }
1666 }
1667 ```
1668
1669 It is possible to define an implementation without referring to a trait. The
1670 methods in such an implementation can only be used as direct calls on the
1671 values of the type that the implementation targets. In such an implementation,
1672 the trait type and `for` after `impl` are omitted. Such implementations are
1673 limited to nominal types (enums, structs), and the implementation must appear
1674 in the same module or a sub-module as the `self` type:
1675
1676 ```
1677 struct Point {x: i32, y: i32}
1678
1679 impl Point {
1680     fn log(&self) {
1681         println!("Point is at ({}, {})", self.x, self.y);
1682     }
1683 }
1684
1685 let my_point = Point {x: 10, y:11};
1686 my_point.log();
1687 ```
1688
1689 When a trait _is_ specified in an `impl`, all methods declared as part of the
1690 trait must be implemented, with matching types and type parameter counts.
1691
1692 An implementation can take type parameters, which can be different from the
1693 type parameters taken by the trait it implements. Implementation parameters
1694 are written after the `impl` keyword.
1695
1696 ```
1697 # trait Seq<T> { fn dummy(&self, _: T) { } }
1698 impl<T> Seq<T> for Vec<T> {
1699    /* ... */
1700 }
1701 impl Seq<bool> for u32 {
1702    /* Treat the integer as a sequence of bits */
1703 }
1704 ```
1705
1706 ### External blocks
1707
1708 ```{.ebnf .gram}
1709 extern_block_item : "extern" '{' extern_block '}' ;
1710 extern_block : [ foreign_fn ] * ;
1711 ```
1712
1713 External blocks form the basis for Rust's foreign function interface.
1714 Declarations in an external block describe symbols in external, non-Rust
1715 libraries.
1716
1717 Functions within external blocks are declared in the same way as other Rust
1718 functions, with the exception that they may not have a body and are instead
1719 terminated by a semicolon.
1720
1721 Functions within external blocks may be called by Rust code, just like
1722 functions defined in Rust. The Rust compiler automatically translates between
1723 the Rust ABI and the foreign ABI.
1724
1725 A number of [attributes](#attributes) control the behavior of external blocks.
1726
1727 By default external blocks assume that the library they are calling uses the
1728 standard C "cdecl" ABI. Other ABIs may be specified using an `abi` string, as
1729 shown here:
1730
1731 ```ignore
1732 // Interface to the Windows API
1733 extern "stdcall" { }
1734 ```
1735
1736 The `link` attribute allows the name of the library to be specified. When
1737 specified the compiler will attempt to link against the native library of the
1738 specified name.
1739
1740 ```{.ignore}
1741 #[link(name = "crypto")]
1742 extern { }
1743 ```
1744
1745 The type of a function declared in an extern block is `extern "abi" fn(A1, ...,
1746 An) -> R`, where `A1...An` are the declared types of its arguments and `R` is
1747 the declared return type.
1748
1749 ## Visibility and Privacy
1750
1751 These two terms are often used interchangeably, and what they are attempting to
1752 convey is the answer to the question "Can this item be used at this location?"
1753
1754 Rust's name resolution operates on a global hierarchy of namespaces. Each level
1755 in the hierarchy can be thought of as some item. The items are one of those
1756 mentioned above, but also include external crates. Declaring or defining a new
1757 module can be thought of as inserting a new tree into the hierarchy at the
1758 location of the definition.
1759
1760 To control whether interfaces can be used across modules, Rust checks each use
1761 of an item to see whether it should be allowed or not. This is where privacy
1762 warnings are generated, or otherwise "you used a private item of another module
1763 and weren't allowed to."
1764
1765 By default, everything in Rust is *private*, with one exception. Enum variants
1766 in a `pub` enum are also public by default. You are allowed to alter this
1767 default visibility with the `priv` keyword. When an item is declared as `pub`,
1768 it can be thought of as being accessible to the outside world. For example:
1769
1770 ```
1771 # fn main() {}
1772 // Declare a private struct
1773 struct Foo;
1774
1775 // Declare a public struct with a private field
1776 pub struct Bar {
1777     field: i32
1778 }
1779
1780 // Declare a public enum with two public variants
1781 pub enum State {
1782     PubliclyAccessibleState,
1783     PubliclyAccessibleState2,
1784 }
1785 ```
1786
1787 With the notion of an item being either public or private, Rust allows item
1788 accesses in two cases:
1789
1790 1. If an item is public, then it can be used externally through any of its
1791    public ancestors.
1792 2. If an item is private, it may be accessed by the current module and its
1793    descendants.
1794
1795 These two cases are surprisingly powerful for creating module hierarchies
1796 exposing public APIs while hiding internal implementation details. To help
1797 explain, here's a few use cases and what they would entail:
1798
1799 * A library developer needs to expose functionality to crates which link
1800   against their library. As a consequence of the first case, this means that
1801   anything which is usable externally must be `pub` from the root down to the
1802   destination item. Any private item in the chain will disallow external
1803   accesses.
1804
1805 * A crate needs a global available "helper module" to itself, but it doesn't
1806   want to expose the helper module as a public API. To accomplish this, the
1807   root of the crate's hierarchy would have a private module which then
1808   internally has a "public api". Because the entire crate is a descendant of
1809   the root, then the entire local crate can access this private module through
1810   the second case.
1811
1812 * When writing unit tests for a module, it's often a common idiom to have an
1813   immediate child of the module to-be-tested named `mod test`. This module
1814   could access any items of the parent module through the second case, meaning
1815   that internal implementation details could also be seamlessly tested from the
1816   child module.
1817
1818 In the second case, it mentions that a private item "can be accessed" by the
1819 current module and its descendants, but the exact meaning of accessing an item
1820 depends on what the item is. Accessing a module, for example, would mean
1821 looking inside of it (to import more items). On the other hand, accessing a
1822 function would mean that it is invoked. Additionally, path expressions and
1823 import statements are considered to access an item in the sense that the
1824 import/expression is only valid if the destination is in the current visibility
1825 scope.
1826
1827 Here's an example of a program which exemplifies the three cases outlined
1828 above:
1829
1830 ```
1831 // This module is private, meaning that no external crate can access this
1832 // module. Because it is private at the root of this current crate, however, any
1833 // module in the crate may access any publicly visible item in this module.
1834 mod crate_helper_module {
1835
1836     // This function can be used by anything in the current crate
1837     pub fn crate_helper() {}
1838
1839     // This function *cannot* be used by anything else in the crate. It is not
1840     // publicly visible outside of the `crate_helper_module`, so only this
1841     // current module and its descendants may access it.
1842     fn implementation_detail() {}
1843 }
1844
1845 // This function is "public to the root" meaning that it's available to external
1846 // crates linking against this one.
1847 pub fn public_api() {}
1848
1849 // Similarly to 'public_api', this module is public so external crates may look
1850 // inside of it.
1851 pub mod submodule {
1852     use crate_helper_module;
1853
1854     pub fn my_method() {
1855         // Any item in the local crate may invoke the helper module's public
1856         // interface through a combination of the two rules above.
1857         crate_helper_module::crate_helper();
1858     }
1859
1860     // This function is hidden to any module which is not a descendant of
1861     // `submodule`
1862     fn my_implementation() {}
1863
1864     #[cfg(test)]
1865     mod test {
1866
1867         #[test]
1868         fn test_my_implementation() {
1869             // Because this module is a descendant of `submodule`, it's allowed
1870             // to access private items inside of `submodule` without a privacy
1871             // violation.
1872             super::my_implementation();
1873         }
1874     }
1875 }
1876
1877 # fn main() {}
1878 ```
1879
1880 For a rust program to pass the privacy checking pass, all paths must be valid
1881 accesses given the two rules above. This includes all use statements,
1882 expressions, types, etc.
1883
1884 ### Re-exporting and Visibility
1885
1886 Rust allows publicly re-exporting items through a `pub use` directive. Because
1887 this is a public directive, this allows the item to be used in the current
1888 module through the rules above. It essentially allows public access into the
1889 re-exported item. For example, this program is valid:
1890
1891 ```
1892 pub use self::implementation::api;
1893
1894 mod implementation {
1895     pub mod api {
1896         pub fn f() {}
1897     }
1898 }
1899
1900 # fn main() {}
1901 ```
1902
1903 This means that any external crate referencing `implementation::api::f` would
1904 receive a privacy violation, while the path `api::f` would be allowed.
1905
1906 When re-exporting a private item, it can be thought of as allowing the "privacy
1907 chain" being short-circuited through the reexport instead of passing through
1908 the namespace hierarchy as it normally would.
1909
1910 ## Attributes
1911
1912 ```{.ebnf .gram}
1913 attribute : '#' '!' ? '[' meta_item ']' ;
1914 meta_item : ident [ '=' literal
1915                   | '(' meta_seq ')' ] ? ;
1916 meta_seq : meta_item [ ',' meta_seq ] ? ;
1917 ```
1918
1919 Any item declaration may have an _attribute_ applied to it. Attributes in Rust
1920 are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334
1921 (C#). An attribute is a general, free-form metadatum that is interpreted
1922 according to name, convention, and language and compiler version. Attributes
1923 may appear as any of:
1924
1925 * A single identifier, the attribute name
1926 * An identifier followed by the equals sign '=' and a literal, providing a
1927   key/value pair
1928 * An identifier followed by a parenthesized list of sub-attribute arguments
1929
1930 Attributes with a bang ("!") after the hash ("#") apply to the item that the
1931 attribute is declared within. Attributes that do not have a bang after the hash
1932 apply to the item that follows the attribute.
1933
1934 An example of attributes:
1935
1936 ```{.rust}
1937 // General metadata applied to the enclosing module or crate.
1938 #![crate_type = "lib"]
1939
1940 // A function marked as a unit test
1941 #[test]
1942 fn test_foo() {
1943   /* ... */
1944 }
1945
1946 // A conditionally-compiled module
1947 #[cfg(target_os="linux")]
1948 mod bar {
1949   /* ... */
1950 }
1951
1952 // A lint attribute used to suppress a warning/error
1953 #[allow(non_camel_case_types)]
1954 type int8_t = i8;
1955 ```
1956
1957 > **Note:** At some point in the future, the compiler will distinguish between
1958 > language-reserved and user-available attributes. Until then, there is
1959 > effectively no difference between an attribute handled by a loadable syntax
1960 > extension and the compiler.
1961
1962 ### Crate-only attributes
1963
1964 - `crate_name` - specify the this crate's crate name.
1965 - `crate_type` - see [linkage](#linkage).
1966 - `feature` - see [compiler features](#compiler-features).
1967 - `no_builtins` - disable optimizing certain code patterns to invocations of
1968                   library functions that are assumed to exist
1969 - `no_main` - disable emitting the `main` symbol. Useful when some other
1970    object being linked to defines `main`.
1971 - `no_start` - disable linking to the `native` crate, which specifies the
1972   "start" language item.
1973 - `no_std` - disable linking to the `std` crate.
1974 - `plugin` â€” load a list of named crates as compiler plugins, e.g.
1975              `#![plugin(foo, bar)]`. Optional arguments for each plugin,
1976              i.e. `#![plugin(foo(... args ...))]`, are provided to the plugin's
1977              registrar function.  The `plugin` feature gate is required to use
1978              this attribute.
1979
1980 ### Module-only attributes
1981
1982 - `no_implicit_prelude` - disable injecting `use std::prelude::*` in this
1983   module.
1984 - `path` - specifies the file to load the module from. `#[path="foo.rs"] mod
1985   bar;` is equivalent to `mod bar { /* contents of foo.rs */ }`. The path is
1986   taken relative to the directory that the current module is in.
1987
1988 ### Function-only attributes
1989
1990 - `main` - indicates that this function should be passed to the entry point,
1991   rather than the function in the crate root named `main`.
1992 - `plugin_registrar` - mark this function as the registration point for
1993   [compiler plugins][plugin], such as loadable syntax extensions.
1994 - `start` - indicates that this function should be used as the entry point,
1995   overriding the "start" language item. See the "start" [language
1996   item](#language-items) for more details.
1997 - `test` - indicates that this function is a test function, to only be compiled
1998   in case of `--test`.
1999 - `should_panic` - indicates that this test function should panic, inverting the success condition.
2000 - `cold` - The function is unlikely to be executed, so optimize it (and calls
2001   to it) differently.
2002
2003 ### Static-only attributes
2004
2005 - `thread_local` - on a `static mut`, this signals that the value of this
2006   static may change depending on the current thread. The exact consequences of
2007   this are implementation-defined.
2008
2009 ### FFI attributes
2010
2011 On an `extern` block, the following attributes are interpreted:
2012
2013 - `link_args` - specify arguments to the linker, rather than just the library
2014   name and type. This is feature gated and the exact behavior is
2015   implementation-defined (due to variety of linker invocation syntax).
2016 - `link` - indicate that a native library should be linked to for the
2017   declarations in this block to be linked correctly. `link` supports an optional `kind`
2018   key with three possible values: `dylib`, `static`, and `framework`. See [external blocks](#external-blocks) for more about external blocks. Two
2019   examples: `#[link(name = "readline")]` and
2020   `#[link(name = "CoreFoundation", kind = "framework")]`.
2021
2022 On declarations inside an `extern` block, the following attributes are
2023 interpreted:
2024
2025 - `link_name` - the name of the symbol that this function or static should be
2026   imported as.
2027 - `linkage` - on a static, this specifies the [linkage
2028   type](http://llvm.org/docs/LangRef.html#linkage-types).
2029
2030 On `enum`s:
2031
2032 - `repr` - on C-like enums, this sets the underlying type used for
2033   representation. Takes one argument, which is the primitive
2034   type this enum should be represented for, or `C`, which specifies that it
2035   should be the default `enum` size of the C ABI for that platform. Note that
2036   enum representation in C is undefined, and this may be incorrect when the C
2037   code is compiled with certain flags.
2038
2039 On `struct`s:
2040
2041 - `repr` - specifies the representation to use for this struct. Takes a list
2042   of options. The currently accepted ones are `C` and `packed`, which may be
2043   combined. `C` will use a C ABI compatible struct layout, and `packed` will
2044   remove any padding between fields (note that this is very fragile and may
2045   break platforms which require aligned access).
2046
2047 ### Macro-related attributes
2048
2049 - `macro_use` on a `mod` â€” macros defined in this module will be visible in the
2050   module's parent, after this module has been included.
2051
2052 - `macro_use` on an `extern crate` â€” load macros from this crate.  An optional
2053   list of names `#[macro_use(foo, bar)]` restricts the import to just those
2054   macros named.  The `extern crate` must appear at the crate root, not inside
2055   `mod`, which ensures proper function of the [`$crate` macro
2056   variable](book/macros.html#the-variable-$crate).
2057
2058 - `macro_reexport` on an `extern crate` â€” re-export the named macros.
2059
2060 - `macro_export` - export a macro for cross-crate usage.
2061
2062 - `no_link` on an `extern crate` â€” even if we load this crate for macros, don't
2063   link it into the output.
2064
2065 See the [macros section of the
2066 book](book/macros.html#scoping-and-macro-import/export) for more information on
2067 macro scope.
2068
2069
2070 ### Miscellaneous attributes
2071
2072 - `export_name` - on statics and functions, this determines the name of the
2073   exported symbol.
2074 - `link_section` - on statics and functions, this specifies the section of the
2075   object file that this item's contents will be placed into.
2076 - `no_mangle` - on any item, do not apply the standard name mangling. Set the
2077   symbol for this item to its identifier.
2078 - `packed` - on structs or enums, eliminate any padding that would be used to
2079   align fields.
2080 - `simd` - on certain tuple structs, derive the arithmetic operators, which
2081   lower to the target's SIMD instructions, if any; the `simd` feature gate
2082   is necessary to use this attribute.
2083 - `static_assert` - on statics whose type is `bool`, terminates compilation
2084   with an error if it is not initialized to `true`.
2085 - `unsafe_destructor` - allow implementations of the "drop" language item
2086   where the type it is implemented for does not implement the "send" language
2087   item; the `unsafe_destructor` feature gate is needed to use this attribute
2088 - `unsafe_no_drop_flag` - on structs, remove the flag that prevents
2089   destructors from being run twice. Destructors might be run multiple times on
2090   the same object with this attribute.
2091 - `doc` - Doc comments such as `/// foo` are equivalent to `#[doc = "foo"]`.
2092 - `rustc_on_unimplemented` - Write a custom note to be shown along with the error
2093    when the trait is found to be unimplemented on a type.
2094    You may use format arguments like `{T}`, `{A}` to correspond to the
2095    types at the point of use corresponding to the type parameters of the
2096    trait of the same name. `{Self}` will be replaced with the type that is supposed
2097    to implement the trait but doesn't. To use this, the `on_unimplemented` feature gate
2098    must be enabled.
2099
2100 ### Conditional compilation
2101
2102 Sometimes one wants to have different compiler outputs from the same code,
2103 depending on build target, such as targeted operating system, or to enable
2104 release builds.
2105
2106 There are two kinds of configuration options, one that is either defined or not
2107 (`#[cfg(foo)]`), and the other that contains a string that can be checked
2108 against (`#[cfg(bar = "baz")]` (currently only compiler-defined configuration
2109 options can have the latter form).
2110
2111 ```
2112 // The function is only included in the build when compiling for OSX
2113 #[cfg(target_os = "macos")]
2114 fn macos_only() {
2115   // ...
2116 }
2117
2118 // This function is only included when either foo or bar is defined
2119 #[cfg(any(foo, bar))]
2120 fn needs_foo_or_bar() {
2121   // ...
2122 }
2123
2124 // This function is only included when compiling for a unixish OS with a 32-bit
2125 // architecture
2126 #[cfg(all(unix, target_pointer_width = "32"))]
2127 fn on_32bit_unix() {
2128   // ...
2129 }
2130
2131 // This function is only included when foo is not defined
2132 #[cfg(not(foo))]
2133 fn needs_not_foo() {
2134   // ...
2135 }
2136 ```
2137
2138 This illustrates some conditional compilation can be achieved using the
2139 `#[cfg(...)]` attribute. `any`, `all` and `not` can be used to assemble
2140 arbitrarily complex configurations through nesting.
2141
2142 The following configurations must be defined by the implementation:
2143
2144 * `target_arch = "..."`. Target CPU architecture, such as `"x86"`, `"x86_64"`
2145   `"mips"`, `"powerpc"`, `"arm"`, or `"aarch64"`.
2146 * `target_endian = "..."`. Endianness of the target CPU, either `"little"` or
2147   `"big"`.
2148 * `target_family = "..."`. Operating system family of the target, e. g.
2149   `"unix"` or `"windows"`. The value of this configuration option is defined
2150   as a configuration itself, like `unix` or `windows`.
2151 * `target_os = "..."`. Operating system of the target, examples include
2152   `"windows"`, `"macos"`, `"ios"`, `"linux"`, `"android"`, `"freebsd"`, `"dragonfly"`,
2153   `"bitrig"` or `"openbsd"`.
2154 * `target_pointer_width = "..."`. Target pointer width in bits. This is set
2155   to `"32"` for targets with 32-bit pointers, and likewise set to `"64"` for
2156   64-bit pointers.
2157 * `unix`. See `target_family`.
2158 * `windows`. See `target_family`.
2159
2160 You can also set another attribute based on a `cfg` variable with `cfg_attr`:
2161
2162 ```rust,ignore
2163 #[cfg_attr(a, b)]
2164 ```
2165
2166 Will be the same as `#[b]` if `a` is set by `cfg`, and nothing otherwise.
2167
2168 ### Lint check attributes
2169
2170 A lint check names a potentially undesirable coding pattern, such as
2171 unreachable code or omitted documentation, for the static entity to which the
2172 attribute applies.
2173
2174 For any lint check `C`:
2175
2176 * `allow(C)` overrides the check for `C` so that violations will go
2177    unreported,
2178 * `deny(C)` signals an error after encountering a violation of `C`,
2179 * `forbid(C)` is the same as `deny(C)`, but also forbids changing the lint
2180    level afterwards,
2181 * `warn(C)` warns about violations of `C` but continues compilation.
2182
2183 The lint checks supported by the compiler can be found via `rustc -W help`,
2184 along with their default settings.  [Compiler
2185 plugins](book/plugins.html#lint-plugins) can provide additional lint checks.
2186
2187 ```{.ignore}
2188 mod m1 {
2189     // Missing documentation is ignored here
2190     #[allow(missing_docs)]
2191     pub fn undocumented_one() -> i32 { 1 }
2192
2193     // Missing documentation signals a warning here
2194     #[warn(missing_docs)]
2195     pub fn undocumented_too() -> i32 { 2 }
2196
2197     // Missing documentation signals an error here
2198     #[deny(missing_docs)]
2199     pub fn undocumented_end() -> i32 { 3 }
2200 }
2201 ```
2202
2203 This example shows how one can use `allow` and `warn` to toggle a particular
2204 check on and off:
2205
2206 ```{.ignore}
2207 #[warn(missing_docs)]
2208 mod m2{
2209     #[allow(missing_docs)]
2210     mod nested {
2211         // Missing documentation is ignored here
2212         pub fn undocumented_one() -> i32 { 1 }
2213
2214         // Missing documentation signals a warning here,
2215         // despite the allow above.
2216         #[warn(missing_docs)]
2217         pub fn undocumented_two() -> i32 { 2 }
2218     }
2219
2220     // Missing documentation signals a warning here
2221     pub fn undocumented_too() -> i32 { 3 }
2222 }
2223 ```
2224
2225 This example shows how one can use `forbid` to disallow uses of `allow` for
2226 that lint check:
2227
2228 ```{.ignore}
2229 #[forbid(missing_docs)]
2230 mod m3 {
2231     // Attempting to toggle warning signals an error here
2232     #[allow(missing_docs)]
2233     /// Returns 2.
2234     pub fn undocumented_too() -> i32 { 2 }
2235 }
2236 ```
2237
2238 ### Language items
2239
2240 Some primitive Rust operations are defined in Rust code, rather than being
2241 implemented directly in C or assembly language. The definitions of these
2242 operations have to be easy for the compiler to find. The `lang` attribute
2243 makes it possible to declare these operations. For example, the `str` module
2244 in the Rust standard library defines the string equality function:
2245
2246 ```{.ignore}
2247 #[lang="str_eq"]
2248 pub fn eq_slice(a: &str, b: &str) -> bool {
2249     // details elided
2250 }
2251 ```
2252
2253 The name `str_eq` has a special meaning to the Rust compiler, and the presence
2254 of this definition means that it will use this definition when generating calls
2255 to the string equality function.
2256
2257 A complete list of the built-in language items will be added in the future.
2258
2259 ### Inline attributes
2260
2261 The inline attribute is used to suggest to the compiler to perform an inline
2262 expansion and place a copy of the function or static in the caller rather than
2263 generating code to call the function or access the static where it is defined.
2264
2265 The compiler automatically inlines functions based on internal heuristics.
2266 Incorrectly inlining functions can actually making the program slower, so it
2267 should be used with care.
2268
2269 Immutable statics are always considered inlineable unless marked with
2270 `#[inline(never)]`. It is undefined whether two different inlineable statics
2271 have the same memory address. In other words, the compiler is free to collapse
2272 duplicate inlineable statics together.
2273
2274 `#[inline]` and `#[inline(always)]` always causes the function to be serialized
2275 into crate metadata to allow cross-crate inlining.
2276
2277 There are three different types of inline attributes:
2278
2279 * `#[inline]` hints the compiler to perform an inline expansion.
2280 * `#[inline(always)]` asks the compiler to always perform an inline expansion.
2281 * `#[inline(never)]` asks the compiler to never perform an inline expansion.
2282
2283 ### `derive`
2284
2285 The `derive` attribute allows certain traits to be automatically implemented
2286 for data structures. For example, the following will create an `impl` for the
2287 `PartialEq` and `Clone` traits for `Foo`, the type parameter `T` will be given
2288 the `PartialEq` or `Clone` constraints for the appropriate `impl`:
2289
2290 ```
2291 #[derive(PartialEq, Clone)]
2292 struct Foo<T> {
2293     a: i32,
2294     b: T
2295 }
2296 ```
2297
2298 The generated `impl` for `PartialEq` is equivalent to
2299
2300 ```
2301 # struct Foo<T> { a: i32, b: T }
2302 impl<T: PartialEq> PartialEq for Foo<T> {
2303     fn eq(&self, other: &Foo<T>) -> bool {
2304         self.a == other.a && self.b == other.b
2305     }
2306
2307     fn ne(&self, other: &Foo<T>) -> bool {
2308         self.a != other.a || self.b != other.b
2309     }
2310 }
2311 ```
2312
2313 ### Compiler Features
2314
2315 Certain aspects of Rust may be implemented in the compiler, but they're not
2316 necessarily ready for every-day use. These features are often of "prototype
2317 quality" or "almost production ready", but may not be stable enough to be
2318 considered a full-fledged language feature.
2319
2320 For this reason, Rust recognizes a special crate-level attribute of the form:
2321
2322 ```{.ignore}
2323 #![feature(feature1, feature2, feature3)]
2324 ```
2325
2326 This directive informs the compiler that the feature list: `feature1`,
2327 `feature2`, and `feature3` should all be enabled. This is only recognized at a
2328 crate-level, not at a module-level. Without this directive, all features are
2329 considered off, and using the features will result in a compiler error.
2330
2331 The currently implemented features of the reference compiler are:
2332
2333 * `advanced_slice_patterns` - See the [match expressions](#match-expressions)
2334                               section for discussion; the exact semantics of
2335                               slice patterns are subject to change, so some types
2336                               are still unstable.
2337
2338 * `slice_patterns` - OK, actually, slice patterns are just scary and
2339                      completely unstable.
2340
2341 * `asm` - The `asm!` macro provides a means for inline assembly. This is often
2342           useful, but the exact syntax for this feature along with its
2343           semantics are likely to change, so this macro usage must be opted
2344           into.
2345
2346 * `associated_types` - Allows type aliases in traits. Experimental.
2347
2348 * `box_patterns` - Allows `box` patterns, the exact semantics of which
2349                    is subject to change.
2350
2351 * `box_syntax` - Allows use of `box` expressions, the exact semantics of which
2352                  is subject to change.
2353
2354 * `concat_idents` - Allows use of the `concat_idents` macro, which is in many
2355                     ways insufficient for concatenating identifiers, and may be
2356                     removed entirely for something more wholesome.
2357
2358 * `custom_attribute` - Allows the usage of attributes unknown to the compiler
2359                        so that new attributes can be added in a backwards compatible
2360                        manner (RFC 572).
2361
2362 * `custom_derive` - Allows the use of `#[derive(Foo,Bar)]` as sugar for
2363                     `#[derive_Foo] #[derive_Bar]`, which can be user-defined syntax
2364                     extensions.
2365
2366 * `intrinsics` - Allows use of the "rust-intrinsics" ABI. Compiler intrinsics
2367                  are inherently unstable and no promise about them is made.
2368
2369 * `lang_items` - Allows use of the `#[lang]` attribute. Like `intrinsics`,
2370                  lang items are inherently unstable and no promise about them
2371                  is made.
2372
2373 * `link_args` - This attribute is used to specify custom flags to the linker,
2374                 but usage is strongly discouraged. The compiler's usage of the
2375                 system linker is not guaranteed to continue in the future, and
2376                 if the system linker is not used then specifying custom flags
2377                 doesn't have much meaning.
2378
2379 * `link_llvm_intrinsics` â€“ Allows linking to LLVM intrinsics via
2380                            `#[link_name="llvm.*"]`.
2381
2382 * `linkage` - Allows use of the `linkage` attribute, which is not portable.
2383
2384 * `log_syntax` - Allows use of the `log_syntax` macro attribute, which is a
2385                  nasty hack that will certainly be removed.
2386
2387 * `main` - Allows use of the `#[main]` attribute, which changes the entry point
2388            into a Rust program. This capability is subject to change.
2389
2390 * `macro_reexport` - Allows macros to be re-exported from one crate after being imported
2391                      from another. This feature was originally designed with the sole
2392                      use case of the Rust standard library in mind, and is subject to
2393                      change.
2394
2395 * `non_ascii_idents` - The compiler supports the use of non-ascii identifiers,
2396                        but the implementation is a little rough around the
2397                        edges, so this can be seen as an experimental feature
2398                        for now until the specification of identifiers is fully
2399                        fleshed out.
2400
2401 * `no_std` - Allows the `#![no_std]` crate attribute, which disables the implicit
2402              `extern crate std`. This typically requires use of the unstable APIs
2403              behind the libstd "facade", such as libcore and libcollections. It
2404              may also cause problems when using syntax extensions, including
2405              `#[derive]`.
2406
2407 * `on_unimplemented` - Allows the `#[rustc_on_unimplemented]` attribute, which allows
2408                        trait definitions to add specialized notes to error messages
2409                        when an implementation was expected but not found.
2410
2411 * `optin_builtin_traits` - Allows the definition of default and negative trait
2412                            implementations. Experimental.
2413
2414 * `plugin` - Usage of [compiler plugins][plugin] for custom lints or syntax extensions.
2415              These depend on compiler internals and are subject to change.
2416
2417 * `plugin_registrar` - Indicates that a crate provides [compiler plugins][plugin].
2418
2419 * `quote` - Allows use of the `quote_*!` family of macros, which are
2420             implemented very poorly and will likely change significantly
2421             with a proper implementation.
2422
2423 * `rustc_attrs` - Gates internal `#[rustc_*]` attributes which may be
2424                   for internal use only or have meaning added to them in the future.
2425
2426 * `rustc_diagnostic_macros`- A mysterious feature, used in the implementation
2427                              of rustc, not meant for mortals.
2428
2429 * `simd` - Allows use of the `#[simd]` attribute, which is overly simple and
2430            not the SIMD interface we want to expose in the long term.
2431
2432 * `simd_ffi` - Allows use of SIMD vectors in signatures for foreign functions.
2433                The SIMD interface is subject to change.
2434
2435 * `staged_api` - Allows usage of stability markers and `#![staged_api]` in a
2436                  crate. Stability markers are also attributes: `#[stable]`,
2437                  `#[unstable]`, and `#[deprecated]` are the three levels.
2438
2439 * `static_assert` - The `#[static_assert]` functionality is experimental and
2440                     unstable. The attribute can be attached to a `static` of
2441                     type `bool` and the compiler will error if the `bool` is
2442                     `false` at compile time. This version of this functionality
2443                     is unintuitive and suboptimal.
2444
2445 * `start` - Allows use of the `#[start]` attribute, which changes the entry point
2446             into a Rust program. This capability, especially the signature for the
2447             annotated function, is subject to change.
2448
2449 * `struct_inherit` - Allows using struct inheritance, which is barely
2450                      implemented and will probably be removed. Don't use this.
2451
2452 * `struct_variant` - Structural enum variants (those with named fields). It is
2453                      currently unknown whether this style of enum variant is as
2454                      fully supported as the tuple-forms, and it's not certain
2455                      that this style of variant should remain in the language.
2456                      For now this style of variant is hidden behind a feature
2457                      flag.
2458
2459 * `thread_local` - The usage of the `#[thread_local]` attribute is experimental
2460                    and should be seen as unstable. This attribute is used to
2461                    declare a `static` as being unique per-thread leveraging
2462                    LLVM's implementation which works in concert with the kernel
2463                    loader and dynamic linker. This is not necessarily available
2464                    on all platforms, and usage of it is discouraged.
2465
2466 * `trace_macros` - Allows use of the `trace_macros` macro, which is a nasty
2467                    hack that will certainly be removed.
2468
2469 * `unboxed_closures` - Rust's new closure design, which is currently a work in
2470                        progress feature with many known bugs.
2471
2472 * `unsafe_destructor` - Allows use of the `#[unsafe_destructor]` attribute,
2473                         which is considered wildly unsafe and will be
2474                         obsoleted by language improvements.
2475
2476 * `unsafe_no_drop_flag` - Allows use of the `#[unsafe_no_drop_flag]` attribute,
2477                           which removes hidden flag added to a type that
2478                           implements the `Drop` trait. The design for the
2479                           `Drop` flag is subject to change, and this feature
2480                           may be removed in the future.
2481
2482 * `unmarked_api` - Allows use of items within a `#![staged_api]` crate
2483                    which have not been marked with a stability marker.
2484                    Such items should not be allowed by the compiler to exist,
2485                    so if you need this there probably is a compiler bug.
2486
2487 * `visible_private_types` - Allows public APIs to expose otherwise private
2488                             types, e.g. as the return type of a public function.
2489                             This capability may be removed in the future.
2490
2491 * `allow_internal_unstable` - Allows `macro_rules!` macros to be tagged with the
2492                               `#[allow_internal_unstable]` attribute, designed
2493                               to allow `std` macros to call
2494                               `#[unstable]`/feature-gated functionality
2495                               internally without imposing on callers
2496                               (i.e. making them behave like function calls in
2497                               terms of encapsulation).
2498
2499 If a feature is promoted to a language feature, then all existing programs will
2500 start to receive compilation warnings about #[feature] directives which enabled
2501 the new feature (because the directive is no longer necessary). However, if a
2502 feature is decided to be removed from the language, errors will be issued (if
2503 there isn't a parser error first). The directive in this case is no longer
2504 necessary, and it's likely that existing code will break if the feature isn't
2505 removed.
2506
2507 If an unknown feature is found in a directive, it results in a compiler error.
2508 An unknown feature is one which has never been recognized by the compiler.
2509
2510 # Statements and expressions
2511
2512 Rust is _primarily_ an expression language. This means that most forms of
2513 value-producing or effect-causing evaluation are directed by the uniform syntax
2514 category of _expressions_. Each kind of expression can typically _nest_ within
2515 each other kind of expression, and rules for evaluation of expressions involve
2516 specifying both the value produced by the expression and the order in which its
2517 sub-expressions are themselves evaluated.
2518
2519 In contrast, statements in Rust serve _mostly_ to contain and explicitly
2520 sequence expression evaluation.
2521
2522 ## Statements
2523
2524 A _statement_ is a component of a block, which is in turn a component of an
2525 outer [expression](#expressions) or [function](#functions).
2526
2527 Rust has two kinds of statement: [declaration
2528 statements](#declaration-statements) and [expression
2529 statements](#expression-statements).
2530
2531 ### Declaration statements
2532
2533 A _declaration statement_ is one that introduces one or more *names* into the
2534 enclosing statement block. The declared names may denote new variables or new
2535 items.
2536
2537 #### Item declarations
2538
2539 An _item declaration statement_ has a syntactic form identical to an
2540 [item](#items) declaration within a module. Declaring an item &mdash; a
2541 function, enumeration, structure, type, static, trait, implementation or module
2542 &mdash; locally within a statement block is simply a way of restricting its
2543 scope to a narrow region containing all of its uses; it is otherwise identical
2544 in meaning to declaring the item outside the statement block.
2545
2546 > **Note**: there is no implicit capture of the function's dynamic environment when
2547 > declaring a function-local item.
2548
2549 #### Variable declarations
2550
2551 ```{.ebnf .gram}
2552 let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
2553 init : [ '=' ] expr ;
2554 ```
2555
2556 A _variable declaration_ introduces a new set of variable, given by a pattern. The
2557 pattern may be followed by a type annotation, and/or an initializer expression.
2558 When no type annotation is given, the compiler will infer the type, or signal
2559 an error if insufficient type information is available for definite inference.
2560 Any variables introduced by a variable declaration are visible from the point of
2561 declaration until the end of the enclosing block scope.
2562
2563 ### Expression statements
2564
2565 An _expression statement_ is one that evaluates an [expression](#expressions)
2566 and ignores its result. The type of an expression statement `e;` is always
2567 `()`, regardless of the type of `e`. As a rule, an expression statement's
2568 purpose is to trigger the effects of evaluating its expression.
2569
2570 ## Expressions
2571
2572 An expression may have two roles: it always produces a *value*, and it may have
2573 *effects* (otherwise known as "side effects"). An expression *evaluates to* a
2574 value, and has effects during *evaluation*. Many expressions contain
2575 sub-expressions (operands). The meaning of each kind of expression dictates
2576 several things:
2577
2578 * Whether or not to evaluate the sub-expressions when evaluating the expression
2579 * The order in which to evaluate the sub-expressions
2580 * How to combine the sub-expressions' values to obtain the value of the expression
2581
2582 In this way, the structure of expressions dictates the structure of execution.
2583 Blocks are just another kind of expression, so blocks, statements, expressions,
2584 and blocks again can recursively nest inside each other to an arbitrary depth.
2585
2586 #### Lvalues, rvalues and temporaries
2587
2588 Expressions are divided into two main categories: _lvalues_ and _rvalues_.
2589 Likewise within each expression, sub-expressions may occur in _lvalue context_
2590 or _rvalue context_. The evaluation of an expression depends both on its own
2591 category and the context it occurs within.
2592
2593 An lvalue is an expression that represents a memory location. These expressions
2594 are [paths](#path-expressions) (which refer to local variables, function and
2595 method arguments, or static variables), dereferences (`*expr`), [indexing
2596 expressions](#index-expressions) (`expr[expr]`), and [field
2597 references](#field-expressions) (`expr.f`). All other expressions are rvalues.
2598
2599 The left operand of an [assignment](#assignment-expressions) or
2600 [compound-assignment](#compound-assignment-expressions) expression is an lvalue
2601 context, as is the single operand of a unary
2602 [borrow](#unary-operator-expressions). All other expression contexts are
2603 rvalue contexts.
2604
2605 When an lvalue is evaluated in an _lvalue context_, it denotes a memory
2606 location; when evaluated in an _rvalue context_, it denotes the value held _in_
2607 that memory location.
2608
2609 When an rvalue is used in an lvalue context, a temporary un-named lvalue is
2610 created and used instead. A temporary's lifetime equals the largest lifetime
2611 of any reference that points to it.
2612
2613 #### Moved and copied types
2614
2615 When a [local variable](#variables) is used as an
2616 [rvalue](#lvalues,-rvalues-and-temporaries) the variable will either be moved
2617 or copied, depending on its type. All values whose type implements `Copy` are
2618 copied, all others are moved.
2619
2620 ### Literal expressions
2621
2622 A _literal expression_ consists of one of the [literal](#literals) forms
2623 described earlier. It directly describes a number, character, string, boolean
2624 value, or the unit value.
2625
2626 ```{.literals}
2627 ();        // unit type
2628 "hello";   // string type
2629 '5';       // character type
2630 5;         // integer type
2631 ```
2632
2633 ### Path expressions
2634
2635 A [path](#paths) used as an expression context denotes either a local variable
2636 or an item. Path expressions are [lvalues](#lvalues,-rvalues-and-temporaries).
2637
2638 ### Tuple expressions
2639
2640 Tuples are written by enclosing zero or more comma-separated expressions in
2641 parentheses. They are used to create [tuple-typed](#tuple-types) values.
2642
2643 ```{.tuple}
2644 (0,);
2645 (0.0, 4.5);
2646 ("a", 4us, true);
2647 ```
2648
2649 ### Unit expressions
2650
2651 The expression `()` denotes the _unit value_, the only value of the type with
2652 the same name.
2653
2654 ### Structure expressions
2655
2656 ```{.ebnf .gram}
2657 struct_expr : expr_path '{' ident ':' expr
2658                       [ ',' ident ':' expr ] *
2659                       [ ".." expr ] '}' |
2660               expr_path '(' expr
2661                       [ ',' expr ] * ')' |
2662               expr_path ;
2663 ```
2664
2665 There are several forms of structure expressions. A _structure expression_
2666 consists of the [path](#paths) of a [structure item](#structures), followed by
2667 a brace-enclosed list of one or more comma-separated name-value pairs,
2668 providing the field values of a new instance of the structure. A field name
2669 can be any identifier, and is separated from its value expression by a colon.
2670 The location denoted by a structure field is mutable if and only if the
2671 enclosing structure is mutable.
2672
2673 A _tuple structure expression_ consists of the [path](#paths) of a [structure
2674 item](#structures), followed by a parenthesized list of one or more
2675 comma-separated expressions (in other words, the path of a structure item
2676 followed by a tuple expression). The structure item must be a tuple structure
2677 item.
2678
2679 A _unit-like structure expression_ consists only of the [path](#paths) of a
2680 [structure item](#structures).
2681
2682 The following are examples of structure expressions:
2683
2684 ```
2685 # struct Point { x: f64, y: f64 }
2686 # struct TuplePoint(f64, f64);
2687 # mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } }
2688 # struct Cookie; fn some_fn<T>(t: T) {}
2689 Point {x: 10.0, y: 20.0};
2690 TuplePoint(10.0, 20.0);
2691 let u = game::User {name: "Joe", age: 35, score: 100_000};
2692 some_fn::<Cookie>(Cookie);
2693 ```
2694
2695 A structure expression forms a new value of the named structure type. Note
2696 that for a given *unit-like* structure type, this will always be the same
2697 value.
2698
2699 A structure expression can terminate with the syntax `..` followed by an
2700 expression to denote a functional update. The expression following `..` (the
2701 base) must have the same structure type as the new structure type being formed.
2702 The entire expression denotes the result of constructing a new structure (with
2703 the same type as the base expression) with the given values for the fields that
2704 were explicitly specified and the values in the base expression for all other
2705 fields.
2706
2707 ```
2708 # struct Point3d { x: i32, y: i32, z: i32 }
2709 let base = Point3d {x: 1, y: 2, z: 3};
2710 Point3d {y: 0, z: 10, .. base};
2711 ```
2712
2713 ### Block expressions
2714
2715 ```{.ebnf .gram}
2716 block_expr : '{' [ stmt ';' | item ] *
2717                  [ expr ] '}' ;
2718 ```
2719
2720 A _block expression_ is similar to a module in terms of the declarations that
2721 are possible. Each block conceptually introduces a new namespace scope. Use
2722 items can bring new names into scopes and declared items are in scope for only
2723 the block itself.
2724
2725 A block will execute each statement sequentially, and then execute the
2726 expression (if given). If the block ends in a statement, its value is `()`:
2727
2728 ```
2729 let x: () = { println!("Hello."); };
2730 ```
2731
2732 If it ends in an expression, its value and type are that of the expression:
2733
2734 ```
2735 let x: i32 = { println!("Hello."); 5 };
2736
2737 assert_eq!(5, x);
2738 ```
2739
2740 ### Method-call expressions
2741
2742 ```{.ebnf .gram}
2743 method_call_expr : expr '.' ident paren_expr_list ;
2744 ```
2745
2746 A _method call_ consists of an expression followed by a single dot, an
2747 identifier, and a parenthesized expression-list. Method calls are resolved to
2748 methods on specific traits, either statically dispatching to a method if the
2749 exact `self`-type of the left-hand-side is known, or dynamically dispatching if
2750 the left-hand-side expression is an indirect [trait object](#trait-objects).
2751
2752 ### Field expressions
2753
2754 ```{.ebnf .gram}
2755 field_expr : expr '.' ident ;
2756 ```
2757
2758 A _field expression_ consists of an expression followed by a single dot and an
2759 identifier, when not immediately followed by a parenthesized expression-list
2760 (the latter is a [method call expression](#method-call-expressions)). A field
2761 expression denotes a field of a [structure](#structure-types).
2762
2763 ```{.ignore .field}
2764 mystruct.myfield;
2765 foo().x;
2766 (Struct {a: 10, b: 20}).a;
2767 ```
2768
2769 A field access is an [lvalue](#lvalues,-rvalues-and-temporaries) referring to
2770 the value of that field. When the type providing the field inherits mutability,
2771 it can be [assigned](#assignment-expressions) to.
2772
2773 Also, if the type of the expression to the left of the dot is a pointer, it is
2774 automatically dereferenced to make the field access possible.
2775
2776 ### Array expressions
2777
2778 ```{.ebnf .gram}
2779 array_expr : '[' "mut" ? array_elems? ']' ;
2780
2781 array_elems : [expr [',' expr]*] | [expr ';' expr] ;
2782 ```
2783
2784 An [array](#array,-and-slice-types) _expression_ is written by enclosing zero
2785 or more comma-separated expressions of uniform type in square brackets.
2786
2787 In the `[expr ';' expr]` form, the expression after the `';'` must be a
2788 constant expression that can be evaluated at compile time, such as a
2789 [literal](#literals) or a [static item](#static-items).
2790
2791 ```
2792 [1, 2, 3, 4];
2793 ["a", "b", "c", "d"];
2794 [0; 128];              // array with 128 zeros
2795 [0u8, 0u8, 0u8, 0u8];
2796 ```
2797
2798 ### Index expressions
2799
2800 ```{.ebnf .gram}
2801 idx_expr : expr '[' expr ']' ;
2802 ```
2803
2804 [Array](#array,-and-slice-types)-typed expressions can be indexed by
2805 writing a square-bracket-enclosed expression (the index) after them. When the
2806 array is mutable, the resulting [lvalue](#lvalues,-rvalues-and-temporaries) can
2807 be assigned to.
2808
2809 Indices are zero-based, and may be of any integral type. Vector access is
2810 bounds-checked at run-time. When the check fails, it will put the thread in a
2811 _panicked state_.
2812
2813 ```{should-fail}
2814 ([1, 2, 3, 4])[0];
2815 (["a", "b"])[10]; // panics
2816 ```
2817
2818 ### Unary operator expressions
2819
2820 Rust defines three unary operators. They are all written as prefix operators,
2821 before the expression they apply to.
2822
2823 * `-`
2824   : Negation. May only be applied to numeric types.
2825 * `*`
2826   : Dereference. When applied to a [pointer](#pointer-types) it denotes the
2827     pointed-to location. For pointers to mutable locations, the resulting
2828     [lvalue](#lvalues,-rvalues-and-temporaries) can be assigned to.
2829     On non-pointer types, it calls the `deref` method of the `std::ops::Deref`
2830     trait, or the `deref_mut` method of the `std::ops::DerefMut` trait (if
2831     implemented by the type and required for an outer expression that will or
2832     could mutate the dereference), and produces the result of dereferencing the
2833     `&` or `&mut` borrowed pointer returned from the overload method.
2834
2835 * `!`
2836   : Logical negation. On the boolean type, this flips between `true` and
2837     `false`. On integer types, this inverts the individual bits in the
2838     two's complement representation of the value.
2839
2840 ### Binary operator expressions
2841
2842 ```{.ebnf .gram}
2843 binop_expr : expr binop expr ;
2844 ```
2845
2846 Binary operators expressions are given in terms of [operator
2847 precedence](#operator-precedence).
2848
2849 #### Arithmetic operators
2850
2851 Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
2852 defined in the `std::ops` module of the `std` library. This means that
2853 arithmetic operators can be overridden for user-defined types. The default
2854 meaning of the operators on standard types is given here.
2855
2856 * `+`
2857   : Addition and array/string concatenation.
2858     Calls the `add` method on the `std::ops::Add` trait.
2859 * `-`
2860   : Subtraction.
2861     Calls the `sub` method on the `std::ops::Sub` trait.
2862 * `*`
2863   : Multiplication.
2864     Calls the `mul` method on the `std::ops::Mul` trait.
2865 * `/`
2866   : Quotient.
2867     Calls the `div` method on the `std::ops::Div` trait.
2868 * `%`
2869   : Remainder.
2870     Calls the `rem` method on the `std::ops::Rem` trait.
2871
2872 #### Bitwise operators
2873
2874 Like the [arithmetic operators](#arithmetic-operators), bitwise operators are
2875 syntactic sugar for calls to methods of built-in traits. This means that
2876 bitwise operators can be overridden for user-defined types. The default
2877 meaning of the operators on standard types is given here.
2878
2879 * `&`
2880   : And.
2881     Calls the `bitand` method of the `std::ops::BitAnd` trait.
2882 * `|`
2883   : Inclusive or.
2884     Calls the `bitor` method of the `std::ops::BitOr` trait.
2885 * `^`
2886   : Exclusive or.
2887     Calls the `bitxor` method of the `std::ops::BitXor` trait.
2888 * `<<`
2889   : Left shift.
2890     Calls the `shl` method of the `std::ops::Shl` trait.
2891 * `>>`
2892   : Right shift.
2893     Calls the `shr` method of the `std::ops::Shr` trait.
2894
2895 #### Lazy boolean operators
2896
2897 The operators `||` and `&&` may be applied to operands of boolean type. The
2898 `||` operator denotes logical 'or', and the `&&` operator denotes logical
2899 'and'. They differ from `|` and `&` in that the right-hand operand is only
2900 evaluated when the left-hand operand does not already determine the result of
2901 the expression. That is, `||` only evaluates its right-hand operand when the
2902 left-hand operand evaluates to `false`, and `&&` only when it evaluates to
2903 `true`.
2904
2905 #### Comparison operators
2906
2907 Comparison operators are, like the [arithmetic
2908 operators](#arithmetic-operators), and [bitwise operators](#bitwise-operators),
2909 syntactic sugar for calls to built-in traits. This means that comparison
2910 operators can be overridden for user-defined types. The default meaning of the
2911 operators on standard types is given here.
2912
2913 * `==`
2914   : Equal to.
2915     Calls the `eq` method on the `std::cmp::PartialEq` trait.
2916 * `!=`
2917   : Unequal to.
2918     Calls the `ne` method on the `std::cmp::PartialEq` trait.
2919 * `<`
2920   : Less than.
2921     Calls the `lt` method on the `std::cmp::PartialOrd` trait.
2922 * `>`
2923   : Greater than.
2924     Calls the `gt` method on the `std::cmp::PartialOrd` trait.
2925 * `<=`
2926   : Less than or equal.
2927     Calls the `le` method on the `std::cmp::PartialOrd` trait.
2928 * `>=`
2929   : Greater than or equal.
2930     Calls the `ge` method on the `std::cmp::PartialOrd` trait.
2931
2932 #### Type cast expressions
2933
2934 A type cast expression is denoted with the binary operator `as`.
2935
2936 Executing an `as` expression casts the value on the left-hand side to the type
2937 on the right-hand side.
2938
2939 An example of an `as` expression:
2940
2941 ```
2942 # fn sum(v: &[f64]) -> f64 { 0.0 }
2943 # fn len(v: &[f64]) -> i32 { 0 }
2944
2945 fn avg(v: &[f64]) -> f64 {
2946   let sum: f64 = sum(v);
2947   let sz: f64 = len(v) as f64;
2948   return sum / sz;
2949 }
2950 ```
2951
2952 #### Assignment expressions
2953
2954 An _assignment expression_ consists of an
2955 [lvalue](#lvalues,-rvalues-and-temporaries) expression followed by an equals
2956 sign (`=`) and an [rvalue](#lvalues,-rvalues-and-temporaries) expression.
2957
2958 Evaluating an assignment expression [either copies or
2959 moves](#moved-and-copied-types) its right-hand operand to its left-hand
2960 operand.
2961
2962 ```
2963 # let mut x = 0;
2964 # let y = 0;
2965
2966 x = y;
2967 ```
2968
2969 #### Compound assignment expressions
2970
2971 The `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, and `>>` operators may be
2972 composed with the `=` operator. The expression `lval OP= val` is equivalent to
2973 `lval = lval OP val`. For example, `x = x + 1` may be written as `x += 1`.
2974
2975 Any such expression always has the [`unit`](#primitive-types) type.
2976
2977 #### Operator precedence
2978
2979 The precedence of Rust binary operators is ordered as follows, going from
2980 strong to weak:
2981
2982 ```{.text .precedence}
2983 as
2984 * / %
2985 + -
2986 << >>
2987 &
2988 ^
2989 |
2990 == != < > <= >=
2991 &&
2992 ||
2993 = ..
2994 ```
2995
2996 Operators at the same precedence level are evaluated left-to-right. [Unary
2997 operators](#unary-operator-expressions) have the same precedence level and are
2998 stronger than any of the binary operators.
2999
3000 ### Grouped expressions
3001
3002 An expression enclosed in parentheses evaluates to the result of the enclosed
3003 expression. Parentheses can be used to explicitly specify evaluation order
3004 within an expression.
3005
3006 ```{.ebnf .gram}
3007 paren_expr : '(' expr ')' ;
3008 ```
3009
3010 An example of a parenthesized expression:
3011
3012 ```
3013 let x: i32 = (2 + 3) * 4;
3014 ```
3015
3016
3017 ### Call expressions
3018
3019 ```{.ebnf .gram}
3020 expr_list : [ expr [ ',' expr ]* ] ? ;
3021 paren_expr_list : '(' expr_list ')' ;
3022 call_expr : expr paren_expr_list ;
3023 ```
3024
3025 A _call expression_ invokes a function, providing zero or more input variables
3026 and an optional location to move the function's output into. If the function
3027 eventually returns, then the expression completes.
3028
3029 Some examples of call expressions:
3030
3031 ```
3032 # fn add(x: i32, y: i32) -> i32 { 0 }
3033
3034 let x: i32 = add(1i32, 2i32);
3035 let pi: Result<f32, _> = "3.14".parse();
3036 ```
3037
3038 ### Lambda expressions
3039
3040 ```{.ebnf .gram}
3041 ident_list : [ ident [ ',' ident ]* ] ? ;
3042 lambda_expr : '|' ident_list '|' expr ;
3043 ```
3044
3045 A _lambda expression_ (sometimes called an "anonymous function expression")
3046 defines a function and denotes it as a value, in a single expression. A lambda
3047 expression is a pipe-symbol-delimited (`|`) list of identifiers followed by an
3048 expression.
3049
3050 A lambda expression denotes a function that maps a list of parameters
3051 (`ident_list`) onto the expression that follows the `ident_list`. The
3052 identifiers in the `ident_list` are the parameters to the function. These
3053 parameters' types need not be specified, as the compiler infers them from
3054 context.
3055
3056 Lambda expressions are most useful when passing functions as arguments to other
3057 functions, as an abbreviation for defining and capturing a separate function.
3058
3059 Significantly, lambda expressions _capture their environment_, which regular
3060 [function definitions](#functions) do not. The exact type of capture depends
3061 on the [function type](#function-types) inferred for the lambda expression. In
3062 the simplest and least-expensive form (analogous to a ```|| { }``` expression),
3063 the lambda expression captures its environment by reference, effectively
3064 borrowing pointers to all outer variables mentioned inside the function.
3065 Alternately, the compiler may infer that a lambda expression should copy or
3066 move values (depending on their type) from the environment into the lambda
3067 expression's captured environment.
3068
3069 In this example, we define a function `ten_times` that takes a higher-order
3070 function argument, and call it with a lambda expression as an argument:
3071
3072 ```
3073 fn ten_times<F>(f: F) where F: Fn(i32) {
3074     let mut i = 0i32;
3075     while i < 10 {
3076         f(i);
3077         i += 1;
3078     }
3079 }
3080
3081 ten_times(|j| println!("hello, {}", j));
3082 ```
3083
3084 ### Infinite loops
3085
3086 A `loop` expression denotes an infinite loop.
3087
3088 ```{.ebnf .gram}
3089 loop_expr : [ lifetime ':' ] "loop" '{' block '}';
3090 ```
3091
3092 A `loop` expression may optionally have a _label_. The label is written as
3093 a lifetime preceding the loop expression, as in `'foo: loop{ }`. If a
3094 label is present, then labeled `break` and `continue` expressions nested
3095 within this loop may exit out of this loop or return control to its head.
3096 See [Break expressions](#break-expressions) and [Continue
3097 expressions](#continue-expressions).
3098
3099 ### Break expressions
3100
3101 ```{.ebnf .gram}
3102 break_expr : "break" [ lifetime ];
3103 ```
3104
3105 A `break` expression has an optional _label_. If the label is absent, then
3106 executing a `break` expression immediately terminates the innermost loop
3107 enclosing it. It is only permitted in the body of a loop. If the label is
3108 present, then `break 'foo` terminates the loop with label `'foo`, which need not
3109 be the innermost label enclosing the `break` expression, but must enclose it.
3110
3111 ### Continue expressions
3112
3113 ```{.ebnf .gram}
3114 continue_expr : "continue" [ lifetime ];
3115 ```
3116
3117 A `continue` expression has an optional _label_. If the label is absent, then
3118 executing a `continue` expression immediately terminates the current iteration
3119 of the innermost loop enclosing it, returning control to the loop *head*. In
3120 the case of a `while` loop, the head is the conditional expression controlling
3121 the loop. In the case of a `for` loop, the head is the call-expression
3122 controlling the loop. If the label is present, then `continue 'foo` returns
3123 control to the head of the loop with label `'foo`, which need not be the
3124 innermost label enclosing the `break` expression, but must enclose it.
3125
3126 A `continue` expression is only permitted in the body of a loop.
3127
3128 ### While loops
3129
3130 ```{.ebnf .gram}
3131 while_expr : [ lifetime ':' ] "while" no_struct_literal_expr '{' block '}' ;
3132 ```
3133
3134 A `while` loop begins by evaluating the boolean loop conditional expression.
3135 If the loop conditional expression evaluates to `true`, the loop body block
3136 executes and control returns to the loop conditional expression. If the loop
3137 conditional expression evaluates to `false`, the `while` expression completes.
3138
3139 An example:
3140
3141 ```
3142 let mut i = 0;
3143
3144 while i < 10 {
3145     println!("hello");
3146     i = i + 1;
3147 }
3148 ```
3149
3150 Like `loop` expressions, `while` loops can be controlled with `break` or
3151 `continue`, and may optionally have a _label_. See [infinite
3152 loops](#infinite-loops), [break expressions](#break-expressions), and
3153 [continue expressions](#continue-expressions) for more information.
3154
3155 ### For expressions
3156
3157 ```{.ebnf .gram}
3158 for_expr : [ lifetime ':' ] "for" pat "in" no_struct_literal_expr '{' block '}' ;
3159 ```
3160
3161 A `for` expression is a syntactic construct for looping over elements provided
3162 by an implementation of `std::iter::Iterator`.
3163
3164 An example of a for loop over the contents of an array:
3165
3166 ```
3167 # type Foo = i32;
3168 # fn bar(f: Foo) { }
3169 # let a = 0;
3170 # let b = 0;
3171 # let c = 0;
3172
3173 let v: &[Foo] = &[a, b, c];
3174
3175 for e in v.iter() {
3176     bar(*e);
3177 }
3178 ```
3179
3180 An example of a for loop over a series of integers:
3181
3182 ```
3183 # fn bar(b:usize) { }
3184 for i in 0..256 {
3185     bar(i);
3186 }
3187 ```
3188
3189 Like `loop` expressions, `for` loops can be controlled with `break` or
3190 `continue`, and may optionally have a _label_. See [infinite
3191 loops](#infinite-loops), [break expressions](#break-expressions), and
3192 [continue expressions](#continue-expressions) for more information.
3193
3194 ### If expressions
3195
3196 ```{.ebnf .gram}
3197 if_expr : "if" no_struct_literal_expr '{' block '}'
3198           else_tail ? ;
3199
3200 else_tail : "else" [ if_expr | if_let_expr
3201                    | '{' block '}' ] ;
3202 ```
3203
3204 An `if` expression is a conditional branch in program control. The form of an
3205 `if` expression is a condition expression, followed by a consequent block, any
3206 number of `else if` conditions and blocks, and an optional trailing `else`
3207 block. The condition expressions must have type `bool`. If a condition
3208 expression evaluates to `true`, the consequent block is executed and any
3209 subsequent `else if` or `else` block is skipped. If a condition expression
3210 evaluates to `false`, the consequent block is skipped and any subsequent `else
3211 if` condition is evaluated. If all `if` and `else if` conditions evaluate to
3212 `false` then any `else` block is executed.
3213
3214 ### Match expressions
3215
3216 ```{.ebnf .gram}
3217 match_expr : "match" no_struct_literal_expr '{' match_arm * '}' ;
3218
3219 match_arm : attribute * match_pat "=>" [ expr "," | '{' block '}' ] ;
3220
3221 match_pat : pat [ '|' pat ] * [ "if" expr ] ? ;
3222 ```
3223
3224 A `match` expression branches on a *pattern*. The exact form of matching that
3225 occurs depends on the pattern. Patterns consist of some combination of
3226 literals, destructured arrays or enum constructors, structures and tuples,
3227 variable binding specifications, wildcards (`..`), and placeholders (`_`). A
3228 `match` expression has a *head expression*, which is the value to compare to
3229 the patterns. The type of the patterns must equal the type of the head
3230 expression.
3231
3232 In a pattern whose head expression has an `enum` type, a placeholder (`_`)
3233 stands for a *single* data field, whereas a wildcard `..` stands for *all* the
3234 fields of a particular variant.
3235
3236 A `match` behaves differently depending on whether or not the head expression
3237 is an [lvalue or an rvalue](#lvalues,-rvalues-and-temporaries). If the head
3238 expression is an rvalue, it is first evaluated into a temporary location, and
3239 the resulting value is sequentially compared to the patterns in the arms until
3240 a match is found. The first arm with a matching pattern is chosen as the branch
3241 target of the `match`, any variables bound by the pattern are assigned to local
3242 variables in the arm's block, and control enters the block.
3243
3244 When the head expression is an lvalue, the match does not allocate a temporary
3245 location (however, a by-value binding may copy or move from the lvalue). When
3246 possible, it is preferable to match on lvalues, as the lifetime of these
3247 matches inherits the lifetime of the lvalue, rather than being restricted to
3248 the inside of the match.
3249
3250 An example of a `match` expression:
3251
3252 ```
3253 let x = 1;
3254
3255 match x {
3256     1 => println!("one"),
3257     2 => println!("two"),
3258     3 => println!("three"),
3259     4 => println!("four"),
3260     5 => println!("five"),
3261     _ => println!("something else"),
3262 }
3263 ```
3264
3265 Patterns that bind variables default to binding to a copy or move of the
3266 matched value (depending on the matched value's type). This can be changed to
3267 bind to a reference by using the `ref` keyword, or to a mutable reference using
3268 `ref mut`.
3269
3270 Subpatterns can also be bound to variables by the use of the syntax `variable @
3271 subpattern`. For example:
3272
3273 ```
3274 let x = 1;
3275
3276 match x {
3277     e @ 1 ... 5 => println!("got a range element {}", e),
3278     _ => println!("anything"),
3279 }
3280 ```
3281
3282 Patterns can also dereference pointers by using the `&`, `&mut` and `box`
3283 symbols, as appropriate. For example, these two matches on `x: &i32` are
3284 equivalent:
3285
3286 ```
3287 # let x = &3;
3288 let y = match *x { 0 => "zero", _ => "some" };
3289 let z = match x { &0 => "zero", _ => "some" };
3290
3291 assert_eq!(y, z);
3292 ```
3293
3294 A pattern that's just an identifier, like `Nil` in the previous example, could
3295 either refer to an enum variant that's in scope, or bind a new variable. The
3296 compiler resolves this ambiguity by forbidding variable bindings that occur in
3297 `match` patterns from shadowing names of variants that are in scope. For
3298 example, wherever `List` is in scope, a `match` pattern would not be able to
3299 bind `Nil` as a new name. The compiler interprets a variable pattern `x` as a
3300 binding _only_ if there is no variant named `x` in scope. A convention you can
3301 use to avoid conflicts is simply to name variants with upper-case letters, and
3302 local variables with lower-case letters.
3303
3304 Multiple match patterns may be joined with the `|` operator. A range of values
3305 may be specified with `...`. For example:
3306
3307 ```
3308 # let x = 2;
3309
3310 let message = match x {
3311   0 | 1  => "not many",
3312   2 ... 9 => "a few",
3313   _      => "lots"
3314 };
3315 ```
3316
3317 Range patterns only work on scalar types (like integers and characters; not
3318 like arrays and structs, which have sub-components). A range pattern may not
3319 be a sub-range of another range pattern inside the same `match`.
3320
3321 Finally, match patterns can accept *pattern guards* to further refine the
3322 criteria for matching a case. Pattern guards appear after the pattern and
3323 consist of a bool-typed expression following the `if` keyword. A pattern guard
3324 may refer to the variables bound within the pattern they follow.
3325
3326 ```
3327 # let maybe_digit = Some(0);
3328 # fn process_digit(i: i32) { }
3329 # fn process_other(i: i32) { }
3330
3331 let message = match maybe_digit {
3332   Some(x) if x < 10 => process_digit(x),
3333   Some(x) => process_other(x),
3334   None => panic!()
3335 };
3336 ```
3337
3338 ### If let expressions
3339
3340 ```{.ebnf .gram}
3341 if_let_expr : "if" "let" pat '=' expr '{' block '}'
3342                else_tail ? ;
3343 else_tail : "else" [ if_expr | if_let_expr | '{' block '}' ] ;
3344 ```
3345
3346 An `if let` expression is semantically identical to an `if` expression but in place
3347 of a condition expression it expects a refutable let statement. If the value of the
3348 expression on the right hand side of the let statement matches the pattern, the corresponding
3349 block will execute, otherwise flow proceeds to the first `else` block that follows.
3350
3351 ### While let loops
3352
3353 ```{.ebnf .gram}
3354 while_let_expr : "while" "let" pat '=' expr '{' block '}' ;
3355 ```
3356
3357 A `while let` loop is semantically identical to a `while` loop but in place of a
3358 condition expression it expects a refutable let statement. If the value of the
3359 expression on the right hand side of the let statement matches the pattern, the
3360 loop body block executes and control returns to the pattern matching statement.
3361 Otherwise, the while expression completes.
3362
3363 ### Return expressions
3364
3365 ```{.ebnf .gram}
3366 return_expr : "return" expr ? ;
3367 ```
3368
3369 Return expressions are denoted with the keyword `return`. Evaluating a `return`
3370 expression moves its argument into the designated output location for the
3371 current function call, destroys the current function activation frame, and
3372 transfers control to the caller frame.
3373
3374 An example of a `return` expression:
3375
3376 ```
3377 fn max(a: i32, b: i32) -> i32 {
3378    if a > b {
3379       return a;
3380    }
3381    return b;
3382 }
3383 ```
3384
3385 # Type system
3386
3387 ## Types
3388
3389 Every variable, item and value in a Rust program has a type. The _type_ of a
3390 *value* defines the interpretation of the memory holding it.
3391
3392 Built-in types and type-constructors are tightly integrated into the language,
3393 in nontrivial ways that are not possible to emulate in user-defined types.
3394 User-defined types have limited capabilities.
3395
3396 ### Primitive types
3397
3398 The primitive types are the following:
3399
3400 * The "unit" type `()`, having the single "unit" value `()` (occasionally called
3401   "nil"). [^unittype]
3402 * The boolean type `bool` with values `true` and `false`.
3403 * The machine types.
3404 * The machine-dependent integer and floating-point types.
3405
3406 [^unittype]: The "unit" value `()` is *not* a sentinel "null pointer" value for
3407     reference variables; the "unit" type is the implicit return type from functions
3408     otherwise lacking a return type, and can be used in other contexts (such as
3409     message-sending or type-parametric code) as a zero-size type.]
3410
3411 #### Machine types
3412
3413 The machine types are the following:
3414
3415 * The unsigned word types `u8`, `u16`, `u32` and `u64`, with values drawn from
3416   the integer intervals [0, 2^8 - 1], [0, 2^16 - 1], [0, 2^32 - 1] and
3417   [0, 2^64 - 1] respectively.
3418
3419 * The signed two's complement word types `i8`, `i16`, `i32` and `i64`, with
3420   values drawn from the integer intervals [-(2^(7)), 2^7 - 1],
3421   [-(2^(15)), 2^15 - 1], [-(2^(31)), 2^31 - 1], [-(2^(63)), 2^63 - 1]
3422   respectively.
3423
3424 * The IEEE 754-2008 `binary32` and `binary64` floating-point types: `f32` and
3425   `f64`, respectively.
3426
3427 #### Machine-dependent integer types
3428
3429 The `usize` type is an unsigned integer type with the same number of bits as the
3430 platform's pointer type. It can represent every memory address in the process.
3431
3432 The `isize` type is a signed integer type with the same number of bits as the
3433 platform's pointer type. The theoretical upper bound on object and array size
3434 is the maximum `isize` value. This ensures that `isize` can be used to calculate
3435 differences between pointers into an object or array and can address every byte
3436 within an object along with one byte past the end.
3437
3438 ### Textual types
3439
3440 The types `char` and `str` hold textual data.
3441
3442 A value of type `char` is a [Unicode scalar value](
3443 http://www.unicode.org/glossary/#unicode_scalar_value) (i.e. a code point that
3444 is not a surrogate), represented as a 32-bit unsigned word in the 0x0000 to
3445 0xD7FF or 0xE000 to 0x10FFFF range. A `[char]` array is effectively an UCS-4 /
3446 UTF-32 string.
3447
3448 A value of type `str` is a Unicode string, represented as an array of 8-bit
3449 unsigned bytes holding a sequence of UTF-8 codepoints. Since `str` is of
3450 unknown size, it is not a _first-class_ type, but can only be instantiated
3451 through a pointer type, such as `&str` or `String`.
3452
3453 ### Tuple types
3454
3455 A tuple *type* is a heterogeneous product of other types, called the *elements*
3456 of the tuple. It has no nominal name and is instead structurally typed.
3457
3458 Tuple types and values are denoted by listing the types or values of their
3459 elements, respectively, in a parenthesized, comma-separated list.
3460
3461 Because tuple elements don't have a name, they can only be accessed by
3462 pattern-matching or by using `N` directly as a field to access the
3463 `N`th element.
3464
3465 An example of a tuple type and its use:
3466
3467 ```
3468 type Pair<'a> = (i32, &'a str);
3469 let p: Pair<'static> = (10, "hello");
3470 let (a, b) = p;
3471 assert!(b != "world");
3472 assert!(p.0 == 10);
3473 ```
3474
3475 ### Array, and Slice types
3476
3477 Rust has two different types for a list of items:
3478
3479 * `[T; N]`, an 'array'.
3480 * `&[T]`, a 'slice'.
3481
3482 An array has a fixed size, and can be allocated on either the stack or the
3483 heap.
3484
3485 A slice is a 'view' into an array. It doesn't own the data it points
3486 to, it borrows it.
3487
3488 An example of each kind:
3489
3490 ```{rust}
3491 let vec: Vec<i32> = vec![1, 2, 3];
3492 let arr: [i32; 3] = [1, 2, 3];
3493 let s: &[i32] = &vec[..];
3494 ```
3495
3496 As you can see, the `vec!` macro allows you to create a `Vec<T>` easily. The
3497 `vec!` macro is also part of the standard library, rather than the language.
3498
3499 All in-bounds elements of arrays, and slices are always initialized, and access
3500 to an array or slice is always bounds-checked.
3501
3502 ### Structure types
3503
3504 A `struct` *type* is a heterogeneous product of other types, called the
3505 *fields* of the type.[^structtype]
3506
3507 [^structtype]: `struct` types are analogous `struct` types in C,
3508     the *record* types of the ML family,
3509     or the *structure* types of the Lisp family.
3510
3511 New instances of a `struct` can be constructed with a [struct
3512 expression](#structure-expressions).
3513
3514 The memory layout of a `struct` is undefined by default to allow for compiler
3515 optimizations like field reordering, but it can be fixed with the
3516 `#[repr(...)]` attribute. In either case, fields may be given in any order in
3517 a corresponding struct *expression*; the resulting `struct` value will always
3518 have the same memory layout.
3519
3520 The fields of a `struct` may be qualified by [visibility
3521 modifiers](#re-exporting-and-visibility), to allow access to data in a
3522 structure outside a module.
3523
3524 A _tuple struct_ type is just like a structure type, except that the fields are
3525 anonymous.
3526
3527 A _unit-like struct_ type is like a structure type, except that it has no
3528 fields. The one value constructed by the associated [structure
3529 expression](#structure-expressions) is the only value that inhabits such a
3530 type.
3531
3532 ### Enumerated types
3533
3534 An *enumerated type* is a nominal, heterogeneous disjoint union type, denoted
3535 by the name of an [`enum` item](#enumerations). [^enumtype]
3536
3537 [^enumtype]: The `enum` type is analogous to a `data` constructor declaration in
3538              ML, or a *pick ADT* in Limbo.
3539
3540 An [`enum` item](#enumerations) declares both the type and a number of *variant
3541 constructors*, each of which is independently named and takes an optional tuple
3542 of arguments.
3543
3544 New instances of an `enum` can be constructed by calling one of the variant
3545 constructors, in a [call expression](#call-expressions).
3546
3547 Any `enum` value consumes as much memory as the largest variant constructor for
3548 its corresponding `enum` type.
3549
3550 Enum types cannot be denoted *structurally* as types, but must be denoted by
3551 named reference to an [`enum` item](#enumerations).
3552
3553 ### Recursive types
3554
3555 Nominal types &mdash; [enumerations](#enumerated-types) and
3556 [structures](#structure-types) &mdash; may be recursive. That is, each `enum`
3557 constructor or `struct` field may refer, directly or indirectly, to the
3558 enclosing `enum` or `struct` type itself. Such recursion has restrictions:
3559
3560 * Recursive types must include a nominal type in the recursion
3561   (not mere [type definitions](#type-definitions),
3562    or other structural types such as [arrays](#array,-and-slice-types) or [tuples](#tuple-types)).
3563 * A recursive `enum` item must have at least one non-recursive constructor
3564   (in order to give the recursion a basis case).
3565 * The size of a recursive type must be finite;
3566   in other words the recursive fields of the type must be [pointer types](#pointer-types).
3567 * Recursive type definitions can cross module boundaries, but not module *visibility* boundaries,
3568   or crate boundaries (in order to simplify the module system and type checker).
3569
3570 An example of a *recursive* type and its use:
3571
3572 ```
3573 enum List<T> {
3574     Nil,
3575     Cons(T, Box<List<T>>)
3576 }
3577
3578 let a: List<i32> = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil))));
3579 ```
3580
3581 ### Pointer types
3582
3583 All pointers in Rust are explicit first-class values. They can be copied,
3584 stored into data structures, and returned from functions. There are two
3585 varieties of pointer in Rust:
3586
3587 * References (`&`)
3588   : These point to memory _owned by some other value_.
3589     A reference type is written `&type` for some lifetime-variable `f`,
3590     or just `&'a type` when you need an explicit lifetime.
3591     Copying a reference is a "shallow" operation:
3592     it involves only copying the pointer itself.
3593     Releasing a reference typically has no effect on the value it points to,
3594     with the exception of temporary values, which are released when the last
3595     reference to them is released.
3596
3597 * Raw pointers (`*`)
3598   : Raw pointers are pointers without safety or liveness guarantees.
3599     Raw pointers are written as `*const T` or `*mut T`,
3600     for example `*const int` means a raw pointer to an integer.
3601     Copying or dropping a raw pointer has no effect on the lifecycle of any
3602     other value. Dereferencing a raw pointer or converting it to any other
3603     pointer type is an [`unsafe` operation](#unsafe-functions).
3604     Raw pointers are generally discouraged in Rust code;
3605     they exist to support interoperability with foreign code,
3606     and writing performance-critical or low-level functions.
3607
3608 The standard library contains additional 'smart pointer' types beyond references
3609 and raw pointers.
3610
3611 ### Function types
3612
3613 The function type constructor `fn` forms new function types. A function type
3614 consists of a possibly-empty set of function-type modifiers (such as `unsafe`
3615 or `extern`), a sequence of input types and an output type.
3616
3617 An example of a `fn` type:
3618
3619 ```
3620 fn add(x: i32, y: i32) -> i32 {
3621   return x + y;
3622 }
3623
3624 let mut x = add(5,7);
3625
3626 type Binop = fn(i32, i32) -> i32;
3627 let bo: Binop = add;
3628 x = bo(5,7);
3629 ```
3630
3631 ### Closure types
3632
3633 ```{.ebnf .notation}
3634 closure_type := [ 'unsafe' ] [ '<' lifetime-list '>' ] '|' arg-list '|'
3635                 [ ':' bound-list ] [ '->' type ]
3636 lifetime-list := lifetime | lifetime ',' lifetime-list
3637 arg-list := ident ':' type | ident ':' type ',' arg-list
3638 bound-list := bound | bound '+' bound-list
3639 bound := path | lifetime
3640 ```
3641
3642 The type of a closure mapping an input of type `A` to an output of type `B` is
3643 `|A| -> B`. A closure with no arguments or return values has type `||`.
3644
3645 An example of creating and calling a closure:
3646
3647 ```rust
3648 let captured_var = 10;
3649
3650 let closure_no_args = || println!("captured_var={}", captured_var);
3651
3652 let closure_args = |arg: i32| -> i32 {
3653   println!("captured_var={}, arg={}", captured_var, arg);
3654   arg // Note lack of semicolon after 'arg'
3655 };
3656
3657 fn call_closure<F: Fn(), G: Fn(i32) -> i32>(c1: F, c2: G) {
3658   c1();
3659   c2(2);
3660 }
3661
3662 call_closure(closure_no_args, closure_args);
3663
3664 ```
3665
3666 ### Trait objects
3667
3668 Every trait item (see [traits](#traits)) defines a type with the same name as
3669 the trait. This type is called the _trait object_ of the trait. Trait objects
3670 permit "late binding" of methods, dispatched using _virtual method tables_
3671 ("vtables"). Whereas most calls to trait methods are "early bound" (statically
3672 resolved) to specific implementations at compile time, a call to a method on an
3673 trait objects is only resolved to a vtable entry at compile time. The actual
3674 implementation for each vtable entry can vary on an object-by-object basis.
3675
3676 Given a pointer-typed expression `E` of type `&T` or `Box<T>`, where `T`
3677 implements trait `R`, casting `E` to the corresponding pointer type `&R` or
3678 `Box<R>` results in a value of the _trait object_ `R`. This result is
3679 represented as a pair of pointers: the vtable pointer for the `T`
3680 implementation of `R`, and the pointer value of `E`.
3681
3682 An example of a trait object:
3683
3684 ```
3685 trait Printable {
3686   fn stringify(&self) -> String;
3687 }
3688
3689 impl Printable for i32 {
3690   fn stringify(&self) -> String { self.to_string() }
3691 }
3692
3693 fn print(a: Box<Printable>) {
3694    println!("{}", a.stringify());
3695 }
3696
3697 fn main() {
3698    print(Box::new(10) as Box<Printable>);
3699 }
3700 ```
3701
3702 In this example, the trait `Printable` occurs as a trait object in both the
3703 type signature of `print`, and the cast expression in `main`.
3704
3705 ### Type parameters
3706
3707 Within the body of an item that has type parameter declarations, the names of
3708 its type parameters are types:
3709
3710 ```ignore
3711 fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
3712     if xs.is_empty() {
3713        return vec![];
3714     }
3715     let first: B = f(xs[0].clone());
3716     let mut rest: Vec<B> = map(f, xs.slice(1, xs.len()));
3717     rest.insert(0, first);
3718     return rest;
3719 }
3720 ```
3721
3722 Here, `first` has type `B`, referring to `map`'s `B` type parameter; and `rest`
3723 has type `Vec<B>`, a vector type with element type `B`.
3724
3725 ### Self types
3726
3727 The special type `self` has a meaning within methods inside an impl item. It
3728 refers to the type of the implicit `self` argument. For example, in:
3729
3730 ```
3731 trait Printable {
3732   fn make_string(&self) -> String;
3733 }
3734
3735 impl Printable for String {
3736     fn make_string(&self) -> String {
3737         (*self).clone()
3738     }
3739 }
3740 ```
3741
3742 `self` refers to the value of type `String` that is the receiver for a call to
3743 the method `make_string`.
3744
3745 # Special traits
3746
3747 Several traits define special evaluation behavior.
3748
3749 ## The `Copy` trait
3750
3751 The `Copy` trait changes the semantics of a type implementing it. Values whose
3752 type implements `Copy` are copied rather than moved upon assignment.
3753
3754 ## The `Sized` trait
3755
3756 The `Sized` trait indicates that the size of this type is known at compile-time.
3757
3758 ## The `Drop` trait
3759
3760 The `Drop` trait provides a destructor, to be run whenever a value of this type
3761 is to be destroyed.
3762
3763 # Memory model
3764
3765 A Rust program's memory consists of a static set of *items* and a *heap*.
3766 Immutable portions of the heap may be safely shared between threads, mutable
3767 portions may not be safely shared, but several mechanisms for effectively-safe
3768 sharing of mutable values, built on unsafe code but enforcing a safe locking
3769 discipline, exist in the standard library.
3770
3771 Allocations in the stack consist of *variables*, and allocations in the heap
3772 consist of *boxes*.
3773
3774 ### Memory allocation and lifetime
3775
3776 The _items_ of a program are those functions, modules and types that have their
3777 value calculated at compile-time and stored uniquely in the memory image of the
3778 rust process. Items are neither dynamically allocated nor freed.
3779
3780 The _heap_ is a general term that describes boxes.  The lifetime of an
3781 allocation in the heap depends on the lifetime of the box values pointing to
3782 it. Since box values may themselves be passed in and out of frames, or stored
3783 in the heap, heap allocations may outlive the frame they are allocated within.
3784
3785 ### Memory ownership
3786
3787 When a stack frame is exited, its local allocations are all released, and its
3788 references to boxes are dropped.
3789
3790 ### Variables
3791
3792 A _variable_ is a component of a stack frame, either a named function parameter,
3793 an anonymous [temporary](#lvalues,-rvalues-and-temporaries), or a named local
3794 variable.
3795
3796 A _local variable_ (or *stack-local* allocation) holds a value directly,
3797 allocated within the stack's memory. The value is a part of the stack frame.
3798
3799 Local variables are immutable unless declared otherwise like: `let mut x = ...`.
3800
3801 Function parameters are immutable unless declared with `mut`. The `mut` keyword
3802 applies only to the following parameter (so `|mut x, y|` and `fn f(mut x:
3803 Box<i32>, y: Box<i32>)` declare one mutable variable `x` and one immutable
3804 variable `y`).
3805
3806 Methods that take either `self` or `Box<Self>` can optionally place them in a
3807 mutable variable by prefixing them with `mut` (similar to regular arguments):
3808
3809 ```
3810 trait Changer {
3811     fn change(mut self) -> Self;
3812     fn modify(mut self: Box<Self>) -> Box<Self>;
3813 }
3814 ```
3815
3816 Local variables are not initialized when allocated; the entire frame worth of
3817 local variables are allocated at once, on frame-entry, in an uninitialized
3818 state. Subsequent statements within a function may or may not initialize the
3819 local variables. Local variables can be used only after they have been
3820 initialized; this is enforced by the compiler.
3821
3822 # Linkage
3823
3824 The Rust compiler supports various methods to link crates together both
3825 statically and dynamically. This section will explore the various methods to
3826 link Rust crates together, and more information about native libraries can be
3827 found in the [ffi section of the book][ffi].
3828
3829 In one session of compilation, the compiler can generate multiple artifacts
3830 through the usage of either command line flags or the `crate_type` attribute.
3831 If one or more command line flag is specified, all `crate_type` attributes will
3832 be ignored in favor of only building the artifacts specified by command line.
3833
3834 * `--crate-type=bin`, `#[crate_type = "bin"]` - A runnable executable will be
3835   produced. This requires that there is a `main` function in the crate which
3836   will be run when the program begins executing. This will link in all Rust and
3837   native dependencies, producing a distributable binary.
3838
3839 * `--crate-type=lib`, `#[crate_type = "lib"]` - A Rust library will be produced.
3840   This is an ambiguous concept as to what exactly is produced because a library
3841   can manifest itself in several forms. The purpose of this generic `lib` option
3842   is to generate the "compiler recommended" style of library. The output library
3843   will always be usable by rustc, but the actual type of library may change from
3844   time-to-time. The remaining output types are all different flavors of
3845   libraries, and the `lib` type can be seen as an alias for one of them (but the
3846   actual one is compiler-defined).
3847
3848 * `--crate-type=dylib`, `#[crate_type = "dylib"]` - A dynamic Rust library will
3849   be produced. This is different from the `lib` output type in that this forces
3850   dynamic library generation. The resulting dynamic library can be used as a
3851   dependency for other libraries and/or executables. This output type will
3852   create `*.so` files on linux, `*.dylib` files on osx, and `*.dll` files on
3853   windows.
3854
3855 * `--crate-type=staticlib`, `#[crate_type = "staticlib"]` - A static system
3856   library will be produced. This is different from other library outputs in that
3857   the Rust compiler will never attempt to link to `staticlib` outputs. The
3858   purpose of this output type is to create a static library containing all of
3859   the local crate's code along with all upstream dependencies. The static
3860   library is actually a `*.a` archive on linux and osx and a `*.lib` file on
3861   windows. This format is recommended for use in situations such as linking
3862   Rust code into an existing non-Rust application because it will not have
3863   dynamic dependencies on other Rust code.
3864
3865 * `--crate-type=rlib`, `#[crate_type = "rlib"]` - A "Rust library" file will be
3866   produced. This is used as an intermediate artifact and can be thought of as a
3867   "static Rust library". These `rlib` files, unlike `staticlib` files, are
3868   interpreted by the Rust compiler in future linkage. This essentially means
3869   that `rustc` will look for metadata in `rlib` files like it looks for metadata
3870   in dynamic libraries. This form of output is used to produce statically linked
3871   executables as well as `staticlib` outputs.
3872
3873 Note that these outputs are stackable in the sense that if multiple are
3874 specified, then the compiler will produce each form of output at once without
3875 having to recompile. However, this only applies for outputs specified by the
3876 same method. If only `crate_type` attributes are specified, then they will all
3877 be built, but if one or more `--crate-type` command line flag is specified,
3878 then only those outputs will be built.
3879
3880 With all these different kinds of outputs, if crate A depends on crate B, then
3881 the compiler could find B in various different forms throughout the system. The
3882 only forms looked for by the compiler, however, are the `rlib` format and the
3883 dynamic library format. With these two options for a dependent library, the
3884 compiler must at some point make a choice between these two formats. With this
3885 in mind, the compiler follows these rules when determining what format of
3886 dependencies will be used:
3887
3888 1. If a static library is being produced, all upstream dependencies are
3889    required to be available in `rlib` formats. This requirement stems from the
3890    reason that a dynamic library cannot be converted into a static format.
3891
3892    Note that it is impossible to link in native dynamic dependencies to a static
3893    library, and in this case warnings will be printed about all unlinked native
3894    dynamic dependencies.
3895
3896 2. If an `rlib` file is being produced, then there are no restrictions on what
3897    format the upstream dependencies are available in. It is simply required that
3898    all upstream dependencies be available for reading metadata from.
3899
3900    The reason for this is that `rlib` files do not contain any of their upstream
3901    dependencies. It wouldn't be very efficient for all `rlib` files to contain a
3902    copy of `libstd.rlib`!
3903
3904 3. If an executable is being produced and the `-C prefer-dynamic` flag is not
3905    specified, then dependencies are first attempted to be found in the `rlib`
3906    format. If some dependencies are not available in an rlib format, then
3907    dynamic linking is attempted (see below).
3908
3909 4. If a dynamic library or an executable that is being dynamically linked is
3910    being produced, then the compiler will attempt to reconcile the available
3911    dependencies in either the rlib or dylib format to create a final product.
3912
3913    A major goal of the compiler is to ensure that a library never appears more
3914    than once in any artifact. For example, if dynamic libraries B and C were
3915    each statically linked to library A, then a crate could not link to B and C
3916    together because there would be two copies of A. The compiler allows mixing
3917    the rlib and dylib formats, but this restriction must be satisfied.
3918
3919    The compiler currently implements no method of hinting what format a library
3920    should be linked with. When dynamically linking, the compiler will attempt to
3921    maximize dynamic dependencies while still allowing some dependencies to be
3922    linked in via an rlib.
3923
3924    For most situations, having all libraries available as a dylib is recommended
3925    if dynamically linking. For other situations, the compiler will emit a
3926    warning if it is unable to determine which formats to link each library with.
3927
3928 In general, `--crate-type=bin` or `--crate-type=lib` should be sufficient for
3929 all compilation needs, and the other options are just available if more
3930 fine-grained control is desired over the output format of a Rust crate.
3931
3932 # Appendix: Rationales and design tradeoffs
3933
3934 *TODO*.
3935
3936 # Appendix: Influences
3937
3938 Rust is not a particularly original language, with design elements coming from
3939 a wide range of sources. Some of these are listed below (including elements
3940 that have since been removed):
3941
3942 * SML, OCaml: algebraic datatypes, pattern matching, type inference,
3943   semicolon statement separation
3944 * C++: references, RAII, smart pointers, move semantics, monomorphisation,
3945   memory model
3946 * ML Kit, Cyclone: region based memory management
3947 * Haskell (GHC): typeclasses, type families
3948 * Newsqueak, Alef, Limbo: channels, concurrency
3949 * Erlang: message passing, task failure, ~~linked task failure~~,
3950   ~~lightweight concurrency~~
3951 * Swift: optional bindings
3952 * Scheme: hygienic macros
3953 * C#: attributes
3954 * Ruby: ~~block syntax~~
3955 * NIL, Hermes: ~~typestate~~
3956 * [Unicode Annex #31](http://www.unicode.org/reports/tr31/): identifier and
3957   pattern syntax
3958
3959 [ffi]: book/ffi.html
3960 [plugin]: book/plugins.html