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