1 % Rust Reference Manual
5 This document is the reference manual for the Rust programming language. It
6 provides three kinds of material:
8 - Chapters that formally define the language grammar and, for each
9 construct, informally describe its semantics and give examples of its
11 - Chapters that informally describe the memory model, concurrency model,
12 runtime services, linkage model and debugging facilities.
13 - Appendix chapters providing rationale and references to languages that
14 influenced the design.
16 This document does not serve as a tutorial introduction to the
17 language. Background familiarity with the language is assumed. A separate
18 tutorial document is available at <http://doc.rust-lang.org/doc/tutorial.html>
19 to help acquire such background familiarity.
21 This document also does not serve as a reference to the core or standard
22 libraries included in the language distribution. Those libraries are
23 documented separately by extracting documentation attributes from their
24 source code. Formatted documentation can be found at the following
27 - Core library: <http://doc.rust-lang.org/doc/core>
28 - Standard library: <http://doc.rust-lang.org/doc/std>
32 Rust is a work in progress. The language continues to evolve as the design
33 shifts and is fleshed out in working code. Certain parts work, certain parts
34 do not, certain parts will be removed or changed.
36 This manual is a snapshot written in the present tense. All features described
37 exist in working code unless otherwise noted, but some are quite primitive or
38 remain to be further modified by planned work. Some may be temporary. It is a
39 *draft*, and we ask that you not take anything you read here as final.
41 If you have suggestions to make, please try to focus them on *reductions* to
42 the language: possible features that can be combined or omitted. We aim to
43 keep the size and complexity of the language under control.
45 **Note on grammar:** The grammar for Rust given in this document is rough and
46 very incomplete; only a modest number of sections have accompanying grammar
47 rules. Formalizing the grammar accepted by the Rust parser is ongoing work,
48 but future versions of this document will contain a complete
49 grammar. Moreover, we hope that this grammar will be be extracted and verified
50 as LL(1) by an automated grammar-analysis tool, and further tested against the
51 Rust sources. Preliminary versions of this automation exist, but are not yet
56 Rust's grammar is defined over Unicode codepoints, each conventionally
57 denoted `U+XXXX`, for 4 or more hexadecimal digits `X`. _Most_ of Rust's
58 grammar is confined to the ASCII range of Unicode, and is described in this
59 document by a dialect of Extended Backus-Naur Form (EBNF), specifically a
60 dialect of EBNF supported by common automated LL(k) parsing tools such as
61 `llgen`, rather than the dialect given in ISO 14977. The dialect can be
62 defined self-referentially as follows:
64 ~~~~~~~~ {.ebnf .notation}
67 rule : nonterminal ':' productionrule ';' ;
68 productionrule : production [ '|' production ] * ;
70 term : element repeats ;
71 element : LITERAL | IDENTIFIER | '[' productionrule ']' ;
72 repeats : [ '*' | '+' ] NUMBER ? | NUMBER ? | '?' ;
78 - Whitespace in the grammar is ignored.
79 - Square brackets are used to group rules.
80 - `LITERAL` is a single printable ASCII character, or an escaped hexadecimal
81 ASCII code of the form `\xQQ`, in single quotes, denoting the corresponding
82 Unicode codepoint `U+00QQ`.
83 - `IDENTIFIER` is a nonempty string of ASCII letters and underscores.
84 - The `repeat` forms apply to the adjacent `element`, and are as follows:
85 - `?` means zero or one repetition
86 - `*` means zero or more repetitions
87 - `+` means one or more repetitions
88 - NUMBER trailing a repeat symbol gives a maximum repetition count
89 - NUMBER on its own gives an exact repetition count
91 This EBNF dialect should hopefully be familiar to many readers.
93 ## Unicode productions
95 A small number of productions in Rust's grammar permit Unicode codepoints
96 outside the ASCII range; these productions are defined in terms of character
97 properties given by the Unicode standard, rather than ASCII-range
98 codepoints. These are given in the section [Special Unicode
99 Productions](#special-unicode-productions).
101 ## String table productions
103 Some rules in the grammar -- notably [unary
104 operators](#unary-operator-expressions), [binary
105 operators](#binary-operator-expressions), [keywords](#keywords) and [reserved
106 words](#reserved-words) -- are given in a simplified form: as a listing of a
107 table of unquoted, printable whitespace-separated strings. These cases form a
108 subset of the rules regarding the [token](#tokens) rule, and are assumed to be
109 the result of a lexical-analysis phase feeding the parser, driven by a DFA,
110 operating over the disjunction of all such string table entries.
112 When such a string enclosed in double-quotes (`"`) occurs inside the
113 grammar, it is an implicit reference to a single member of such a string table
114 production. See [tokens](#tokens) for more information.
121 Rust input is interpreted as a sequence of Unicode codepoints encoded in
122 UTF-8. No normalization is performed during input processing. Most Rust
123 grammar rules are defined in terms of printable ASCII-range codepoints, but
124 a small number are defined in terms of Unicode properties or explicit
125 codepoint lists. ^[Surrogate definitions for the special Unicode productions
126 are provided to the grammar verifier, restricted to ASCII range, when
127 verifying the grammar in this document.]
129 ## Special Unicode Productions
131 The following productions in the Rust grammar are defined in terms of
132 Unicode properties: `ident`, `non_null`, `non_star`, `non_eol`, `non_slash`,
133 `non_single_quote` and `non_double_quote`.
137 The `ident` production is any nonempty Unicode string of the following form:
139 - The first character has property `XID_start`
140 - The remaining characters have property `XID_continue`
142 that does _not_ occur in the set of [keywords](#keywords) or [reserved
143 words](#reserved-words).
145 Note: `XID_start` and `XID_continue` as character properties cover the
146 character ranges used to form the more familiar C and Java language-family
149 ### Delimiter-restricted productions
151 Some productions are defined by exclusion of particular Unicode characters:
153 - `non_null` is any single Unicode character aside from `U+0000` (null)
154 - `non_eol` is `non_null` restricted to exclude `U+000A` (`'\n'`)
155 - `non_star` is `non_null` restricted to exclude `U+002A` (`*`)
156 - `non_slash` is `non_null` restricted to exclude `U+002F` (`/`)
157 - `non_single_quote` is `non_null` restricted to exclude `U+0027` (`'`)
158 - `non_double_quote` is `non_null` restricted to exclude `U+0022` (`"`)
162 ~~~~~~~~ {.ebnf .gram}
163 comment : block_comment | line_comment ;
164 block_comment : "/*" block_comment_body * "*/" ;
165 block_comment_body : block_comment | non_star * | '*' non_slash ;
166 line_comment : "//" non_eol * ;
169 Comments in Rust code follow the general C++ style of line and block-comment
170 forms, with proper nesting of block-comment delimiters. Comments are
171 interpreted as a form of whitespace.
175 ~~~~~~~~ {.ebnf .gram}
176 whitespace_char : '\x20' | '\x09' | '\x0a' | '\x0d' ;
177 whitespace : [ whitespace_char | comment ] + ;
180 The `whitespace_char` production is any nonempty Unicode string consisting of any
181 of the following Unicode characters: `U+0020` (space, `' '`), `U+0009` (tab,
182 `'\t'`), `U+000A` (LF, `'\n'`), `U+000D` (CR, `'\r'`).
184 Rust is a "free-form" language, meaning that all forms of whitespace serve
185 only to separate _tokens_ in the grammar, and have no semantic significance.
187 A Rust program has identical meaning if each whitespace element is replaced
188 with any other legal whitespace element, such as a single space character.
192 ~~~~~~~~ {.ebnf .gram}
193 simple_token : keyword | reserved | unop | binop ;
194 token : simple_token | ident | literal | symbol | whitespace token ;
197 Tokens are primitive productions in the grammar defined by regular
198 (non-recursive) languages. "Simple" tokens are given in [string table
199 production](#string-table-productions) form, and occur in the rest of the
200 grammar as double-quoted strings. Other tokens have exact rules given.
204 The keywords in [crate files](#crate-files) are the following strings:
207 import export use mod dir
210 The keywords in [source files](#source-files) are the following strings:
212 *TODO* split these between type keywords and regular (value) keywords,
213 and define two different `identifier` productions for the different
218 be bind block bool break
219 char check claim const cont
222 f32 f64 fail false float fn for
223 i16 i32 i64 i8 if iface impl import in int
231 u16 u32 u64 u8 uint unchecked unsafe use
236 Any of these have special meaning in their respective grammars, and are
237 excluded from the `ident` rule.
241 The reserved words are the following strings:
249 Any of these may have special meaning in future versions of the language, so
250 are excluded from the `ident` rule.
254 A literal is an expression consisting of a single token, rather than a
255 sequence of tokens, that immediately and directly denotes the value it
256 evaluates to, rather than referring to it by name or some other evaluation
257 rule. A literal is a form of constant expression, so is evaluated (primarily)
260 ~~~~~~~~ {.ebnf .gram}
261 literal : string_lit | char_lit | num_lit ;
264 #### Character and string literals
266 ~~~~~~~~ {.ebnf .gram}
267 char_lit : '\x27' char_body '\x27' ;
268 string_lit : '"' string_body * '"' ;
270 char_body : non_single_quote
271 | '\x5c' [ '\x27' | common_escape ] ;
273 string_body : non_double_quote
274 | '\x5c' [ '\x22' | common_escape ] ;
276 common_escape : '\x5c'
282 hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
283 | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
285 dec_digit : '0' | nonzero_dec ;
286 nonzero_dec: '1' | '2' | '3' | '4'
287 | '5' | '6' | '7' | '8' | '9' ;
290 A _character literal_ is a single Unicode character enclosed within two
291 `U+0027` (single-quote) characters, with the exception of `U+0027` itself,
292 which must be _escaped_ by a preceding U+005C character (`\`).
294 A _string literal_ is a sequence of any Unicode characters enclosed within
295 two `U+0022` (double-quote) characters, with the exception of `U+0022`
296 itself, which must be _escaped_ by a preceding `U+005C` character (`\`).
298 Some additional _escapes_ are available in either character or string
299 literals. An escape starts with a `U+005C` (`\`) and continues with one of
302 * An _8-bit codepoint escape_ escape starts with `U+0078` (`x`) and is
303 followed by exactly two _hex digits_. It denotes the Unicode codepoint
304 equal to the provided hex value.
305 * A _16-bit codepoint escape_ starts with `U+0075` (`u`) and is followed
306 by exactly four _hex digits_. It denotes the Unicode codepoint equal to
307 the provided hex value.
308 * A _32-bit codepoint escape_ starts with `U+0055` (`U`) and is followed
309 by exactly eight _hex digits_. It denotes the Unicode codepoint equal to
310 the provided hex value.
311 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
312 (`r`), or `U+0074` (`t`), denoting the unicode values `U+000A` (LF),
313 `U+000D` (CR) or `U+0009` (HT) respectively.
314 * The _backslash escape_ is the character U+005C (`\`) which must be
315 escaped in order to denote *itself*.
319 ~~~~~~~~ {.ebnf .gram}
321 num_lit : nonzero_dec [ dec_digit | '_' ] * num_suffix ?
322 | '0' [ [ dec_digit | '_' ] + num_suffix ?
323 | 'b' [ '1' | '0' | '_' ] + int_suffix ?
324 | 'x' [ hex_digit | '-' ] + int_suffix ? ] ;
326 num_suffix : int_suffix | float_suffix ;
328 int_suffix : 'u' int_suffix_size ?
329 | 'i' int_suffix_size ;
330 int_suffix_size : [ '8' | '1' '6' | '3' '2' | '6' '4' ] ;
332 float_suffix : [ exponent | '.' dec_lit exponent ? ] float_suffix_ty ? ;
333 float_suffix_ty : 'f' [ '3' '2' | '6' '4' ] ;
334 exponent : ['E' | 'e'] ['-' | '+' ] ? dec_lit ;
335 dec_lit : [ dec_digit | '_' ] + ;
338 A _number literal_ is either an _integer literal_ or a _floating-point
339 literal_. The grammar for recognizing the two kinds of literals is mixed,
340 as they are differentiated by suffixes.
342 ##### Integer literals
344 An _integer literal_ has one of three forms:
346 * A _decimal literal_ starts with a *decimal digit* and continues with any
347 mixture of *decimal digits* and _underscores_.
348 * A _hex literal_ starts with the character sequence `U+0030` `U+0078`
349 (`0x`) and continues as any mixture hex digits and underscores.
350 * A _binary literal_ starts with the character sequence `U+0030` `U+0062`
351 (`0b`) and continues as any mixture binary digits and underscores.
353 By default, an integer literal is of type `int`. An integer literal may be
354 followed (immediately, without any spaces) by an _integer suffix_, which
355 changes the type of the literal. There are two kinds of integer literal
358 * The `u` suffix gives the literal type `uint`.
359 * Each of the signed and unsigned machine types `u8`, `i8`,
360 `u16`, `i16`, `u32`, `i32`, `u64` and `i64`
361 give the literal the corresponding machine type.
364 Examples of integer literals of various forms:
372 0b1111_1111_1001_0000_i32; // type i32
375 ##### Floating-point literals
377 A _floating-point literal_ has one of two forms:
379 * Two _decimal literals_ separated by a period
380 character `U+002E` (`.`), with an optional _exponent_ trailing after the
381 second decimal literal.
382 * A single _decimal literal_ followed by an _exponent_.
384 By default, a floating-point literal is of type `float`. A
385 floating-point literal may be followed (immediately, without any
386 spaces) by a _floating-point suffix_, which changes the type of the
387 literal. There are three floating-point suffixes: `f` (for the base
388 `float` type), `f32`, and `f64` (the 32-bit and 64-bit floating point
391 A set of suffixes are also reserved to accommodate literal support for
392 types corresponding to reserved tokens. The reserved suffixes are `f16`,
393 `f80`, `f128`, `m`, `m32`, `m64` and `m128`.
395 Examples of floating-point literals of various forms:
402 12E+99_f64; // type f64
405 ##### Nil and boolean literals
407 The _nil value_, the only value of the type by the same name, is
408 written as `()`. The two values of the boolean type are written `true`
413 ~~~~~~~~ {.ebnf .gram}
415 | '#' | '[' | ']' | '(' | ')' | '{' | '}'
419 Symbols are a general class of printable [token](#tokens) that play structural
420 roles in a variety of grammar productions. They are catalogued here for
421 completeness as the set of remaining miscellaneous printable tokens that do not
422 otherwise appear as [unary operators](#unary-operator-expressions), [binary
423 operators](#binary-operator-expressions), [keywords](#keywords) or [reserved
424 words](#reserved-words).
429 ~~~~~~~~ {.ebnf .gram}
431 expr_path : ident [ "::" expr_path_tail ] + ;
432 expr_path_tail : '<' type_expr [ ',' type_expr ] + '>'
435 type_path : ident [ type_path_tail ] + ;
436 type_path_tail : '<' type_expr [ ',' type_expr ] + '>'
441 A _path_ is a sequence of one or more path components _logically_ separated by
442 a namespace qualifier (`::`). If a path consists of only one component, it may
443 refer to either an [item](#items) or a [slot](#slot-declarations) in a local
444 control scope. If a path has multiple components, it refers to an item.
446 Every item has a _canonical path_ within its crate, but the path naming an
447 item is only meaningful within a given crate. There is no global namespace
448 across crates; an item's canonical path merely identifies it within the crate.
450 Two examples of simple paths consisting of only identifier components:
457 Path components are usually [identifiers](#identifiers), but the trailing
458 component of a path may be an angle-bracket-enclosed list of type
459 arguments. In [expression](#expressions) context, the type argument list is
460 given after a final (`::`) namespace qualifier in order to disambiguate it
461 from a relational expression involving the less-than symbol (`<`). In type
462 expression context, the final namespace qualifier is omitted.
464 Two examples of paths with type arguments:
467 type t = map::hashtbl<int,str>; // Type arguments used in a type expression
468 let x = id::<int>(10); // Type arguments used in a call expression
472 # Crates and source files
474 Rust is a *compiled* language. Its semantics are divided along a
475 *phase distinction* between compile-time and run-time. Those semantic
476 rules that have a *static interpretation* govern the success or failure
477 of compilation. A program that fails to compile due to violation of a
478 compile-time rule has no defined semantics at run-time; the compiler should
479 halt with an error report, and produce no executable artifact.
481 The compilation model centres on artifacts called _crates_. Each compilation
482 is directed towards a single crate in source form, and if successful,
483 produces a single crate in binary form: either an executable or a library.
485 A _crate_ is a unit of compilation and linking, as well as versioning,
486 distribution and runtime loading. A crate contains a _tree_ of nested
487 [module](#modules) scopes. The top level of this tree is a module that is
488 anonymous -- from the point of view of paths within the module -- and any item
489 within a crate has a canonical [module path](#paths) denoting its location
490 within the crate's module tree.
492 Crates are provided to the Rust compiler through two kinds of file:
494 - _crate files_, that end in `.rc` and each define a `crate`.
495 - _source files_, that end in `.rs` and each define a `module`.
497 The Rust compiler is always invoked with a single input file, and always
498 produces a single output crate.
500 When the Rust compiler is invoked with a crate file, it reads the _explicit_
501 definition of the crate it's compiling from that file, and populates the
502 crate with modules derived from all the source files referenced by the
503 crate, reading and processing all the referenced modules at once.
505 When the Rust compiler is invoked with a source file, it creates an
506 _implicit_ crate and treats the source file as though it was referenced as
507 the sole module populating this implicit crate. The module name is derived
508 from the source file name, with the `.rs` extension removed.
512 ~~~~~~~~ {.ebnf .gram}
513 crate : attribute [ ';' | attribute* directive ]
515 directive : view_item | dir_directive | source_directive ;
518 A crate file contains a crate definition, for which the production above
519 defines the grammar. It is a declarative grammar that guides the compiler in
520 assembling a crate from component source files.^[A crate is somewhat
521 analogous to an *assembly* in the ECMA-335 CLI model, a *library* in the
522 SML/NJ Compilation Manager, a *unit* in the Owens and Flatt module system,
523 or a *configuration* in Mesa.] A crate file describes:
525 * [Attributes](#attributes) about the crate, such as author, name, version,
526 and copyright. These are used for linking, versioning and distributing
528 * The source-file and directory modules that make up the crate.
529 * Any `use`, `import` or `export` [view items](#view-items) that apply to the
530 anonymous module at the top-level of the crate's module tree.
532 An example of a crate file:
535 // Linkage attributes
536 #[ link(name = "projx"
538 uuid = "9cccc5d5-aceb-4af5-8285-811211826b82") ];
540 // Additional metadata attributes
541 #[ desc = "Project X",
543 author = "Jane Doe" ];
546 use std (ver = "1.0");
548 // Define some modules.
559 A `dir_directive` forms a module in the module tree making up the crate, as
560 well as implicitly relating that module to a directory in the filesystem
561 containing source files and/or further subdirectories. The filesystem
562 directory associated with a `dir_directive` module can either be explicit,
563 or if omitted, is implicitly the same name as the module.
565 A `source_directive` references a source file, either explicitly or
566 implicitly by combining the module name with the file extension `.rs`. The
567 module contained in that source file is bound to the module path formed by
568 the `dir_directive` modules containing the `source_directive`.
572 A source file contains a `module`: that is, a sequence of zero or more
573 `item` definitions. Each source file is an implicit module, the name and
574 location of which -- in the module tree of the current crate -- is defined
575 from outside the source file: either by an explicit `source_directive` in
576 a referencing crate file, or by the filename of the source file itself.
579 # Items and attributes
581 A crate is a collection of [items](#items), each of which may have some number
582 of [attributes](#attributes) attached to it.
586 ~~~~~~~~ {.ebnf .gram}
587 item : mod_item | fn_item | type_item | enum_item
588 | res_item | iface_item | impl_item ;
591 An _item_ is a component of a crate; some module items can be defined in crate
592 files, but most are defined in source files. Items are organized within a
593 crate by a nested set of [modules](#modules). Every crate has a single
594 "outermost" anonymous module; all further items within the crate have
595 [paths](#paths) within the module tree of the crate.
597 Items are entirely determined at compile-time, remain constant during
598 execution, and may reside in read-only memory.
600 There are several kinds of item:
602 * [modules](#modules)
603 * [functions](#functions)
604 * [type definitions](#type-definitions)
605 * [enumerations](#enumerations)
606 * [resources](#resources)
607 * [interfaces](#interfaces)
608 * [implementations](#implementations)
610 Some items form an implicit scope for the declaration of sub-items. In other
611 words, within a function or module, declarations of items can (in many cases)
612 be mixed with the statements, control blocks, and similar artifacts that
613 otherwise compose the item body. The meaning of these scoped items is the same
614 as if the item was declared outside the scope -- it is still a static item --
615 except that the item's *path name* within the module namespace is qualified by
616 the name of the enclosing item, or is private to the enclosing item (in the
617 case of functions). The exact locations in which sub-items may be declared is
618 given by the grammar.
620 All items except modules may be *parametrized* by type. Type parameters are
621 given as a comma-separated list of identifiers enclosed in angle brackets
622 (`<...>`), after the name of the item and before its definition. The type
623 parameters of an item are considered "part of the name", not the type of the
624 item; in order to refer to the type-parametrized item, a referencing
625 [path](#paths) must in general provide type arguments as a list of
626 comma-separated types enclosed within angle brackets. In practice, the
627 type-inference system can usually infer such argument types from
628 context. There are no general type-parametric types, only type-parametric
634 ~~~~~~~~ {.ebnf .gram}
635 mod_item : "mod" ident '{' mod '}' ;
636 mod : [ view_item | item ] * ;
639 A module is a container for zero or more [view items](#view-items) and zero or
640 more [items](#items). The view items manage the visibility of the items
641 defined within the module, as well as the visibility of names from outside the
642 module when referenced from inside the module.
644 A _module item_ is a module, surrounded in braces, named, and prefixed with
645 the keyword `mod`. A module item introduces a new, named module into the tree
646 of modules making up a crate. Modules can nest arbitrarily.
648 An example of a module:
652 type complex = (f64,f64);
669 ~~~~~~~~ {.ebnf .gram}
670 view_item : use_decl | import_decl | export_decl ;
673 A view item manages the namespace of a module; it does not define new items
674 but simply changes the visibility of other items. There are several kinds of
677 * [use declarations](#use-declarations)
678 * [import declarations](#import-declarations)
679 * [export declarations](#export-declarations)
681 ##### Use declarations
683 ~~~~~~~~ {.ebnf .gram}
684 use_decl : "use" ident [ '(' link_attrs ')' ] ? ;
685 link_attrs : link_attr [ ',' link_attrs ] + ;
686 link_attr : ident '=' literal ;
689 A _use declaration_ specifies a dependency on an external crate. The external
690 crate is then imported into the declaring scope as the `ident` provided in the
693 The external crate is resolved to a specific `soname` at compile time, and a
694 runtime linkage requirement to that `soname` is passed to the linker for
695 loading at runtime. The `soname` is resolved at compile time by scanning the
696 compiler's library path and matching the `link_attrs` provided in the
697 `use_decl` against any `#link` attributes that were declared on the external
698 crate when it was compiled. If no `link_attrs` are provided, a default `name`
699 attribute is assumed, equal to the `ident` given in the `use_decl`.
701 Two examples of `use` declarations:
704 use pcre (uuid = "54aba0f8-a7b1-4beb-92f1-4cf625264841");
706 use std; // equivalent to: use std ( name = "std" );
708 use ruststd (name = "std"); // linking to 'std' under another name
711 ##### Import declarations
713 ~~~~~~~~ {.ebnf .gram}
714 import_decl : "import" ident [ '=' path
717 path_glob : ident [ "::" path_glob ] ?
719 | '{' ident [ ',' ident ] * '}'
722 An _import declaration_ creates one or more local name bindings synonymous
723 with some other [path](#paths). Usually an import declaration is used to
724 shorten the path required to refer to a module item.
726 *Note*: unlike many languages, Rust's `import` declarations do *not* declare
727 linkage-dependency with external crates. Linkage dependencies are
728 independently declared with [`use` declarations](#use-declarations).
730 Imports support a number of "convenience" notations:
732 * Importing as a different name than the imported name, using the
733 syntax `import x = p::q::r;`.
734 * Importing a list of paths differing only in final element, using
735 the glob-like brace syntax `import a::b::{c,d,e,f};`
736 * Importing all paths matching a given prefix, using the glob-like
737 asterisk syntax `import a::b::*;`
739 An example of imports:
742 import foo = core::info;
743 import std::math::sin;
744 import std::str::{char_at, hash};
745 import core::option::*;
748 // Equivalent to 'log(core::info, std::math::sin(1.0));'
751 // Equivalent to 'log(core::info, core::option::some(1.0));'
752 log(info, some(1.0));
754 // Equivalent to 'log(core::info,
755 // std::str::hash(std::str::char_at("foo")));'
756 log(info, hash(char_at("foo")));
760 ##### Export declarations
762 ~~~~~~~~ {.ebnf .gram}
763 export_decl : "export" ident [ ',' ident ] * ;
766 An _export declaration_ restricts the set of local names within a module that
767 can be accessed from code outside the module. By default, all _local items_ in
768 a module are exported; imported paths are not automatically re-exported by
769 default. If a module contains an explicit `export` declaration, this
770 declaration replaces the default export with the export specified.
772 An example of an export:
783 fn helper(x: int, y: int) {
789 foo::primary(); // Will compile.
790 foo::helper(2,3) // ERROR: will not compile.
794 Multiple names may be exported from a single export declaration:
798 export primary, secondary;
809 fn helper(x: int, y: int) {
818 A _function item_ defines a sequence of [statements](#statements) and an
819 optional final [expression](#expressions) associated with a name and a set of
820 parameters. Functions are declared with the keyword `fn`. Functions declare a
821 set of *input [slots](#slot-declarations)* as parameters, through which the
822 caller passes arguments into the function, and an *output
823 [slot](#slot-declarations)* through which the function passes results back to
826 A function may also be copied into a first class *value*, in which case the
827 value has the corresponding [*function type*](#function-types), and can be
828 used otherwise exactly as a function item (with a minor additional cost of
829 calling the function indirectly).
831 Every control path in a function logically ends with a `ret` expression or a
832 diverging expression. If the outermost block of a function has a
833 value-producing expression in its final-expression position, that expression
834 is interpreted as an implicit `ret` expression applied to the
837 An example of a function:
840 fn add(x: int, y: int) -> int {
845 #### Diverging functions
847 A special kind of function can be declared with a `!` character where the
848 output slot type would normally be. For example:
851 fn my_err(s: str) -> ! {
857 We call such functions "diverging" because they never return a value to the
858 caller. Every control path in a diverging function must end with a
859 [`fail`](#fail-expressions) or a call to another diverging function on every
860 control path. The `!` annotation does *not* denote a type. Rather, the result
861 type of a diverging function is a special type called $\bot$ ("bottom") that
862 unifies with any type. Rust has no syntax for $\bot$.
864 It might be necessary to declare a diverging function because as mentioned
865 previously, the typechecker checks that every control path in a function ends
866 with a [`ret`](#return-expressions) or diverging expression. So, if `my_err`
867 were declared without the `!` annotation, the following code would not
871 fn f(i: int) -> int {
876 my_err("Bad number!");
881 The typechecker would complain that `f` doesn't return a value in the
882 `else` branch. Adding the `!` annotation on `my_err` would
883 express that `f` requires no explicit `ret`, as if it returns
884 control to the caller, it returns a value (true because it never returns
887 #### Predicate functions
889 Any pure boolean function is called a *predicate function*, and may be used in
890 a [constraint](#constraints), as part of the static [typestate
891 system](#typestate-system). A predicate declaration is identical to a function
892 declaration, except that it is declared with the additional keyword `pure`. In
893 addition, the typechecker checks the body of a predicate with a restricted set
894 of typechecking rules. A predicate
896 * may not contain an assignment or self-call expression; and
897 * may only call other predicates, not general functions.
899 An example of a predicate:
902 pure fn lt_42(x: int) -> bool {
907 A non-boolean function may also be declared with `pure fn`. This allows
908 predicates to call non-boolean functions as long as they are pure. For example:
911 pure fn pure_length<T>(ls: list<T>) -> uint { /* ... */ }
913 pure fn nonempty_list<T>(ls: list<T>) -> bool { pure_length(ls) > 0u }
916 In this example, `nonempty_list` is a predicate---it can be used in a
917 typestate constraint---but the auxiliary function `pure_length` is
920 *TODO:* should actually define referential transparency.
922 The effect checking rules previously enumerated are a restricted set of
923 typechecking rules meant to approximate the universe of observably
924 referentially transparent Rust procedures conservatively. Sometimes, these
925 rules are *too* restrictive. Rust allows programmers to violate these rules by
926 writing predicates that the compiler cannot prove to be referentially
927 transparent, using an escape-hatch feature called "unchecked blocks". When
928 writing code that uses unchecked blocks, programmers should always be aware
929 that they have an obligation to show that the code *behaves* referentially
930 transparently at all times, even if the compiler cannot *prove* automatically
931 that the code is referentially transparent. In the presence of unchecked
932 blocks, the compiler provides no static guarantee that the code will behave as
933 expected at runtime. Rather, the programmer has an independent obligation to
934 verify the semantics of the predicates they write.
936 *TODO:* last two sentences are vague.
938 An example of a predicate that uses an unchecked block:
941 fn pure_foldl<T, U: copy>(ls: list<T>, u: U, f: block(&T, &U) -> U) -> U {
944 cons(hd, tl) { f(hd, pure_foldl(*tl, f(hd, u), f)) }
948 pure fn pure_length<T>(ls: list<T>) -> uint {
949 fn count<T>(_t: T, u: uint) -> uint { u + 1u }
951 pure_foldl(ls, 0u, count)
956 Despite its name, `pure_foldl` is a `fn`, not a `pure fn`, because there is no
957 way in Rust to specify that the higher-order function argument `f` is a pure
958 function. So, to use `foldl` in a pure list length function that a predicate
959 could then use, we must use an `unchecked` block wrapped around the call to
960 `pure_foldl` in the definition of `pure_length`.
962 #### Generic functions
964 A _generic function_ allows one or more _parameterized types_ to
965 appear in its signature. Each type parameter must be explicitly
966 declared, in an angle-bracket-enclosed, comma-separated list following
970 fn iter<T>(seq: [T], f: block(T)) {
971 for elt: T in seq { f(elt); }
973 fn map<T, U>(seq: [T], f: block(T) -> U) -> [U] {
975 for elt in seq { acc += [f(elt)]; }
980 Inside the function signature and body, the name of the type parameter
981 can be used as a type name.
983 When a generic function is referenced, its type is instantiated based
984 on the context of the reference. For example, calling the `iter`
985 function defined above on `[1, 2]` will instantiate type parameter `T`
986 with `int`, and require the closure parameter to have type
989 Since a parameter type is opaque to the generic function, the set of
990 operations that can be performed on it is limited. Values of parameter
991 type can always be moved, but they can only be copied when the
992 parameter is given a [`copy` bound](#type-kinds).
995 fn id<T: copy>(x: T) -> T { x }
998 Similarly, [interface](#interfaces) bounds can be specified for type
999 parameters to allow methods of that interface to be called on values
1002 ### Type definitions
1004 A _type definition_ defines a new name for an existing [type](#types). Type
1005 definitions are declared with the keyword `type`. Every value has a single,
1006 specific type; the type-specified aspects of a value include:
1008 * Whether the value is composed of sub-values or is indivisible.
1009 * Whether the value represents textual or numerical information.
1010 * Whether the value represents integral or floating-point information.
1011 * The sequence of memory operations required to access the value.
1012 * The *kind* of the type (pinned, unique or shared).
1014 For example, the type `{x: u8, y: u8`} defines the set of immutable values
1015 that are composite records, each containing two unsigned 8-bit integers
1016 accessed through the components `x` and `y`, and laid out in memory with the
1017 `x` component preceding the `y` component.
1021 An _enumeration item_ simultaneously declares a new nominal
1022 [enumerated type](#enumerated-types) as well as a set of *constructors* that
1023 can be used to create or pattern-match values of the corresponding enumerated
1026 The constructors of an `enum` type may be recursive: that is, each constructor
1027 may take an argument that refers, directly or indirectly, to the enumerated
1028 type the constructor is a member of. Such recursion has restrictions:
1030 * Recursive types can be introduced only through `enum` constructors.
1031 * A recursive `enum` item must have at least one non-recursive constructor (in
1032 order to give the recursion a basis case).
1033 * The recursive argument of recursive `enum` constructors must be [*box*
1034 values](#box-types) (in order to bound the in-memory size of the
1036 * Recursive type definitions can cross module boundaries, but not module
1037 *visibility* boundaries or crate boundaries (in order to simplify the
1041 An example of an `enum` item and its use:
1049 let a: animal = dog;
1053 An example of a *recursive* `enum` item and its use:
1061 let a: list<int> = cons(7, @cons(13, @nil));
1066 _Resources_ are values that have a destructor associated with them. A
1067 _resource item_ is used to declare resource type and constructor.
1070 resource file_descriptor(fd: int) {
1071 std::os::libc::close(fd);
1075 Calling the `file_descriptor` constructor function on an integer will
1076 produce a value with the `file_descriptor` type. Resource types have a
1077 noncopyable [type kind](#type-kinds), and thus may not be copied. The
1078 semantics guarantee that for each constructed resources value, the
1079 destructor will run once: when the value is disposed of (barring
1080 drastic program termination that somehow prevents unwinding from taking
1081 place). For stack-allocated values, disposal happens when the value
1082 goes out of scope. For values in shared boxes, it happens when the
1083 reference count of the box reaches zero.
1085 The argument to the resource constructor is stored in the resulting
1086 value, and can be accessed using the dereference (`*`) [unary
1087 operator](#unary-operator-expressions).
1091 An _interface item_ describes a set of method types. _[implementation
1092 items](#implementations)_ can be used to provide implementations of
1093 those methods for a specific type.
1098 fn bounding_box() -> bounding_box;
1102 This defines an interface with two methods. All values which have
1103 [implementations](#implementations) of this interface in scope can
1104 have their `draw` and `bounding_box` methods called, using
1105 `value.bounding_box()` [syntax](#field-expressions).
1107 Type parameters can be specified for an interface to make it generic.
1108 These appear after the name, using the same syntax used in [generic
1109 functions](#generic-functions).
1114 fn elt_at(n: uint) -> T;
1119 Generic functions may use interfaces as bounds on their type
1120 parameters. This will have two effects: only types that implement the
1121 interface can be used to instantiate the parameter, and within the
1122 generic function, the methods of the interface can be called on values
1123 that have the parameter's type. For example:
1126 fn draw_twice<T: shape>(surface: surface, sh: T) {
1132 Interface items also define a type with the same name as the
1133 interface. Values of this type are created by
1134 [casting](#type-cast-expressions) values (of a type for which an
1135 implementation of the given interface is in scope) to the interface
1139 let myshape: shape = mycircle as shape;
1142 The resulting value is a reference counted box containing the value
1143 that was cast along with information that identify the methods of the
1144 implementation that was used. Values with an interface type can always
1145 have methods of their interface called on them, and can be used to
1146 instantiate type parameters that are bounded on their interface.
1150 An _implementation item_ provides an implementation of an
1151 [interfaces](#interfaces) for a type.
1154 type circle = {radius: float, center: point};
1156 impl circle_shape of shape for circle {
1157 fn draw(s: surface) { do_draw_circle(s, self); }
1158 fn bounding_box() -> bounding_box {
1159 let r = self.radius;
1160 {x: self.center.x - r, y: self.center.y - r,
1161 width: 2 * r, height: 2 * r}
1166 This defines an implementation named `circle_shape` of interface
1167 `shape` for type `circle`. The name of the implementation is the name
1168 by which it is imported and exported, but has no further significance.
1169 It may be omitted to default to the name of the interface that was
1170 implemented. Implementation names do not conflict the way other names
1171 do: multiple implementations with the same name may exist in a scope at
1174 It is possible to define an implementation without referencing an
1175 interface. The methods in such an implementation can only be used
1176 statically (as direct calls on the values of the type that the
1177 implementation targets). In such an implementation, the `of` clause is
1178 not given, and the name is mandatory.
1181 impl uint_loops for uint {
1182 fn times(f: block(uint)) {
1184 while i < self { f(i); i += 1u; }
1189 _When_ an interface is specified, all methods declared as part of the
1190 interface must be present, with matching types and type parameter
1191 counts, in the implementation.
1193 An implementation can take type parameters, which can be different
1194 from the type parameters taken by the interface it implements. They
1195 are written after the name of the implementation, or if that is not
1196 specified, after the `impl` keyword.
1199 impl <T> of seq<T> for [T] {
1202 impl of seq<bool> for u32 {
1203 /* Treat the integer as a sequence of bits */
1209 ~~~~~~~~{.ebnf .gram}
1210 attribute : '#' '[' attr_list ']' ;
1211 attr_list : attr [ ',' attr_list ]*
1212 attr : ident [ '=' literal
1213 | '(' attr_list ')' ] ? ;
1216 Static entities in Rust -- crates, modules and items -- may have _attributes_
1217 applied to them. ^[Attributes in Rust are modeled on Attributes in ECMA-335,
1218 C#] An attribute is a general, free-form piece of metadata that is interpreted
1219 according to name, convention, and language and compiler version. Attributes
1220 may appear as any of:
1222 * A single identifier, the attribute name
1223 * An identifier followed by the equals sign '=' and a literal, providing a key/value pair
1224 * An identifier followed by a parenthesized list of sub-attribute arguments
1226 Attributes are applied to an entity by placing them within a hash-list
1227 (`#[...]`) as either a prefix to the entity or as a semicolon-delimited
1228 declaration within the entity body.
1230 An example of attributes:
1233 // A function marked as a unit test
1239 // General metadata applied to the enclosing module or crate.
1242 // A conditionally-compiled module
1243 #[cfg(target_os="linux")]
1248 // A documentation attribute
1249 #[doc = "Add two numbers together."]
1250 fn add(x: int, y: int) { x + y }
1253 In future versions of Rust, user-provided extensions to the compiler will be
1254 able to interpret attributes. When this facility is provided, the compiler
1255 will distinguish will be made between language-reserved and user-available
1258 At present, only the Rust compiler interprets attributes, so all attribute
1259 names are effectively reserved. Some significant attributes include:
1261 * The `doc` attribute, for documenting code in-place.
1262 * The `cfg` attribute, for conditional-compilation by build-configuration.
1263 * The `link` attribute, for describing linkage metadata for a crate.
1264 * The `test` attribute, for marking functions as unit tests.
1266 Other attributes may be added or removed during development of the language.
1269 # Statements and expressions
1271 Rust is _primarily_ an expression language. This means that most forms of
1272 value-producing or effect-causing evaluation are directed by the uniform
1273 syntax category of _expressions_. Each kind of expression can typically _nest_
1274 within each other kind of expression, and rules for evaluation of expressions
1275 involve specifying both the value produced by the expression and the order in
1276 which its sub-expressions are themselves evaluated.
1278 In contrast, statements in Rust serve _mostly_ to contain and explicitly
1279 sequence expression evaluation.
1283 A _statement_ is a component of a block, which is in turn a component of an
1284 outer [expression](#expressions) or [function](#functions). When a function is
1285 spawned into a [task](#tasks), the task *executes* statements in an order
1286 determined by the body of the enclosing function. Each statement causes the
1287 task to perform certain actions.
1289 Rust has two kinds of statement:
1290 [declaration statements](#declaration-statements) and
1291 [expression statements](#expression-statements).
1293 ### Declaration statements
1295 A _declaration statement_ is one that introduces a *name* into the enclosing
1296 statement block. The declared name may denote a new slot or a new item.
1298 #### Item declarations
1300 An _item declaration statement_ has a syntactic form identical to an
1301 [item](#items) declaration within a module. Declaring an item -- a function,
1302 enumeration, type, resource, interface, implementation or module -- locally
1303 within a statement block is simply a way of restricting its scope to a narrow
1304 region containing all of its uses; it is otherwise identical in meaning to
1305 declaring the item outside the statement block.
1307 Note: there is no implicit capture of the function's dynamic environment when
1308 declaring a function-local item.
1311 #### Slot declarations
1313 ~~~~~~~~{.ebnf .gram}
1314 let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
1315 init : [ '=' | '<-' ] expr ;
1319 A _slot declaration_ has one one of two forms:
1321 * `let` `pattern` `optional-init`;
1322 * `let` `pattern` : `type` `optional-init`;
1324 Where `type` is a type expression, `pattern` is an irrefutable pattern (often
1325 just the name of a single slot), and `optional-init` is an optional
1326 initializer. If present, the initializer consists of either an assignment
1327 operator (`=`) or move operator (`<-`), followed by an expression.
1329 Both forms introduce a new slot into the enclosing block scope. The new slot
1330 is visible from the point of declaration until the end of the enclosing block
1333 The former form, with no type annotation, causes the compiler to infer the
1334 static type of the slot through unification with the types of values assigned
1335 to the slot in the remaining code in the block scope. Inference only occurs on
1336 frame-local variable, not argument slots. Function signatures must
1337 always declare types for all argument slots.
1340 ### Expression statements
1342 An _expression statement_ is one that evaluates an [expression](#expressions)
1343 and drops its result. The purpose of an expression statement is often to cause
1344 the side effects of the expression's evaluation.
1348 An expression plays the dual roles of causing side effects and producing a
1349 *value*. Expressions are said to *evaluate to* a value, and the side effects
1350 are caused during *evaluation*. Many expressions contain sub-expressions as
1351 operands; the definition of each kind of expression dictates whether or not,
1352 and in which order, it will evaluate its sub-expressions, and how the
1353 expression's value derives from the value of its sub-expressions.
1355 In this way, the structure of execution -- both the overall sequence of
1356 observable side effects and the final produced value -- is dictated by the
1357 structure of expressions. Blocks themselves are expressions, so the nesting
1358 sequence of block, statement, expression, and block can repeatedly nest to an
1361 ### Literal expressions
1363 A _literal expression_ consists of one of the [literal](#literals)
1364 forms described earlier. It directly describes a number, character,
1365 string, boolean value, or the nil value.
1367 ~~~~~~~~ {.literals}
1369 "hello"; // string type
1370 '5'; // character type
1374 ### Tuple expressions
1376 Tuples are written by enclosing two or more comma-separated
1377 expressions in parentheses. They are used to create [tuple-typed](#tuple-types)
1385 ### Record expressions
1387 ~~~~~~~~{.ebnf .gram}
1388 rec_expr : '{' ident ':' expr
1389 [ ',' ident ':' expr ] *
1393 A _[record](#record-types) expression_ is one or more comma-separated
1394 name-value pairs enclosed by braces. A fieldname can be any identifier
1395 (including reserved words), and is separated from its value expression
1396 by a colon. To indicate that a field is mutable, the `mutable` keyword
1397 is written before its name.
1401 {name: "Joe", age: 35u, score: 100_000};
1402 {ident: "X", mutable count: 0u};
1405 The order of the fields in a record expression is significant, and
1406 determines the type of the resulting value. `{a: u8, b: u8}` and `{b:
1407 u8, a: u8}` are two different fields.
1409 A record expression can terminate with the word `with` followed by an
1410 expression to denote a functional update. The expression following
1411 `with` (the base) must be of a record type that includes at least all the
1412 fields mentioned in the record expression. A new record will be
1413 created, of the same type as the base expression, with the given
1414 values for the fields that were explicitly specified, and the values
1415 in the base record for all other fields. The ordering of the fields in
1416 such a record expression is not significant.
1419 let base = {x: 1, y: 2, z: 3};
1420 {y: 0, z: 10 with base};
1423 ### Field expressions
1425 ~~~~~~~~{.ebnf .gram}
1426 field_expr : expr '.' expr
1429 A dot can be used to access a field in a record.
1436 A field access on a record is an _lval_ referring to the value of that
1437 field. When the field is mutable, it can be
1438 [assigned](#assignment-expressions) to.
1440 When the type of the expression to the left of the dot is a boxed
1441 record, it is automatically derferenced to make the field access
1444 Field access syntax is overloaded for [interface method](#interfaces)
1445 access. When no matching field is found, or the expression to the left
1446 of the dot is not a (boxed) record, an
1447 [implementation](#implementations) that matches this type and the
1448 given method name is looked up instead, and the result of the
1449 expression is this method, with its _self_ argument bound to the
1450 expression on the left of the dot.
1452 ### Vector expressions
1454 ~~~~~~~~{.ebnf .gram}
1455 vec_expr : '[' "mutable" ? [ expr [ ',' expr ] * ] ? ']'
1458 A _[vector](#vector-types) expression_ is written by enclosing zero or
1459 more comma-separated expressions of uniform type in square brackets.
1460 The keyword `mutable` can be written after the opening bracket to
1461 indicate that the elements of the resulting vector may be mutated.
1462 When no mutability is specified, the vector is immutable.
1466 ["a", "b", "c", "d"];
1467 [mutable 0u8, 0u8, 0u8, 0u8];
1470 ### Index expressions
1472 ~~~~~~~~{.ebnf .gram}
1473 idx_expr : expr '[' expr ']'
1477 [Vector](#vector-types)-typed expressions can be indexed by writing a
1478 square-bracket-enclosed expression (the index) after them. When the
1479 vector is mutable, the resulting _lval_ can be assigned to.
1481 Indices are zero-based, and may be of any integral type. Vector access
1482 is bounds-checked at run-time. When the check fails, it will put the
1483 task in a _failing state_.
1487 [mutable 'x', 'y'][1] = 'z';
1488 ["a", "b"][10]; // fails
1491 ### Unary operator expressions
1493 Rust defines five unary operators. They are all written as prefix
1494 operators, before the expression they apply to.
1497 : Negation. May only be applied to numeric types.
1499 : Dereference. When applied to a [box](#box-types) or
1500 [resource](#resources) type, it accesses the inner value. For
1501 mutable boxes, the resulting _lval_ can be assigned to. For
1502 [enums](#enumerated-types) that have only a single variant,
1503 containing a single parameter, the dereference operator accesses
1506 : Logical negation. On the boolean type, this flips between `true` and
1507 `false`. On integer types, this inverts the individual bits in the
1508 two's complement representation of the value.
1510 : [Boxing](#box-types) operators. Allocate a box to hold the value
1511 they are applied to, and store the value in it. `@` creates a
1512 shared, reference-counted box, whereas `~` creates a unique box.
1514 ### Binary operator expressions
1516 ~~~~~~~~{.ebnf .gram}
1517 binop_expr : expr binop expr ;
1520 Binary operators expressions are given in terms of
1521 [operator precedence](#operator-precedence).
1523 #### Arithmetic operators
1525 Binary arithmetic expressions require both their operands to be of the
1526 same type, and can be applied only to numeric types, with the
1527 exception of `+`, which acts both as addition operator on numbers and
1528 as concatenate operator on vectors and strings.
1531 : Addition and vector/string concatenation.
1541 #### Bitwise operators
1543 Bitwise operators apply only to integer types, and perform their
1544 operation on the bits of the two's complement representation of the
1554 : Logical left shift.
1556 : Logical right shift.
1558 : Arithmetic right shift.
1560 #### Lazy boolean operators
1562 The operators `||` and `&&` may be applied to operands of boolean
1563 type. The first performs the 'or' operation, and the second the 'and'
1564 operation. They differ from `|` and `&` in that the right-hand operand
1565 is only evaluated when the left-hand operand does not already
1566 determine the outcome of the expression. That is, `||` only evaluates
1567 its right-hand operand when the left-hand operand evaluates to `false`,
1568 and `&&` only when it evaluates to `true`.
1570 #### Comparison operators
1581 : Less than or equal.
1583 : Greater than or equal.
1585 The binary comparison operators can be applied to any two operands of
1586 the same type, and produce a boolean value.
1588 *TODO* details on how types are descended during comparison.
1590 #### Type cast expressions
1592 A type cast expression is denoted with the binary operator `as`.
1594 Executing an `as` expression casts the value on the left-hand side to the type
1595 on the right-hand side.
1597 A numeric value can be cast to any numeric type. A native pointer value can
1598 be cast to or from any integral type or native pointer type. Any other cast
1599 is unsupported and will fail to compile.
1601 An example of an `as` expression:
1604 fn avg(v: [float]) -> float {
1605 let sum: float = sum(v);
1606 let sz: float = std::vec::len(v) as float;
1611 A cast is a *trivial cast* iff the type of the casted expression and the
1612 target type are identical after replacing all occurences of `int`, `uint`,
1613 `float` with their machine type equivalents of the target architecture in both
1617 #### Binary move expressions
1619 A _binary move expression_ consists of an *lval* followed by a left-pointing
1620 arrow (`<-`) and an *rval* expression.
1622 Evaluating a move expression causes, as a side effect, the *rval* to be
1623 *moved* into the *lval*. If the *rval* was itself an *lval*, it must be a
1624 local variable, as it will be de-initialized in the process.
1626 Evaluating a move expression does not change reference counts, nor does it
1627 cause a deep copy of any unique structure pointed to by the moved
1628 *rval*. Instead, the move expression represents an indivisible *transfer of
1629 ownership* from the right-hand-side to the left-hand-side of the
1630 expression. No allocation or destruction is entailed.
1632 An example of three different move expressions:
1640 #### Swap expressions
1642 A _swap expression_ consists of an *lval* followed by a bi-directional arrow
1643 (`<->`) and another *lval* expression.
1645 Evaluating a swap expression causes, as a side effect, the vales held in the
1646 left-hand-side and right-hand-side *lvals* to be exchanged indivisibly.
1648 Evaluating a move expression does not change reference counts, nor does it
1649 cause a deep copy of any unique structure pointed to by the moved
1650 *rval*. Instead, the move expression represents an indivisible *exchange of
1651 ownership* between the right-hand-side to the left-hand-side of the
1652 expression. No allocation or destruction is entailed.
1654 An example of three different swap expressions:
1663 #### Assignment expressions
1665 An _assignment expression_ consists of an *lval* expression followed by an
1666 equals sign (`=`) and an *rval* expression.
1668 Evaluating an assignment expression is equivalent to evaluating a [binary move
1669 expression](#binary-move-expressions) applied to a [unary copy
1670 expression](#unary-copy-expressions). For example, the following two
1671 expressions have the same effect:
1678 The former is just more terse and familiar.
1680 #### Operator-assignment expressions
1682 The `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, `>>`, and `>>>`
1683 operators may be composed with the `=` operator. The expression `lval
1684 OP= val` is equivalent to `lval = lval OP val`. For example, `x = x +
1685 1` may be written as `x += 1`.
1687 #### Operator precedence
1689 The precedence of Rust binary operators is ordered as follows, going
1690 from strong to weak:
1706 ### Unary copy expressions
1708 ~~~~~~~~{.ebnf .gram}
1709 copy_expr : "copy" expr ;
1712 A _unary copy expression_ consists of the unary `copy` operator applied to
1713 some argument expression.
1715 Evaluating a copy expression first evaluates the argument expression, then
1716 copies the resulting value, allocating any memory necessary to hold the new
1719 [Shared boxes](#box-types) (type `@`) are, as usual, shallow-copied, as they
1720 may be cyclic. [Unique boxes](#box-types), [vectors](#vector-types) and
1721 similar unique types are deep-copied.
1723 Since the binary [assignment operator](#assignment-expressions) `=` performs a
1724 copy implicitly, the unary copy operator is typically only used to cause an
1725 argument to a function to be copied and passed by value.
1727 An example of a copy expression:
1730 fn mutate(vec: [mutable int]) {
1734 let v = [mutable 1,2,3];
1736 mutate(copy v); // Pass a copy
1738 assert v[0] == 1; // Original was not modified
1741 ### Unary move expressions
1743 ~~~~~~~~{.ebnf .gram}
1744 move_expr : "move" expr ;
1747 This is used to indicate that the referenced _lval_ must be moved out,
1748 rather than copied, when evaluating this expression. It will only have
1749 an effect when the expression is _stored_ somewhere or passed to a
1750 function that takes ownership of it.
1757 Any access to `x` after applying the `move` operator to it is invalid,
1758 since it is no longer initialized at that point.
1760 ### Call expressions
1762 ~~~~~~~~ {.abnf .gram}
1763 expr_list : [ expr [ ',' expr ]* ] ? ;
1764 paren_expr_list : '(' expr_list ')' ;
1765 call_expr : expr paren_expr_list ;
1768 A _call expression_ invokes a function, providing zero or more input slots and
1769 an optional reference slot to serve as the function's output, bound to the
1770 `lval` on the right hand side of the call. If the function eventually returns,
1771 then the expression completes.
1773 A call expression statically requires that the precondition declared in the
1774 callee's signature is satisfied by the expression prestate. In this way,
1775 typestates propagate through function boundaries.
1777 An example of a call expression:
1780 let x: int = add(1, 2);
1784 ### Bind expressions
1786 A _bind expression_ constructs a new function from an existing function.^[The
1787 `bind` expression is analogous to the `bind` expression in the Sather
1788 language.] The new function has zero or more of its arguments *bound* into a
1789 new, hidden boxed tuple that holds the bindings. For each concrete argument
1790 passed in the `bind` expression, the corresponding parameter in the existing
1791 function is *omitted* as a parameter of the new function. For each argument
1792 passed the placeholder symbol `_` in the `bind` expression, the corresponding
1793 parameter of the existing function is *retained* as a parameter of the new
1796 Any subsequent invocation of the new function with residual arguments causes
1797 invocation of the existing function with the combination of bound arguments
1798 and residual arguments that was specified during the binding.
1800 An example of a `bind` expression:
1803 fn add(x: int, y: int) -> int {
1806 type single_param_fn = fn(int) -> int;
1808 let add4: single_param_fn = bind add(4, _);
1810 let add5: single_param_fn = bind add(_, 5);
1812 assert (add(4,5) == add4(5));
1813 assert (add(4,5) == add5(4));
1817 A `bind` expression generally stores a copy of the bound arguments in a
1818 hidden, boxed tuple, owned by the resulting first-class function. For each
1819 bound slot in the bound function's signature, space is allocated in the hidden
1820 tuple and populated with a copy of the bound value.
1822 A `bind` expression is an alternative way of constructing a shared function
1823 closure; the [`fn@` expression](#shared-function-expressions) form is another
1826 ### Shared function expressions
1830 ### Unique function expressions
1834 ### While expressions
1836 ~~~~~~~~{.ebnf .gram}
1837 while_expr : "while" expr '{' block '}'
1838 | "do" '{' block '}' "while" expr ;
1841 A `while` expression is a loop construct. A `while` loop may be either a
1842 simple `while` or a `do`-`while` loop.
1844 In the case of a simple `while`, the loop begins by evaluating the boolean
1845 loop conditional expression. If the loop conditional expression evaluates to
1846 `true`, the loop body block executes and control returns to the loop
1847 conditional expression. If the loop conditional expression evaluates to
1848 `false`, the `while` expression completes.
1850 In the case of a `do`-`while`, the loop begins with an execution of the loop
1851 body. After the loop body executes, it evaluates the loop conditional
1852 expression. If it evaluates to `true`, control returns to the beginning of the
1853 loop body. If it evaluates to `false`, control exits the loop.
1855 An example of a simple `while` expression:
1864 An example of a `do`-`while` expression:
1874 ### Break expressions
1876 ~~~~~~~~{.ebnf .gram}
1877 break_expr : "break" ;
1880 Executing a `break` expression immediately terminates the innermost loop
1881 enclosing it. It is only permitted in the body of a loop.
1883 ### Continue expressions
1885 ~~~~~~~~{.ebnf .gram}
1886 break_expr : "cont" ;
1889 Evaluating a `cont` expression immediately terminates the current iteration of
1890 the innermost loop enclosing it, returning control to the loop *head*. In the
1891 case of a `while` loop, the head is the conditional expression controlling the
1892 loop. In the case of a `for` loop, the head is the vector-element increment
1893 controlling the loop.
1895 A `cont` expression is only permitted in the body of a loop.
1900 ~~~~~~~~{.ebnf .gram}
1901 for_expr : "for" pat "in" expr '{' block '}' ;
1904 A _for loop_ is controlled by a vector or string. The for loop bounds-checks
1905 the underlying sequence *once* when initiating the loop, then repeatedly
1906 executes the loop body with the loop variable referencing the successive
1907 elements of the underlying sequence, one iteration per sequence element.
1909 An example a for loop:
1912 let v: [foo] = [a, b, c];
1922 ~~~~~~~~{.ebnf .gram}
1923 if_expr : "if" expr '{' block '}'
1924 [ "else" else_tail ] ? ;
1926 else_tail : "else" [ if_expr
1930 An `if` expression is a conditional branch in program control. The form of
1931 an `if` expression is a condition expression, followed by a consequent
1932 block, any number of `else if` conditions and blocks, and an optional
1933 trailing `else` block. The condition expressions must have type
1934 `bool`. If a condition expression evaluates to `true`, the
1935 consequent block is executed and any subsequent `else if` or `else`
1936 block is skipped. If a condition expression evaluates to `false`, the
1937 consequent block is skipped and any subsequent `else if` condition is
1938 evaluated. If all `if` and `else if` conditions evaluate to `false`
1939 then any `else` block is executed.
1942 ### Alternative expressions
1944 ~~~~~~~~{.ebnf .gram}
1945 alt_expr : "alt" expr '{' alt_arm [ '|' alt_arm ] * '}' ;
1947 alt_arm : alt_pat '{' block '}' ;
1949 alt_pat : pat [ "to" pat ] ? [ "if" expr ] ;
1953 An `alt` expression branches on a *pattern*. The exact form of matching that
1954 occurs depends on the pattern. Patterns consist of some combination of
1955 literals, destructured tag constructors, records and tuples, variable binding
1956 specifications and placeholders (`_`). An `alt` expression has a *head
1957 expression*, which is the value to compare to the patterns. The type of the
1958 patterns must equal the type of the head expression.
1960 To execute an `alt` expression, first the head expression is evaluated, then
1961 its value is sequentially compared to the patterns in the arms until a match
1962 is found. The first arm with a matching pattern is chosen as the branch target
1963 of the `alt`, any variables bound by the pattern are assigned to local
1964 variables in the arm's block, and control enters the block.
1966 An example of an `alt` expression:
1970 tag list<X> { nil; cons(X, @list<X>); }
1972 let x: list<int> = cons(10, @cons(11, @nil));
1975 cons(a, @cons(b, _)) {
1990 Records can also be pattern-matched and their fields bound to variables.
1991 When matching fields of a record, the fields being matched are specified
1992 first, then a placeholder (`_`) represents the remaining fields.
1998 stats: load_stats(),
2006 {options: {choose: true, _}, _} {
2009 {player: p, options: {size: "small", _}, _} {
2010 log(info, p + " is small");
2019 Multiple alternative patterns may be joined with the `|` operator. A
2020 range of values may be specified with `to`. For example:
2023 let message = alt x {
2024 0 | 1 { "not many" }
2030 Finally, alt patterns can accept *pattern guards* to further refine the
2031 criteria for matching a case. Pattern guards appear after the pattern and
2032 consist of a bool-typed expression following the `if` keyword. A pattern
2033 guard may refer to the variables bound within the pattern they follow.
2036 let message = alt maybe_digit {
2037 some(x) if x < 10 { process_digit(x) }
2038 some(x) { process_other(x) }
2043 ### Fail expressions
2045 ~~~~~~~~{.ebnf .gram}
2046 fail_expr : "fail" expr ? ;
2049 Evaluating a `fail` expression causes a task to enter the *failing* state. In
2050 the *failing* state, a task unwinds its stack, destroying all frames and
2051 freeing all resources until it reaches its entry frame, at which point it
2052 halts execution in the *dead* state.
2054 ### Note expressions
2056 ~~~~~~~~{.ebnf .gram}
2057 note_expr : "note" expr ;
2060 **Note: Note expressions are not yet supported by the compiler.**
2062 A `note` expression has no effect during normal execution. The purpose of a
2063 `note` expression is to provide additional diagnostic information to the
2064 logging subsystem during task failure. See [log
2065 expressions](#log-expressions). Using `note` expressions, normal diagnostic
2066 logging can be kept relatively sparse, while still providing verbose
2067 diagnostic "back-traces" when a task fails.
2069 When a task is failing, control frames *unwind* from the innermost frame to
2070 the outermost, and from the innermost lexical block within an unwinding frame
2071 to the outermost. When unwinding a lexical block, the runtime processes all
2072 the `note` expressions in the block sequentially, from the first expression of
2073 the block to the last. During processing, a `note` expression has equivalent
2074 meaning to a `log` expression: it causes the runtime to append the argument of
2075 the `note` to the internal logging diagnostic buffer.
2077 An example of a `note` expression:
2080 fn read_file_lines(path: str) -> [str] {
2083 let f: file = open_read(path);
2091 In this example, if the task fails while attempting to open or read a file,
2092 the runtime will log the path name that was being read. If the function
2093 completes normally, the runtime will not log the path.
2095 A value that is marked by a `note` expression is *not* copied aside
2096 when control passes through the `note`. In other words, if a `note`
2097 expression notes a particular `lval`, and code after the `note`
2098 mutates that slot, and then a subsequent failure occurs, the *mutated*
2099 value will be logged during unwinding, *not* the original value that was
2100 denoted by the `lval` at the moment control passed through the `note`
2103 ### Return expressions
2105 ~~~~~~~~{.ebnf .gram}
2106 ret_expr : "ret" expr ? ;
2109 Return expressions are denoted with the keyword `ret`. Evaluating a `ret`
2110 expression^[A `ret` expression is analogous to a `return` expression
2111 in the C family.] moves its argument into the output slot of the current
2112 function, destroys the current function activation frame, and transfers
2113 control to the caller frame.
2115 An example of a `ret` expression:
2118 fn max(a: int, b: int) -> int {
2128 ~~~~~~~~{.ebnf .gram}
2129 log_expr : "log" '(' level ',' expr ')' ;
2132 Evaluating a `log` expression may, depending on runtime configuration, cause a
2133 value to be appended to an internal diagnostic logging buffer provided by the
2134 runtime or emitted to a system console. Log expressions are enabled or
2135 disabled dynamically at run-time on a per-task and per-item basis. See
2136 [logging system](#logging-system).
2138 Each `log` expression must be provided with a *level* argument in
2139 addition to the value to log. The logging level is a `u32` value, where
2140 lower levels indicate more-urgent levels of logging. By default, the lowest
2141 four logging levels (`0_u32 ... 3_u32`) are predefined as the constants
2142 `error`, `warn`, `info` and `debug` in the `core` library.
2144 Additionally, the macros `#error`, `#warn`, `#info` and `#debug` are defined
2145 in the default syntax-extension namespace. These expand into calls to the
2146 logging facility composed with calls to the `#fmt` string formatting
2149 The following examples all produce the same output, logged at the `error`
2153 // Full version, logging a value.
2154 log(core::error, "file not found: " + filename);
2156 // Log-level abbreviated, since core::* is imported by default.
2157 log(error, "file not found: " + filename);
2159 // Formatting the message using a format-string and #fmt
2160 log(error, #fmt("file not found: %s", filename));
2162 // Using the #error macro, that expands to the previous call.
2163 #error("file not found: %s", filename);
2166 A `log` expression is *not evaluated* when logging at the specified
2167 logging-level, module or task is disabled at runtime. This makes inactive
2168 `log` expressions very cheap; they should be used extensively in Rust
2169 code, as diagnostic aids, as they add little overhead beyond a single
2170 integer-compare and branch at runtime.
2172 Logging is presently implemented as a language built-in feature, as it makes
2173 use of compiler-provided logic for allocating the associated per-module
2174 logging-control structures visible to the runtime, and lazily evaluating
2175 arguments. In the future, as more of the supporting compiler-provided logic is
2176 moved into libraries, logging is likely to move to a component of the core
2177 library. It is best to use the macro forms of logging (*#error*,
2178 *#debug*, etc.) to minimize disruption to code using the logging facility
2182 ### Check expressions
2184 ~~~~~~~~{.ebnf .gram}
2185 check_expr : "check" call_expr ;
2188 A `check` expression connects dynamic assertions made at run-time to the
2189 static [typestate system](#typestate-system). A `check` expression takes a
2190 constraint to check at run-time. If the constraint holds at run-time, control
2191 passes through the `check` and on to the next expression in the enclosing
2192 block. If the condition fails to hold at run-time, the `check` expression
2193 behaves as a `fail` expression.
2195 The typestate algorithm is built around `check` expressions, and in particular
2196 the fact that control *will not pass* a check expression with a condition that
2197 fails to hold. The typestate algorithm can therefore assume that the (static)
2198 postcondition of a `check` expression includes the checked constraint
2199 itself. From there, the typestate algorithm can perform dataflow calculations
2200 on subsequent expressions, propagating [conditions](#conditions) forward and
2201 statically comparing implied states and their specifications.
2204 pure fn even(x: int) -> bool {
2208 fn print_even(x: int) : even(x) {
2215 // Cannot call print_even(y) here.
2219 // Can call print_even(y) here, since even(y) now holds.
2224 ### Prove expressions
2226 **Note: Prove expressions are not yet supported by the compiler.**
2228 ~~~~~~~~{.ebnf .gram}
2229 prove_expr : "prove" call_expr ;
2232 A `prove` expression has no run-time effect. Its purpose is to statically
2233 check (and document) that its argument constraint holds at its expression
2234 entry point. If its argument typestate does not hold, under the typestate
2235 algorithm, the program containing it will fail to compile.
2237 ### Claim expressions
2239 ~~~~~~~~{.ebnf .gram}
2240 claim_expr : "claim" call_expr ;
2243 A `claim` expression is an unsafe variant on a `check` expression that is not
2244 actually checked at runtime. Thus, using a `claim` implies a proof obligation
2245 to ensure---without compiler assistance---that an assertion always holds.
2247 Setting a runtime flag can turn all `claim` expressions into `check`
2248 expressions in a compiled Rust program, but the default is to not check the
2249 assertion contained in a `claim`. The idea behind `claim` is that performance
2250 profiling might identify a few bottlenecks in the code where actually checking
2251 a given callee's predicate is too expensive; `claim` allows the code to
2252 typecheck without removing the predicate check at every other call site.
2256 ### If-Check expressions
2258 An `if check` expression combines a `if` expression and a `check`
2259 expression in an indivisible unit that can be used to build more complex
2260 conditional control-flow than the `check` expression affords.
2262 In fact, `if check` is a "more primitive" expression than `check`;
2263 instances of the latter can be rewritten as instances of the former. The
2264 following two examples are equivalent:
2266 Example using `check`:
2273 Equivalent example using `if check`:
2283 ### Assert expressions
2285 ~~~~~~~~{.ebnf .gram}
2286 assert_expr : "assert" expr ;
2289 An `assert` expression is similar to a `check` expression, except
2290 the condition may be any boolean-typed expression, and the compiler makes no
2291 use of the knowledge that the condition holds if the program continues to
2292 execute after the `assert`.
2295 ### Syntax extension expressions
2297 ~~~~~~~~ {.abnf .gram}
2298 syntax_ext_expr : '#' ident paren_expr_list ? brace_match ? ;
2301 Rust provides a notation for _syntax extension_. The notation for invoking
2302 a syntax extension is a marked syntactic form that can appear as an expression
2303 in the body of a Rust program.
2305 After parsing, a syntax-extension invocation is expanded into a Rust
2306 expression. The name of the extension determines the translation performed. In
2307 future versions of Rust, user-provided syntax extensions aside from macros
2308 will be provided via external crates.
2310 At present, only a set of built-in syntax extensions, as well as macros
2311 introduced inline in source code using the `macro` extension, may be used. The
2312 current built-in syntax extensions are:
2315 * `fmt` expands into code to produce a formatted string, similar to
2317 * `env` expands into a string literal containing the value of that
2318 environment variable at compile-time.
2319 * `concat_idents` expands into an identifier which is the
2320 concatenation of its arguments.
2321 * `ident_to_str` expands into a string literal containing the name of
2322 its argument (which must be a literal).
2323 * `log_syntax` causes the compiler to pretty-print its arguments.
2326 Finally, `macro` is used to define a new macro. A macro can abstract over
2327 second-class Rust concepts that are present in syntax. The arguments to
2328 `macro` are pairs (two-element vectors). The pairs consist of an invocation
2329 and the syntax to expand into. An example:
2332 #macro([#apply[fn, [args, ...]], fn(args, ...)]);
2335 In this case, the invocation `#apply[sum, 5, 8, 6]` expands to
2336 `sum(5,8,6)`. If `...` follows an expression (which need not be as
2337 simple as a single identifier) in the input syntax, the matcher will expect an
2338 arbitrary number of occurrences of the thing preceding it, and bind syntax to
2339 the identifiers it contains. If it follows an expression in the output syntax,
2340 it will transcribe that expression repeatedly, according to the identifiers
2341 (bound to syntax) that it contains.
2343 The behaviour of `...` is known as Macro By Example. It allows you to
2344 write a macro with arbitrary repetition by specifying only one case of that
2345 repetition, and following it by `...`, both where the repeated input is
2346 matched, and where the repeated output must be transcribed. A more
2347 sophisticated example:
2351 #macro([#zip_literals[[x, ...], [y, ...]), [[x, y], ...]]);
2352 #macro([#unzip_literals[[x, y], ...], [[x, ...], [y, ...]]]);
2355 In this case, `#zip_literals[[1,2,3], [1,2,3]]` expands to
2356 `[[1,1],[2,2],[3,3]]`, and `#unzip_literals[[1,1], [2,2], [3,3]]`
2357 expands to `[[1,2,3],[1,2,3]]`.
2359 Macro expansion takes place outside-in: that is,
2360 `#unzip_literals[#zip_literals[[1,2,3],[1,2,3]]]` will fail because
2361 `unzip_literals` expects a list, not a macro invocation, as an argument.
2363 The macro system currently has some limitations. It's not possible to
2364 destructure anything other than vector literals (therefore, the arguments to
2365 complicated macros will tend to be an ocean of square brackets). Macro
2366 invocations and `...` can only appear in expression positions. Finally,
2367 macro expansion is currently unhygienic. That is, name collisions between
2368 macro-generated and user-written code can cause unintentional capture.
2370 Future versions of Rust will address these issues.
2373 # Types and typestates
2377 Every slot and value in a Rust program has a type. The _type_ of a *value*
2378 defines the interpretation of the memory holding it. The type of a *slot* may
2379 also include [constraints](#constraints).
2381 Built-in types and type-constructors are tightly integrated into the language,
2382 in nontrivial ways that are not possible to emulate in user-defined
2383 types. User-defined types have limited capabilities. In addition, every
2384 built-in type or type-constructor name is reserved as a *keyword* in Rust;
2385 they cannot be used as user-defined identifiers in any context.
2389 The primitive types are the following:
2391 * The "nil" type `()`, having the single "nil" value `()`.^[The "nil" value
2392 `()` is *not* a sentinel "null pointer" value for reference slots; the "nil"
2393 type is the implicit return type from functions otherwise lacking a return
2394 type, and can be used in other contexts (such as message-sending or
2395 type-parametric code) as a zero-size type.]
2396 * The boolean type `bool` with values `true` and `false`.
2397 * The machine types.
2398 * The machine-dependent integer and floating-point types.
2402 The machine types are the following:
2405 * The unsigned word types `u8`, `u16`, `u32` and `u64`, with values drawn from
2406 the integer intervals $[0, 2^8 - 1]$, $[0, 2^16 - 1]$, $[0, 2^32 - 1]$ and
2407 $[0, 2^64 - 1]$ respectively.
2409 * The signed two's complement word types `i8`, `i16`, `i32` and `i64`, with
2410 values drawn from the integer intervals $[-(2^7), 2^7 - 1]$,
2411 $[-(2^15), 2^15 - 1]$, $[-(2^31), 2^31 - 1]$, $[-(2^63), 2^63 - 1]$
2414 * The IEEE 754-2008 `binary32` and `binary64` floating-point types: `f32` and
2415 `f64`, respectively.
2417 #### Machine-dependent integer types
2419 The Rust type `uint`^[A Rust `uint` is analogous to a C99 `uintptr_t`.] is an
2420 unsigned integer type with with target-machine-dependent size. Its size, in
2421 bits, is equal to the number of bits required to hold any memory address on
2424 The Rust type `int`^[A Rust `int` is analogous to a C99 `intptr_t`.] is a
2425 two's complement signed integer type with target-machine-dependent size. Its
2426 size, in bits, is equal to the size of the rust type `uint` on the same target
2430 #### Machine-dependent floating point type
2432 The Rust type `float` is a machine-specific type equal to one of the supported
2433 Rust floating-point machine types (`f32` or `f64`). It is the largest
2434 floating-point type that is directly supported by hardware on the target
2435 machine, or if the target machine has no floating-point hardware support, the
2436 largest floating-point type supported by the software floating-point library
2437 used to support the other floating-point machine types.
2439 Note that due to the preference for hardware-supported floating-point, the
2440 type `float` may not be equal to the largest *supported* floating-point type.
2445 The types `char` and `str` hold textual data.
2447 A value of type `char` is a Unicode character, represented as a 32-bit
2448 unsigned word holding a UCS-4 codepoint.
2450 A value of type `str` is a Unicode string, represented as a vector of 8-bit
2451 unsigned bytes holding a sequence of UTF-8 codepoints.
2456 The record type-constructor forms a new heterogeneous product of values.^[The
2457 record type-constructor is analogous to the `struct` type-constructor in the
2458 Algol/C family, the *record* types of the ML family, or the *structure* types
2459 of the Lisp family.] Fields of a record type are accessed by name and are
2460 arranged in memory in the order specified by the record type.
2462 An example of a record type and its use:
2465 type point = {x: int, y: int};
2466 let p: point = {x: 10, y: 11};
2472 The tuple type-constructor forms a new heterogeneous product of values similar
2473 to the record type-constructor. The differences are as follows:
2475 * tuple elements cannot be mutable, unlike record fields
2476 * tuple elements are not named and can be accessed only by pattern-matching
2478 Tuple types and values are denoted by listing the types or values of their
2479 elements, respectively, in a parenthesized, comma-separated
2480 list. Single-element tuples are not legal; all tuples have two or more values.
2482 The members of a tuple are laid out in memory contiguously, like a record, in
2483 order specified by the tuple type.
2485 An example of a tuple type and its use:
2488 type pair = (int,str);
2489 let p: pair = (10,"hello");
2491 assert (b == "world");
2496 The vector type-constructor represents a homogeneous array of values of a
2497 given type. A vector has a fixed size. The kind of a vector type depends on
2498 the kind of its member type, as with other simple structural types.
2500 An example of a vector type and its use:
2503 let v: [int] = [7, 5, 3];
2508 Vectors always *allocate* a storage region sufficient to store the first power
2509 of two worth of elements greater than or equal to the size of the vector. This
2510 behaviour supports idiomatic in-place "growth" of a mutable slot holding a
2515 let v: mutable [int] = [1, 2, 3];
2519 Normal vector concatenation causes the allocation of a fresh vector to hold
2520 the result; in this case, however, the slot holding the vector recycles the
2521 underlying storage in-place (since the reference-count of the underlying
2522 storage is equal to 1).
2524 All accessible elements of a vector are always initialized, and access to a
2525 vector is always bounds-checked.
2528 ### Enumerated types
2530 An *enumerated type* is a nominal, heterogeneous disjoint union type.^[The
2531 `enum` type is analogous to a `data` constructor declaration in ML or a *pick
2532 ADT* in Limbo.} An [`enum` *item*](#enumerations) consists of a number of
2533 *constructors*, each of which is independently named and takes an optional
2536 Enumerated types cannot be denoted *structurally* as types, but must be
2537 denoted by named reference to an [*enumeration* item](#enumerations).
2541 Box types are represented as pointers. There are three flavours of
2545 : These are reference-counted boxes. Their type is written
2546 `@content`, for example `@int` means a shared box containing an
2547 integer. Copying a value of such a type means copying the pointer
2548 and increasing the reference count.
2551 : Unique boxes have only a single owner, and are freed when their
2552 owner releases them. They are written `~content`. Copying a
2553 unique box involves copying the contents into a new box.
2555 Unsafe pointers (`*`)
2556 : Unsafe pointers are pointers without safety guarantees or
2557 language-enforced semantics. Their type is written `*content`.
2558 They can be copied and dropped freely. Dereferencing an unsafe
2559 pointer is part of the unsafe sub-dialect of Rust.
2563 The function type-constructor `fn` forms new function types. A function type
2564 consists of a sequence of input slots, an optional set of
2565 [input constraints](#constraints) and an output slot.
2567 An example of a `fn` type:
2570 fn add(x: int, y: int) -> int {
2574 let int x = add(5,7);
2576 type binop = fn(int,int) -> int;
2577 let bo: binop = add;
2583 Types in Rust are categorized into three kinds, based on whether they
2584 allow copying of their values, and sending to different tasks. The
2588 : Values with a sendable type can be safely sent to another task.
2589 This kind includes scalars, unique pointers, unique closures, and
2590 structural types containing only other sendable types.
2592 : This kind includes all types that can be copied. All types with
2593 sendable kind are copyable, as are shared boxes, shared closures,
2594 interface types, and structural types built out of these.
2596 : [Resource](#resources) types, and every type that includes a
2597 resource without storing it in a shared box, may not be copied.
2598 Types of sendable or copyable type can always be used in places
2599 where a noncopyable type is expected, so in effect this kind
2602 These form a hierarchy. The noncopyable kind is the widest, including
2603 all types in the language. The copyable kind is a subset of that, and
2604 the sendable kind is a subset of the copyable kind.
2606 Any operation that causes a value to be copied requires the type of
2607 that value to be of copyable kind. Type parameter types are assumed to
2608 be noncopyable, unless one of the special bounds `send` or `copy` is
2609 declared for it. For example, this is not a valid program:
2612 fn box<T>(x: T) -> @T { @x }
2615 Putting `x` into a shared box involves copying, and the `T` parameter
2616 is assumed to be noncopyable. To change that, a bound is declared:
2619 fn box<T: copy>(x: T) -> @T { @x }
2622 Calling this second version of `box` on a noncopyable type is not
2623 allowed. When instantiating a type parameter, the kind bounds on the
2624 parameter are checked to be the same or narrower than the kind of the
2625 type that it is instantiated with.
2627 Sending operations are not part of the Rust language, but are
2628 implemented in the library. Generic functions that send values bound
2629 the kind of these values to sendable.
2636 Rust programs have a static semantics that determine the types of values
2637 produced by each expression, as well as the *predicates* that hold over
2638 slots in the environment at each point in time during execution.
2640 The latter semantics -- the dataflow analysis of predicates holding over slots
2641 -- is called the *typestate* system.
2645 Control flows from statement to statement in a block, and through the
2646 evaluation of each expression, from one sub-expression to another. This
2647 sequential control flow is specified as a set of _points_, each of which
2648 has a set of points before and after it in the implied control flow.
2650 For example, this code:
2657 Consists of 2 statements, 3 expressions and 12 points:
2660 * the point before the first statement
2661 * the point before evaluating the static initializer `"hello, world"`
2662 * the point after evaluating the static initializer `"hello, world"`
2663 * the point after the first statement
2664 * the point before the second statement
2665 * the point before evaluating the function value `print`
2666 * the point after evaluating the function value `print`
2667 * the point before evaluating the arguments to `print`
2668 * the point before evaluating the symbol `s`
2669 * the point after evaluating the symbol `s`
2670 * the point after evaluating the arguments to `print`
2671 * the point after the second statement
2681 Consists of 1 statement, 7 expressions and 14 points:
2684 * the point before the statement
2685 * the point before evaluating the function value `print`
2686 * the point after evaluating the function value `print`
2687 * the point before evaluating the arguments to `print`
2688 * the point before evaluating the arguments to `+`
2689 * the point before evaluating the function value `x`
2690 * the point after evaluating the function value `x`
2691 * the point before evaluating the arguments to `x`
2692 * the point after evaluating the arguments to `x`
2693 * the point before evaluating the function value `y`
2694 * the point after evaluating the function value `y`
2695 * the point before evaluating the arguments to `y`
2696 * the point after evaluating the arguments to `y`
2697 * the point after evaluating the arguments to `+`
2698 * the point after evaluating the arguments to `print`
2701 The typestate system reasons over points, rather than statements or
2702 expressions. This may seem counter-intuitive, but points are the more
2703 primitive concept. Another way of thinking about a point is as a set of
2704 *instants in time* at which the state of a task is fixed. By contrast, a
2705 statement or expression represents a *duration in time*, during which the
2706 state of the task changes. The typestate system is concerned with constraining
2707 the possible states of a task's memory at *instants*; it is meaningless to
2708 speak of the state of a task's memory "at" a statement or expression, as each
2709 statement or expression is likely to change the contents of memory.
2712 ### Control flow graph
2714 Each *point* can be considered a vertex in a directed *graph*. Each
2715 kind of expression or statement implies a number of points *and edges* in
2716 this graph. The edges connect the points within each statement or expression,
2717 as well as between those points and those of nearby statements and expressions
2718 in the program. The edges between points represent *possible* indivisible
2719 control transfers that might occur during execution.
2721 This implicit graph is called the _control-flow graph_, or _CFG_.
2726 A [_predicate_](#predicate-functions) is a pure boolean function declared with
2727 the keywords `pure fn`.
2729 A _constraint_ is a predicate applied to specific slots.
2731 For example, consider the following code:
2734 pure fn is_less_than(int a, int b) -> bool {
2741 check is_less_than(x,y);
2745 This example defines the predicate `is_less_than`, and applies it to the slots
2746 `x` and `y`. The constraint being checked on the third line of the function is
2747 `is_less_than(x,y)`.
2749 Predicates can only apply to slots holding immutable values. The slots a
2750 predicate applies to can themselves be mutable, but the types of values held
2751 in those slots must be immutable.
2755 A _condition_ is a set of zero or more constraints.
2757 Each *point* has an associated *condition*:
2759 * The _precondition_ of a statement or expression is the condition required at
2760 in the point before it.
2761 * The _postcondition_ of a statement or expression is the condition enforced
2762 in the point after it.
2764 Any constraint present in the precondition and *absent* in the postcondition
2765 is considered to be *dropped* by the statement or expression.
2768 ### Calculated typestates
2770 The typestate checking system *calculates* an additional condition for each
2771 point called its _typestate_. For a given statement or expression, we call the
2772 two typestates associated with its two points the prestate and a poststate.
2774 * The _prestate_ of a statement or expression is the typestate of the
2776 * The _poststate_ of a statement or expression is the typestate of the
2779 A _typestate_ is a condition that has _been determined by the typestate
2780 algorithm_ to hold at a point. This is a subtle but important point to
2781 understand: preconditions and postconditions are *inputs* to the typestate
2782 algorithm; prestates and poststates are *outputs* from the typestate
2785 The typestate algorithm analyses the preconditions and postconditions of every
2786 statement and expression in a block, and computes a condition for each
2787 typestate. Specifically:
2790 * Initially, every typestate is empty.
2791 * Each statement or expression's poststate is given the union of the its
2792 prestate, precondition, and postcondition.
2793 * Each statement or expression's poststate has the difference between its
2794 precondition and postcondition removed.
2795 * Each statement or expression's prestate is given the intersection of the
2796 poststates of every predecessor point in the CFG.
2797 * The previous three steps are repeated until no typestates in the
2800 The typestate algorithm is a very conventional dataflow calculation, and can
2801 be performed using bit-set operations, with one bit per predicate and one
2802 bit-set per condition.
2804 After the typestates of a block are computed, the typestate algorithm checks
2805 that every constraint in the precondition of a statement is satisfied by its
2806 prestate. If any preconditions are not satisfied, the mismatch is considered a
2807 static (compile-time) error.
2810 ### Typestate checks
2812 The key mechanism that connects run-time semantics and compile-time analysis
2813 of typestates is the use of [`check` expressions](#check-expressions). A
2814 `check` expression guarantees that *if* control were to proceed past it, the
2815 predicate associated with the `check` would have succeeded, so the constraint
2816 being checked *statically* holds in subsequent points.^[A `check` expression
2817 is similar to an `assert` call in a C program, with the significant difference
2818 that the Rust compiler *tracks* the constraint that each `check` expression
2819 enforces. Naturally, `check` expressions cannot be omitted from a "production
2820 build" of a Rust program the same way `asserts` are frequently disabled in
2821 deployed C programs.}
2823 It is important to understand that the typestate system has *no insight* into
2824 the meaning of a particular predicate. Predicates and constraints are not
2825 evaluated in any way at compile time. Predicates are treated as specific (but
2826 unknown) functions applied to specific (also unknown) slots. All the typestate
2827 system does is track which of those predicates -- whatever they calculate --
2828 *must have been checked already* in order for program control to reach a
2829 particular point in the CFG. The fundamental building block, therefore, is the
2830 `check` statement, which tells the typestate system "if control passes this
2831 point, the checked predicate holds".
2833 From this building block, constraints can be propagated to function signatures
2834 and constrained types, and the responsibility to `check` a constraint
2835 pushed further and further away from the site at which the program requires it
2836 to hold in order to execute properly.
2840 # Memory and concurrency models
2842 Rust has a memory model centered around concurrently-executing _tasks_. Thus
2843 its memory model and its concurrency model are best discussed simultaneously,
2844 as parts of each only make sense when considered from the perspective of the
2847 When reading about the memory model, keep in mind that it is partitioned in
2848 order to support tasks; and when reading about tasks, keep in mind that their
2849 isolation and communication mechanisms are only possible due to the ownership
2850 and lifetime semantics of the memory model.
2854 A Rust [task](#tasks)'s memory consists of a static set of *items*, a set of
2855 tasks each with its own *stack*, and a *heap*. Immutable portions of the heap
2856 may be shared between tasks, mutable portions may not.
2858 Allocations in the stack consist of *slots*, and allocations in the heap
2862 ### Memory allocation and lifetime
2864 The _items_ of a program are those functions, modules and types
2865 that have their value calculated at compile-time and stored uniquely in the
2866 memory image of the rust process. Items are neither dynamically allocated nor
2869 A task's _stack_ consists of activation frames automatically allocated on
2870 entry to each function as the task executes. A stack allocation is reclaimed
2871 when control leaves the frame containing it.
2873 The _heap_ is a general term that describes two separate sets of boxes:
2874 shared boxes -- which may be subject to garbage collection -- and unique
2875 boxes. The lifetime of an allocation in the heap depends on the lifetime of
2876 the box values pointing to it. Since box values may themselves be passed in
2877 and out of frames, or stored in the heap, heap allocations may outlive the
2878 frame they are allocated within.
2881 ### Memory ownership
2883 A task owns all memory it can *safely* reach through local variables,
2884 shared or unique boxes, and/or references. Sharing memory between tasks can
2885 only be accomplished using *unsafe* constructs, such as raw pointer
2886 operations or calling C code.
2888 When a task sends a value satisfying the `send` interface over a channel, it
2889 loses ownership of the value sent and can no longer refer to it. This is
2890 statically guaranteed by the combined use of "move semantics" and the
2891 compiler-checked _meaning_ of the `send` interface: it is only instantiated
2892 for (transitively) unique kinds of data constructor and pointers, never shared
2895 When a stack frame is exited, its local allocations are all released, and its
2896 references to boxes (both shared and owned) are dropped.
2898 A shared box may (in the case of a recursive, mutable shared type) be cyclic;
2899 in this case the release of memory inside the shared structure may be deferred
2900 until task-local garbage collection can reclaim it. Code can ensure no such
2901 delayed deallocation occurs by restricting itself to unique boxes and similar
2902 unshared kinds of data.
2904 When a task finishes, its stack is necessarily empty and it therefore has no
2905 references to any boxes; the remainder of its heap is immediately freed.
2910 A task's stack contains slots.
2912 A _slot_ is a component of a stack frame. A slot is either a *local variable*
2915 A _local variable_ (or *stack-local* allocation) holds a value directly,
2916 allocated within the stack's memory. The value is a part of the stack frame.
2918 A _reference_ references a value outside the frame. It may refer to a
2919 value allocated in another frame *or* a boxed value in the heap. The
2920 reference-formation rules ensure that the referent will outlive the reference.
2922 Local variables are always implicitly mutable.
2924 Local variables are not initialized when allocated; the entire frame worth of
2925 local variables are allocated at once, on frame-entry, in an uninitialized
2926 state. Subsequent statements within a function may or may not initialize the
2927 local variables. Local variables can be used only after they have been
2928 initialized; this condition is guaranteed by the typestate system.
2930 References are created for function arguments. If the compiler can not prove
2931 that the referred-to value will outlive the reference, it will try to set
2932 aside a copy of that value to refer to. If this is not semantically safe (for
2933 example, if the referred-to value contains mutable fields), it will reject the
2934 program. If the compiler deems copying the value expensive, it will warn.
2936 A function can be declared to take an argument by mutable reference. This
2937 allows the function to write to the slot that the reference refers to.
2939 An example function that accepts an value by mutable reference:
2949 A _box_ is a reference to a heap allocation holding another value. There
2950 are two kinds of boxes: *shared boxes* and *unique boxes*.
2952 A _shared box_ type or value is constructed by the prefix *at* sigil `@`.
2954 A _unique box_ type or value is constructed by the prefix *tilde* sigil `~`.
2956 Multiple shared box values can point to the same heap allocation; copying a
2957 shared box value makes a shallow copy of the pointer (optionally incrementing
2958 a reference count, if the shared box is implemented through
2959 reference-counting).
2961 Unique box values exist in 1:1 correspondence with their heap allocation;
2962 copying a unique box value makes a deep copy of the heap allocation and
2963 produces a pointer to the new allocation.
2965 An example of constructing one shared box type and value, and one unique box
2973 Some operations implicitly dereference boxes. Examples of such @dfn{implicit
2974 dereference} operations are:
2976 * arithmetic operators (`x + y - z`)
2977 * field selection (`x.y.z`)
2980 An example of an implicit-dereference operation performed on box values:
2985 assert (x + y == 22);
2988 Other operations act on box values as single-word-sized address values. For
2989 these operations, to access the value held in the box requires an explicit
2990 dereference of the box value. Explicitly dereferencing a box is indicated with
2991 the unary *star* operator `*`. Examples of such @dfn{explicit
2992 dereference} operations are:
2994 * copying box values (`x = y`)
2995 * passing box values to functions (`f(x,y)`)
2998 An example of an explicit-dereference operation performed on box values:
3001 fn takes_boxed(b: @int) {
3004 fn takes_unboxed(b: int) {
3016 An executing Rust program consists of a tree of tasks. A Rust _task_
3017 consists of an entry function, a stack, a set of outgoing communication
3018 channels and incoming communication ports, and ownership of some portion of
3019 the heap of a single operating-system process.
3021 Multiple Rust tasks may coexist in a single operating-system process. The
3022 runtime scheduler maps tasks to a certain number of operating-system threads;
3023 by default a number of threads is used based on the number of concurrent
3024 physical CPUs detected at startup, but this can be changed dynamically at
3025 runtime. When the number of tasks exceeds the number of threads -- which is
3026 quite possible -- the tasks are multiplexed onto the threads ^[This is an M:N
3027 scheduler, which is known to give suboptimal results for CPU-bound concurrency
3028 problems. In such cases, running with the same number of threads as tasks can
3029 give better results. The M:N scheduling in Rust exists to support very large
3030 numbers of tasks in contexts where threads are too resource-intensive to use
3031 in a similar volume. The cost of threads varies substantially per operating
3032 system, and is sometimes quite low, so this flexibility is not always worth
3036 ### Communication between tasks
3038 With the exception of *unsafe* blocks, Rust tasks are isolated from
3039 interfering with one another's memory directly. Instead of manipulating shared
3040 storage, Rust tasks communicate with one another using a typed, asynchronous,
3041 simplex message-passing system.
3043 A _port_ is a communication endpoint that can *receive* messages. Ports
3044 receive messages from channels.
3046 A _channel_ is a communication endpoint that can *send* messages. Channels
3047 send messages to ports.
3049 Each port is implicitly boxed and mutable; as such a port has a unique
3050 per-task identity and cannot be replicated or transmitted. If a port value is
3051 copied, both copies refer to the *same* port. New ports can be
3052 constructed dynamically and stored in data structures.
3054 Each channel is bound to a port when the channel is constructed, so the
3055 destination port for a channel must exist before the channel itself. A channel
3056 cannot be rebound to a different port from the one it was constructed with.
3058 Channels are weak: a channel does not keep the port it is bound to
3059 alive. Ports are owned by their allocating task and cannot be sent over
3060 channels; if a task dies its ports die with it, and all channels bound to
3061 those ports no longer function. Messages sent to a channel connected to a dead
3062 port will be dropped.
3064 Channels are immutable types with meaning known to the runtime; channels can
3065 be sent over channels.
3067 Many channels can be bound to the same port, but each channel is bound to a
3068 single port. In other words, channels and ports exist in an N:1 relationship,
3069 N channels to 1 port. ^[It may help to remember nautical terminology
3070 when differentiating channels from ports. Many different waterways --
3071 channels -- may lead to the same port.]
3073 Each port and channel can carry only one type of message. The message type is
3074 encoded as a parameter of the channel or port type. The message type of a
3075 channel is equal to the message type of the port it is bound to. The types of
3076 messages must satisfy the `send` built-in interface.
3078 Messages are generally sent asynchronously, with optional
3079 rate-limiting on the transmit side. Each port contains a message
3080 queue and sending a message over a channel merely means inserting it
3081 into the associated port's queue; message receipt is the
3082 responsibility of the receiving task.
3084 Messages are sent on channels and received on ports using standard library
3090 The _lifecycle_ of a task consists of a finite set of states and events
3091 that cause transitions between the states. The lifecycle states of a task are:
3098 A task begins its lifecycle -- once it has been spawned -- in the *running*
3099 state. In this state it executes the statements of its entry function, and any
3100 functions called by the entry function.
3102 A task may transition from the *running* state to the *blocked* state any time
3103 it makes a blocking recieve call on a port, or attempts a rate-limited
3104 blocking send on a channel. When the communication expression can be completed
3105 -- when a message arrives at a sender, or a queue drains sufficiently to
3106 complete a rate-limited send -- then the blocked task will unblock and
3107 transition back to *running*.
3109 A task may transition to the *failing* state at any time, due being
3110 killed by some external event or internally, from the evaluation of a
3111 `fail` expression. Once *failing*, a task unwinds its stack and
3112 transitions to the *dead* state. Unwinding the stack of a task is done by
3113 the task itself, on its own control stack. If a value with a destructor is
3114 freed during unwinding, the code for the destructor is run, also on the task's
3115 control stack. Running the destructor code causes a temporary transition to a
3116 *running* state, and allows the destructor code to cause any subsequent
3117 state transitions. The original task of unwinding and failing thereby may
3118 suspend temporarily, and may involve (recursive) unwinding of the stack of a
3119 failed destructor. Nonetheless, the outermost unwinding activity will continue
3120 until the stack is unwound and the task transitions to the *dead*
3121 state. There is no way to "recover" from task failure. Once a task has
3122 temporarily suspended its unwinding in the *failing* state, failure
3123 occurring from within this destructor results in *hard* failure. The
3124 unwinding procedure of hard failure frees resources but does not execute
3125 destructors. The original (soft) failure is still resumed at the point where
3126 it was temporarily suspended.
3128 A task in the *dead* state cannot transition to other states; it exists
3129 only to have its termination status inspected by other tasks, and/or to await
3130 reclamation when the last reference to it drops.
3135 The currently scheduled task is given a finite *time slice* in which to
3136 execute, after which it is *descheduled* at a loop-edge or similar
3137 preemption point, and another task within is scheduled, pseudo-randomly.
3139 An executing task can yield control at any time, by making a library call to
3140 `core::task::yield`, which deschedules it immediately. Entering any other
3141 non-executing state (blocked, dead) similarly deschedules the task.
3146 A call to `core::task::spawn`, passing a 0-argument function as its single
3147 argument, causes the runtime to construct a new task executing the passed
3148 function. The passed function is referred to as the _entry function_ for
3149 the spawned task, and any captured environment is carries is moved from the
3150 spawning task to the spawned task before the spawned task begins execution.
3152 The result of a `spawn` call is a `core::task::task` value.
3154 An example of a `spawn` call:
3164 // let task run, do other things
3169 let result = recv(p);
3173 ### Sending values into channels
3175 Sending a value into a channel is done by a library call to `core::comm::send`,
3176 which takes a channel and a value to send, and moves the value into the
3177 channel's outgoing buffer.
3179 An example of a send:
3183 let c: chan<str> = ...;
3184 send(c, "hello, world");
3188 ### Receiving values from ports
3190 Receiving a value is done by a call to the `recv` method on a value of type
3191 `core::comm::port`. This call causes the receiving task to enter the *blocked
3192 reading* state until a value arrives in the port's receive queue, at which
3193 time the port deques a value to return, and un-blocks the receiving task.
3195 An example of a *receive*:
3199 let p: port<str> = ...;
3204 # Runtime services, linkage and debugging
3207 The Rust _runtime_ is a relatively compact collection of C and Rust code
3208 that provides fundamental services and datatypes to all Rust tasks at
3209 run-time. It is smaller and simpler than many modern language runtimes. It is
3210 tightly integrated into the language's execution model of memory, tasks,
3211 communication and logging.
3214 ### Memory allocation
3216 The runtime memory-management system is based on a _service-provider
3217 interface_, through which the runtime requests blocks of memory from its
3218 environment and releases them back to its environment when they are no longer
3219 in use. The default implementation of the service-provider interface consists
3220 of the C runtime functions `malloc` and `free`.
3222 The runtime memory-management system in turn supplies Rust tasks with
3223 facilities for allocating, extending and releasing stacks, as well as
3224 allocating and freeing boxed values.
3229 The runtime provides C and Rust code to assist with various built-in types,
3230 such as vectors, strings, and the low level communication system (ports,
3233 Support for other built-in types such as simple types, tuples, records, and
3234 tags is open-coded by the Rust compiler.
3238 ### Task scheduling and communication
3240 The runtime provides code to manage inter-task communication. This includes
3241 the system of task-lifecycle state transitions depending on the contents of
3242 queues, as well as code to copy values between queues and their recipients and
3243 to serialize values for transmission over operating-system inter-process
3244 communication facilities.
3249 The runtime contains a system for directing [logging
3250 expressions](#log-expressions) to a logging console and/or internal logging
3251 buffers. Logging expressions can be enabled per module.
3253 Logging output is enabled by setting the `RUST_LOG` environment variable.
3254 `RUST_LOG` accepts a logging specification that is a comma-separated list of
3255 paths. For each module containing log expressions, if `RUST_LOG` contains the
3256 path to that module or a parent of that module, then its logs will be output
3257 to the console. The path to an module consists of the crate name, any parent
3258 modules, then the module itself, all separated by double colons (`::`).
3260 As an example, to see all the logs generated by the compiler, you would set
3261 `RUST_LOG` to `rustc`, which is the crate name (as specified in its `link`
3262 [attribute](#attributes)). To narrow down the logs to just crate resolution,
3263 you would set it to `rustc::metadata::creader`.
3265 Note that when compiling either `.rs` or `.rc` files that don't specifiy a
3266 crate name the crate is given a default name that matches the source file,
3267 with the extension removed. In that case, to turn on logging for a program
3268 compiled from, e.g. `helloworld.rs`, `RUST_LOG` should be set to `helloworld`.
3270 As a convenience, the logging spec can also be set to a special psuedo-crate,
3271 `::help`. In this case, when the application starts, the runtime will
3272 simply output a list of loaded modules containing log expressions, then exit.
3274 The Rust runtime itself generates logging information. The runtime's logs are
3275 generated for a number of artificial modules in the `::rt` psuedo-crate,
3276 and can be enabled just like the logs for any standard module. The full list
3277 of runtime logging modules follows.
3279 * `::rt::mem` Memory management
3280 * `::rt::comm` Messaging and task communication
3281 * `::rt::task` Task management
3282 * `::rt::dom` Task scheduling
3283 * `::rt::trace` Unused
3284 * `::rt::cache` Type descriptor cache
3285 * `::rt::upcall` Compiler-generated runtime calls
3286 * `::rt::timer` The scheduler timer
3287 * `::rt::gc` Garbage collection
3288 * `::rt::stdlib` Functions used directly by the standard library
3289 * `::rt::kern` The runtime kernel
3290 * `::rt::backtrace` Unused
3291 * `::rt::callback` Unused
3294 # Appendix: Rationales and design tradeoffs
3298 # Appendix: Influences and further references
3303 > The essential problem that must be solved in making a fault-tolerant
3304 > software system is therefore that of fault-isolation. Different programmers
3305 > will write different modules, some modules will be correct, others will have
3306 > errors. We do not want the errors in one module to adversely affect the
3307 > behaviour of a module which does not have any errors.
3309 > — Joe Armstrong
3312 > In our approach, all data is private to some process, and processes can
3313 > only communicate through communications channels. *Security*, as used
3314 > in this paper, is the property which guarantees that processes in a system
3315 > cannot affect each other except by explicit communication.
3317 > When security is absent, nothing which can be proven about a single module
3318 > in isolation can be guaranteed to hold when that module is embedded in a
3321 > — Robert Strom and Shaula Yemini
3324 > Concurrent and applicative programming complement each other. The
3325 > ability to send messages on channels provides I/O without side effects,
3326 > while the avoidance of shared data helps keep concurrent processes from
3332 Rust is not a particularly original language. It may however appear unusual
3333 by contemporary standards, as its design elements are drawn from a number of
3334 "historical" languages that have, with a few exceptions, fallen out of
3335 favour. Five prominent lineages contribute the most, though their influences
3336 have come and gone during the course of Rust's development:
3338 * The NIL (1981) and Hermes (1990) family. These languages were developed by
3339 Robert Strom, Shaula Yemini, David Bacon and others in their group at IBM
3340 Watson Research Center (Yorktown Heights, NY, USA).
3342 * The Erlang (1987) language, developed by Joe Armstrong, Robert Virding, Claes
3343 Wikström, Mike Williams and others in their group at the Ericsson Computer
3344 Science Laboratory (Älvsjö, Stockholm, Sweden) .
3346 * The Sather (1990) language, developed by Stephen Omohundro, Chu-Cheow Lim,
3347 Heinz Schmidt and others in their group at The International Computer
3348 Science Institute of the University of California, Berkeley (Berkeley, CA,
3351 * The Newsqueak (1988), Alef (1995), and Limbo (1996) family. These
3352 languages were developed by Rob Pike, Phil Winterbottom, Sean Dorward and
3353 others in their group at Bell labs Computing Sciences Reserch Center
3354 (Murray Hill, NJ, USA).
3356 * The Napier (1985) and Napier88 (1988) family. These languages were
3357 developed by Malcolm Atkinson, Ron Morrison and others in their group at
3358 the University of St. Andrews (St. Andrews, Fife, UK).
3360 Additional specific influences can be seen from the following languages:
3362 * The stack-growth implementation of Go.
3363 * The structural algebraic types and compilation manager of SML.
3364 * The attribute and assembly systems of C#.
3365 * The deterministic destructor system of C++.
3366 * The typeclass system of Haskell.
3367 * The lexical identifier rule of Python.
3368 * The block syntax of Ruby.