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