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