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