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