1 # Japanese translations for Rust package
2 # Copyright (C) 2013 The Rust Project Developers
3 # This file is distributed under the same license as the Rust package.
4 # Automatically generated, 2013.
8 "Project-Id-Version: Rust 0.8-pre\n"
9 "POT-Creation-Date: 2013-08-12 02:06+0900\n"
10 "PO-Revision-Date: 2013-08-05 19:40+0900\n"
11 "Last-Translator: Automatically generated\n"
12 "Language-Team: none\n"
15 "Content-Type: text/plain; charset=UTF-8\n"
16 "Content-Transfer-Encoding: 8bit\n"
17 "Plural-Forms: nplurals=1; plural=0;\n"
21 msgid "% Rust Reference Manual"
25 #: doc/rust.md:4 doc/rustpkg.md:4 doc/tutorial.md:4
26 #: doc/tutorial-borrowed-ptr.md:4 doc/tutorial-ffi.md:4
27 #: doc/tutorial-macros.md:4 doc/tutorial-tasks.md:4
28 msgid "# Introduction"
34 "This document is the reference manual for the Rust programming language. It "
35 "provides three kinds of material:"
38 #. type: Bullet: ' - '
41 "Chapters that formally define the language grammar and, for each construct, "
42 "informally describe its semantics and give examples of its use."
45 #. type: Bullet: ' - '
48 "Chapters that informally describe the memory model, concurrency model, "
49 "runtime services, linkage model and debugging facilities."
52 #. type: Bullet: ' - '
55 "Appendix chapters providing rationale and references to languages that "
56 "influenced the design."
62 "This document does not serve as a tutorial introduction to the language. "
63 "Background familiarity with the language is assumed. A separate [tutorial] "
64 "document is available to help acquire such background familiarity."
70 "This document also does not serve as a reference to the [standard] or "
71 "[extra] libraries included in the language distribution. Those libraries are "
72 "documented separately by extracting documentation attributes from their "
79 "[tutorial]: tutorial.html [standard]: std/index.html [extra]: extra/index."
84 #: doc/rust.md:30 doc/rustpkg.md:8
91 "Rust is a work in progress. The language continues to evolve as the design "
92 "shifts and is fleshed out in working code. Certain parts work, certain parts "
93 "do not, certain parts will be removed or changed."
99 "This manual is a snapshot written in the present tense. All features "
100 "described exist in working code unless otherwise noted, but some are quite "
101 "primitive or remain to be further modified by planned work. Some may be "
102 "temporary. It is a *draft*, and we ask that you not take anything you read "
109 "If you have suggestions to make, please try to focus them on *reductions* to "
110 "the language: possible features that can be combined or omitted. We aim to "
111 "keep the size and complexity of the language under control."
117 "> **Note:** The grammar for Rust given in this document is rough and > very "
118 "incomplete; only a modest number of sections have accompanying grammar > "
119 "rules. Formalizing the grammar accepted by the Rust parser is ongoing work, "
120 "> but future versions of this document will contain a complete > grammar. "
121 "Moreover, we hope that this grammar will be extracted and verified > as "
122 "LL(1) by an automated grammar-analysis tool, and further tested against the "
123 "> Rust sources. Preliminary versions of this automation exist, but are not "
135 "Rust's grammar is defined over Unicode codepoints, each conventionally "
136 "denoted `U+XXXX`, for 4 or more hexadecimal digits `X`. _Most_ of Rust's "
137 "grammar is confined to the ASCII range of Unicode, and is described in this "
138 "document by a dialect of Extended Backus-Naur Form (EBNF), specifically a "
139 "dialect of EBNF supported by common automated LL(k) parsing tools such as "
140 "`llgen`, rather than the dialect given in ISO 14977. The dialect can be "
141 "defined self-referentially as follows:"
146 msgid "~~~~~~~~ {.ebnf .notation}"
153 "grammar : rule + ;\n"
154 "rule : nonterminal ':' productionrule ';' ;\n"
155 "productionrule : production [ '|' production ] * ;\n"
156 "production : term * ;\n"
157 "term : element repeats ;\n"
158 "element : LITERAL | IDENTIFIER | '[' productionrule ']' ;\n"
159 "repeats : [ '*' | '+' ] NUMBER ? | NUMBER ? | '?' ;\n"
163 #: doc/rust.md:74 doc/rust.md:416 doc/rust.md:486
172 #. type: Bullet: ' - '
174 msgid "Whitespace in the grammar is ignored."
177 #. type: Bullet: ' - '
179 msgid "Square brackets are used to group rules."
186 " - `LITERAL` is a single printable ASCII character, or an escaped hexadecimal\n"
187 " ASCII code of the form `\\xQQ`, in single quotes, denoting the corresponding\n"
188 " Unicode codepoint `U+00QQ`.\n"
189 " - `IDENTIFIER` is a nonempty string of ASCII letters and underscores.\n"
190 " - The `repeat` forms apply to the adjacent `element`, and are as follows:\n"
191 " - `?` means zero or one repetition\n"
192 " - `*` means zero or more repetitions\n"
193 " - `+` means one or more repetitions\n"
194 " - NUMBER trailing a repeat symbol gives a maximum repetition count\n"
195 " - NUMBER on its own gives an exact repetition count\n"
200 msgid "This EBNF dialect should hopefully be familiar to many readers."
205 msgid "## Unicode productions"
211 "A few productions in Rust's grammar permit Unicode codepoints outside the "
212 "ASCII range. We define these productions in terms of character properties "
213 "specified in the Unicode standard, rather than in terms of ASCII-range "
214 "codepoints. The section [Special Unicode Productions](#special-unicode-"
215 "productions) lists these productions."
220 msgid "## String table productions"
226 "Some rules in the grammar -- notably [unary operators](#unary-operator-"
227 "expressions), [binary operators](#binary-operator-expressions), and "
228 "[keywords](#keywords) -- are given in a simplified form: as a listing of a "
229 "table of unquoted, printable whitespace-separated strings. These cases form "
230 "a subset of the rules regarding the [token](#tokens) rule, and are assumed "
231 "to be the result of a lexical-analysis phase feeding the parser, driven by a "
232 "DFA, operating over the disjunction of all such string table entries."
238 "When such a string enclosed in double-quotes (`\"`) occurs inside the "
239 "grammar, it is an implicit reference to a single member of such a string "
240 "table production. See [tokens](#tokens) for more information."
245 msgid "# Lexical structure"
250 msgid "## Input format"
256 "Rust input is interpreted as a sequence of Unicode codepoints encoded in "
257 "UTF-8, normalized to Unicode normalization form NFKC. Most Rust grammar "
258 "rules are defined in terms of printable ASCII-range codepoints, but a small "
259 "number are defined in terms of Unicode properties or explicit codepoint "
260 "lists. ^[Substitute definitions for the special Unicode productions are "
261 "provided to the grammar verifier, restricted to ASCII range, when verifying "
262 "the grammar in this document.]"
267 msgid "## Special Unicode Productions"
273 "The following productions in the Rust grammar are defined in terms of "
274 "Unicode properties: `ident`, `non_null`, `non_star`, `non_eol`, "
275 "`non_slash_or_star`, `non_single_quote` and `non_double_quote`."
280 msgid "### Identifiers"
286 "The `ident` production is any nonempty Unicode string of the following form:"
289 #. type: Bullet: ' - '
291 msgid "The first character has property `XID_start`"
294 #. type: Bullet: ' - '
296 msgid "The remaining characters have property `XID_continue`"
301 msgid "that does _not_ occur in the set of [keywords](#keywords)."
307 "Note: `XID_start` and `XID_continue` as character properties cover the "
308 "character ranges used to form the more familiar C and Java language-family "
314 msgid "### Delimiter-restricted productions"
320 "Some productions are defined by exclusion of particular Unicode characters:"
323 #. type: Bullet: ' - '
325 msgid "`non_null` is any single Unicode character aside from `U+0000` (null)"
328 #. type: Bullet: ' - '
330 msgid "`non_eol` is `non_null` restricted to exclude `U+000A` (`'\\n'`)"
333 #. type: Bullet: ' - '
335 msgid "`non_star` is `non_null` restricted to exclude `U+002A` (`*`)"
338 #. type: Bullet: ' - '
341 "`non_slash_or_star` is `non_null` restricted to exclude `U+002F` (`/`) and `U"
345 #. type: Bullet: ' - '
347 msgid "`non_single_quote` is `non_null` restricted to exclude `U+0027` (`'`)"
350 #. type: Bullet: ' - '
352 msgid "`non_double_quote` is `non_null` restricted to exclude `U+0022` (`\"`)"
363 "~~~~~~~~ {.ebnf .gram} comment : block_comment | line_comment ; "
364 "block_comment : \"/*\" block_comment_body * '*' + '/' ; block_comment_body : "
365 "non_star * | '*' + non_slash_or_star ; line_comment : \"//\" non_eol * ; "
372 "Comments in Rust code follow the general C++ style of line and block-comment "
373 "forms, with no nesting of block-comment delimiters."
379 "Line comments beginning with _three_ slashes (`///`), and block comments "
380 "beginning with a repeated asterisk in the block-open sequence (`/**`), are "
381 "interpreted as a special syntax for `doc` [attributes](#attributes). That "
382 "is, they are equivalent to writing `#[doc \"...\"]` around the comment's "
388 msgid "Non-doc comments are interpreted as a form of whitespace."
393 msgid "## Whitespace"
399 "~~~~~~~~ {.ebnf .gram} whitespace_char : '\\x20' | '\\x09' | '\\x0a' | "
400 "'\\x0d' ; whitespace : [ whitespace_char | comment ] + ; ~~~~~~~~"
406 "The `whitespace_char` production is any nonempty Unicode string consisting "
407 "of any of the following Unicode characters: `U+0020` (space, `' '`), `U"
408 "+0009` (tab, `'\\t'`), `U+000A` (LF, `'\\n'`), `U+000D` (CR, `'\\r'`)."
414 "Rust is a \"free-form\" language, meaning that all forms of whitespace serve "
415 "only to separate _tokens_ in the grammar, and have no semantic significance."
421 "A Rust program has identical meaning if each whitespace element is replaced "
422 "with any other legal whitespace element, such as a single space character."
433 "~~~~~~~~ {.ebnf .gram} simple_token : keyword | unop | binop ; token : "
434 "simple_token | ident | literal | symbol | whitespace token ; ~~~~~~~~"
440 "Tokens are primitive productions in the grammar defined by regular (non-"
441 "recursive) languages. \"Simple\" tokens are given in [string table "
442 "production](#string-table-productions) form, and occur in the rest of the "
443 "grammar as double-quoted strings. Other tokens have exact rules given."
453 msgid "The keywords are the following strings:"
459 "~~~~~~~~ {.keyword} as break do else enum extern false fn for if impl let "
460 "loop match mod mut priv pub ref return self static struct super true trait "
461 "type unsafe use while ~~~~~~~~"
467 "Each of these keywords has special meaning in its grammar, and all of them "
468 "are excluded from the `ident` rule."
479 "A literal is an expression consisting of a single token, rather than a "
480 "sequence of tokens, that immediately and directly denotes the value it "
481 "evaluates to, rather than referring to it by name or some other evaluation "
482 "rule. A literal is a form of constant expression, so is evaluated "
483 "(primarily) at compile time."
489 "~~~~~~~~ {.ebnf .gram} literal : string_lit | char_lit | num_lit ; ~~~~~~~~"
494 msgid "#### Character and string literals"
500 "~~~~~~~~ {.ebnf .gram} char_lit : '\\x27' char_body '\\x27' ; string_lit : "
501 "'\"' string_body * '\"' ;"
508 "char_body : non_single_quote\n"
509 " | '\\x5c' [ '\\x27' | common_escape ] ;\n"
516 "string_body : non_double_quote\n"
517 " | '\\x5c' [ '\\x22' | common_escape ] ;\n"
524 "common_escape : '\\x5c'\n"
525 " | 'n' | 'r' | 't'\n"
526 " | 'x' hex_digit 2\n"
527 " | 'u' hex_digit 4\n"
528 " | 'U' hex_digit 8 ;\n"
535 "hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f'\n"
536 " | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'\n"
538 "dec_digit : '0' | nonzero_dec ;\n"
539 "nonzero_dec: '1' | '2' | '3' | '4'\n"
540 " | '5' | '6' | '7' | '8' | '9' ;\n"
547 "A _character literal_ is a single Unicode character enclosed within two `U"
548 "+0027` (single-quote) characters, with the exception of `U+0027` itself, "
549 "which must be _escaped_ by a preceding U+005C character (`\\`)."
555 "A _string literal_ is a sequence of any Unicode characters enclosed within "
556 "two `U+0022` (double-quote) characters, with the exception of `U+0022` "
557 "itself, which must be _escaped_ by a preceding `U+005C` character (`\\`)."
563 "Some additional _escapes_ are available in either character or string "
564 "literals. An escape starts with a `U+005C` (`\\`) and continues with one of "
565 "the following forms:"
568 #. type: Bullet: ' * '
571 "An _8-bit codepoint escape_ escape starts with `U+0078` (`x`) and is "
572 "followed by exactly two _hex digits_. It denotes the Unicode codepoint equal "
573 "to the provided hex value."
576 #. type: Bullet: ' * '
579 "A _16-bit codepoint escape_ starts with `U+0075` (`u`) and is followed by "
580 "exactly four _hex digits_. It denotes the Unicode codepoint equal to the "
581 "provided hex value."
584 #. type: Bullet: ' * '
587 "A _32-bit codepoint escape_ starts with `U+0055` (`U`) and is followed by "
588 "exactly eight _hex digits_. It denotes the Unicode codepoint equal to the "
589 "provided hex value."
592 #. type: Bullet: ' * '
595 "A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072` "
596 "(`r`), or `U+0074` (`t`), denoting the unicode values `U+000A` (LF), `U"
597 "+000D` (CR) or `U+0009` (HT) respectively."
600 #. type: Bullet: ' * '
603 "The _backslash escape_ is the character U+005C (`\\`) which must be escaped "
604 "in order to denote *itself*."
609 msgid "#### Number literals"
613 #: doc/rust.md:294 doc/rust.md:406 doc/rust.md:473
614 msgid "~~~~~~~~ {.ebnf .gram}"
621 "num_lit : nonzero_dec [ dec_digit | '_' ] * num_suffix ?\n"
622 " | '0' [ [ dec_digit | '_' ] + num_suffix ?\n"
623 " | 'b' [ '1' | '0' | '_' ] + int_suffix ?\n"
624 " | 'x' [ hex_digit | '_' ] + int_suffix ? ] ;\n"
629 msgid "num_suffix : int_suffix | float_suffix ;"
636 "int_suffix : 'u' int_suffix_size ?\n"
637 " | 'i' int_suffix_size ? ;\n"
638 "int_suffix_size : [ '8' | '1' '6' | '3' '2' | '6' '4' ] ;\n"
644 "float_suffix : [ exponent | '.' dec_lit exponent ? ] ? float_suffix_ty ? ; "
645 "float_suffix_ty : 'f' [ '3' '2' | '6' '4' ] ; exponent : ['E' | 'e'] ['-' | "
646 "'+' ] ? dec_lit ; dec_lit : [ dec_digit | '_' ] + ; ~~~~~~~~"
652 "A _number literal_ is either an _integer literal_ or a _floating-point "
653 "literal_. The grammar for recognizing the two kinds of literals is mixed, as "
654 "they are differentiated by suffixes."
659 msgid "##### Integer literals"
664 msgid "An _integer literal_ has one of three forms:"
667 #. type: Bullet: ' * '
670 "A _decimal literal_ starts with a *decimal digit* and continues with any "
671 "mixture of *decimal digits* and _underscores_."
674 #. type: Bullet: ' * '
677 "A _hex literal_ starts with the character sequence `U+0030` `U+0078` (`0x`) "
678 "and continues as any mixture hex digits and underscores."
681 #. type: Bullet: ' * '
684 "A _binary literal_ starts with the character sequence `U+0030` `U+0062` "
685 "(`0b`) and continues as any mixture binary digits and underscores."
691 "An integer literal may be followed (immediately, without any spaces) by an "
692 "_integer suffix_, which changes the type of the literal. There are two kinds "
693 "of integer literal suffix:"
696 #. type: Bullet: ' * '
699 "The `i` and `u` suffixes give the literal type `int` or `uint`, respectively."
702 #. type: Bullet: ' * '
705 "Each of the signed and unsigned machine types `u8`, `i8`, `u16`, `i16`, "
706 "`u32`, `i32`, `u64` and `i64` give the literal the corresponding machine "
713 "The type of an _unsuffixed_ integer literal is determined by type "
714 "inference. If a integer type can be _uniquely_ determined from the "
715 "surrounding program context, the unsuffixed integer literal has that type. "
716 "If the program context underconstrains the type, the unsuffixed integer "
717 "literal's type is `int`; if the program context overconstrains the type, it "
718 "is considered a static type error."
723 msgid "Examples of integer literals of various forms:"
731 "123; 0xff00; // type determined by program context\n"
732 " // defaults to int in absence of type\n"
740 "123u; // type uint\n"
741 "123_u; // type uint\n"
742 "0xff_u8; // type u8\n"
743 "0b1111_1111_1001_0000_i32; // type i32\n"
749 msgid "##### Floating-point literals"
754 msgid "A _floating-point literal_ has one of two forms:"
757 #. type: Bullet: '* '
760 "Two _decimal literals_ separated by a period character `U+002E` (`.`), with "
761 "an optional _exponent_ trailing after the second decimal literal."
764 #. type: Bullet: '* '
766 msgid "A single _decimal literal_ followed by an _exponent_."
772 "By default, a floating-point literal is of type `float`. A floating-point "
773 "literal may be followed (immediately, without any spaces) by a _floating-"
774 "point suffix_, which changes the type of the literal. There are three "
775 "floating-point suffixes: `f` (for the base `float` type), `f32`, and `f64` "
776 "(the 32-bit and 64-bit floating point types)."
781 msgid "Examples of floating-point literals of various forms:"
789 "123.0; // type float\n"
790 "0.1; // type float\n"
791 "3f; // type float\n"
792 "0.1f32; // type f32\n"
793 "12E+99_f64; // type f64\n"
799 msgid "##### Unit and boolean literals"
805 "The _unit value_, the only value of the type that has the same name, is "
806 "written as `()`. The two values of the boolean type are written `true` and "
819 "~~~~~~~~ {.ebnf .gram}\n"
820 "symbol : \"::\" \"->\"\n"
821 " | '#' | '[' | ']' | '(' | ')' | '{' | '}'\n"
829 "Symbols are a general class of printable [token](#tokens) that play "
830 "structural roles in a variety of grammar productions. They are catalogued "
831 "here for completeness as the set of remaining miscellaneous printable tokens "
832 "that do not otherwise appear as [unary operators](#unary-operator-"
833 "expressions), [binary operators](#binary-operator-expressions), or [keywords]"
846 "expr_path : ident [ \"::\" expr_path_tail ] + ;\n"
847 "expr_path_tail : '<' type_expr [ ',' type_expr ] + '>'\n"
855 "type_path : ident [ type_path_tail ] + ;\n"
856 "type_path_tail : '<' type_expr [ ',' type_expr ] + '>'\n"
857 " | \"::\" type_path ;\n"
863 "A _path_ is a sequence of one or more path components _logically_ separated "
864 "by a namespace qualifier (`::`). If a path consists of only one component, "
865 "it may refer to either an [item](#items) or a [slot](#memory-slots) in a "
866 "local control scope. If a path has multiple components, it refers to an item."
872 "Every item has a _canonical path_ within its crate, but the path naming an "
873 "item is only meaningful within a given crate. There is no global namespace "
874 "across crates; an item's canonical path merely identifies it within the "
880 msgid "Two examples of simple paths consisting of only identifier components:"
885 msgid "~~~~{.ignore} x; x::y::z; ~~~~"
891 "Path components are usually [identifiers](#identifiers), but the trailing "
892 "component of a path may be an angle-bracket-enclosed list of type arguments. "
893 "In [expression](#expressions) context, the type argument list is given after "
894 "a final (`::`) namespace qualifier in order to disambiguate it from a "
895 "relational expression involving the less-than symbol (`<`). In type "
896 "expression context, the final namespace qualifier is omitted."
901 msgid "Two examples of paths with type arguments:"
909 "# use std::hashmap::HashMap;\n"
911 "# fn id<T>(t: T) -> T { t }\n"
912 "type t = HashMap<int,~str>; // Type arguments used in a type expression\n"
913 "let x = id::<int>(10); // Type arguments used in a call expression\n"
920 msgid "# Syntax extensions"
926 "A number of minor features of Rust are not central enough to have their own "
927 "syntax, and yet are not implementable as functions. Instead, they are given "
928 "names, and invoked through a consistent syntax: `name!(...)`. Examples "
932 #. type: Bullet: '* '
934 msgid "`fmt!` : format data into a string"
937 #. type: Bullet: '* '
939 msgid "`env!` : look up an environment variable's value at compile time"
942 #. type: Bullet: '* '
944 msgid "`stringify!` : pretty-print the Rust expression given as an argument"
947 #. type: Bullet: '* '
949 msgid "`proto!` : define a protocol for inter-task communication"
952 #. type: Bullet: '* '
954 msgid "`include!` : include the Rust expression in the given file"
957 #. type: Bullet: '* '
959 msgid "`include_str!` : include the contents of the given file as a string"
962 #. type: Bullet: '* '
965 "`include_bin!` : include the contents of the given file as a binary blob"
968 #. type: Bullet: '* '
970 msgid "`error!`, `warn!`, `info!`, `debug!` : provide diagnostic information."
976 "All of the above extensions, with the exception of `proto!`, are expressions "
977 "with values. `proto!` is an item, defining a new name."
989 "expr_macro_rules : \"macro_rules\" '!' ident '(' macro_rule * ')'\n"
990 "macro_rule : '(' matcher * ')' \"=>\" '(' transcriber * ')' ';'\n"
991 "matcher : '(' matcher * ')' | '[' matcher * ']'\n"
992 " | '{' matcher * '}' | '$' ident ':' ident\n"
993 " | '$' '(' matcher * ')' sep_token? [ '*' | '+' ]\n"
994 " | non_special_token\n"
995 "transcriber : '(' transcriber * ')' | '[' transcriber * ']'\n"
996 " | '{' transcriber * '}' | '$' ident\n"
997 " | '$' '(' transcriber * ')' sep_token? [ '*' | '+' ]\n"
998 " | non_special_token\n"
1004 "User-defined syntax extensions are called \"macros\", and the `macro_rules` "
1005 "syntax extension defines them. Currently, user-defined macros can expand to "
1006 "expressions, statements, or items."
1012 "(A `sep_token` is any token other than `*` and `+`. A `non_special_token` "
1013 "is any token other than a delimiter or `$`.)"
1019 "The macro expander looks up macro invocations by name, and tries each macro "
1020 "rule in turn. It transcribes the first successful match. Matching and "
1021 "transcription are closely related to each other, and we will describe them "
1027 msgid "### Macro By Example"
1033 "The macro expander matches and transcribes every token that does not begin "
1034 "with a `$` literally, including delimiters. For parsing reasons, delimiters "
1035 "must be balanced, but they are otherwise not special."
1041 "In the matcher, `$` _name_ `:` _designator_ matches the nonterminal in the "
1042 "Rust syntax named by _designator_. Valid designators are `item`, `block`, "
1043 "`stmt`, `pat`, `expr`, `ty` (type), `ident`, `path`, `matchers` (lhs of the "
1044 "`=>` in macro rules), `tt` (rhs of the `=>` in macro rules). In the "
1045 "transcriber, the designator is already known, and so only the name of a "
1046 "matched nonterminal comes after the dollar sign."
1052 "In both the matcher and transcriber, the Kleene star-like operator indicates "
1053 "repetition. The Kleene star operator consists of `$` and parens, optionally "
1054 "followed by a separator token, followed by `*` or `+`. `*` means zero or "
1055 "more repetitions, `+` means at least one repetition. The parens are not "
1056 "matched or transcribed. On the matcher side, a name is bound to _all_ of "
1057 "the names it matches, in a structure that mimics the structure of the "
1058 "repetition encountered on a successful match. The job of the transcriber is "
1059 "to sort that structure out."
1065 "The rules for transcription of these repetitions are called \"Macro By "
1066 "Example\". Essentially, one \"layer\" of repetition is discharged at a "
1067 "time, and all of them must be discharged by the time a name is transcribed. "
1068 "Therefore, `( $( $i:ident ),* ) => ( $i )` is an invalid macro, but `( $( $i:"
1069 "ident ),* ) => ( $( $i:ident ),* )` is acceptable (if trivial)."
1075 "When Macro By Example encounters a repetition, it examines all of the `$` "
1076 "_name_ s that occur in its body. At the \"current layer\", they all must "
1077 "repeat the same number of times, so ` ( $( $i:ident ),* ; $( $j:ident ),* ) "
1078 "=> ( $( ($i,$j) ),* )` is valid if given the argument `(a,b,c ; d,e,f)`, but "
1079 "not `(a,b,c ; d,e)`. The repetition walks through the choices at that layer "
1080 "in lockstep, so the former input transcribes to `( (a,d), (b,e), (c,f) )`."
1085 msgid "Nested repetitions are allowed."
1090 msgid "### Parsing limitations"
1096 "The parser used by the macro system is reasonably powerful, but the parsing "
1097 "of Rust syntax is restricted in two ways:"
1104 "1. The parser will always parse as much as possible. If it attempts to match\n"
1105 "`$i:expr [ , ]` against `8 [ , ]`, it will attempt to parse `i` as an array\n"
1106 "index operation and fail. Adding a separator can solve this problem.\n"
1107 "2. The parser must have eliminated all ambiguity by the time it reaches a `$` _name_ `:` _designator_.\n"
1108 "This requirement most often affects name-designator pairs when they occur at the beginning of, or immediately after, a `$(...)*`; requiring a distinctive token in front can solve the problem.\n"
1113 msgid "## Syntax extensions useful for the macro author"
1116 #. type: Bullet: '* '
1118 msgid "`log_syntax!` : print out the arguments at compile time"
1121 #. type: Bullet: '* '
1124 "`trace_macros!` : supply `true` or `false` to enable or disable macro "
1128 #. type: Bullet: '* '
1130 msgid "`stringify!` : turn the identifier argument into a string literal"
1133 #. type: Bullet: '* '
1136 "`concat_idents!` : create a new identifier by concatenating the arguments"
1141 msgid "# Crates and source files"
1147 "Rust is a *compiled* language. Its semantics obey a *phase distinction* "
1148 "between compile-time and run-time. Those semantic rules that have a *static "
1149 "interpretation* govern the success or failure of compilation. We refer to "
1150 "these rules as \"static semantics\". Semantic rules called \"dynamic "
1151 "semantics\" govern the behavior of programs at run-time. A program that "
1152 "fails to compile due to violation of a compile-time rule has no defined "
1153 "dynamic semantics; the compiler should halt with an error report, and "
1154 "produce no executable artifact."
1160 "The compilation model centres on artifacts called _crates_. Each "
1161 "compilation processes a single crate in source form, and if successful, "
1162 "produces a single crate in binary form: either an executable or a library."
1163 "^[A crate is somewhat analogous to an *assembly* in the ECMA-335 CLI model, "
1164 "a *library* in the SML/NJ Compilation Manager, a *unit* in the Owens and "
1165 "Flatt module system, or a *configuration* in Mesa.]"
1171 "A _crate_ is a unit of compilation and linking, as well as versioning, "
1172 "distribution and runtime loading. A crate contains a _tree_ of nested "
1173 "[module](#modules) scopes. The top level of this tree is a module that is "
1174 "anonymous (from the point of view of paths within the module) and any item "
1175 "within a crate has a canonical [module path](#paths) denoting its location "
1176 "within the crate's module tree."
1182 "The Rust compiler is always invoked with a single source file as input, and "
1183 "always produces a single output crate. The processing of that source file "
1184 "may result in other source files being loaded as modules. Source files have "
1185 "the extension `.rs`."
1191 "A Rust source file describes a module, the name and location of which -- in "
1192 "the module tree of the current crate -- are defined from outside the source "
1193 "file: either by an explicit `mod_item` in a referencing source file, or by "
1194 "the name of the crate itself."
1200 "Each source file contains a sequence of zero or more `item` definitions, and "
1201 "may optionally begin with any number of `attributes` that apply to the "
1202 "containing module. Atributes on the anonymous crate module define important "
1203 "metadata that influences the behavior of the compiler."
1211 "// Linkage attributes\n"
1212 "#[ link(name = \"projx\",\n"
1213 " vers = \"2.5\",\n"
1214 " uuid = \"9cccc5d5-aceb-4af5-8285-811211826b82\") ];\n"
1220 "// Additional metadata attributes #[ desc = \"Project X\" ]; #[ license = "
1221 "\"BSD\" ]; #[ author = \"Jane Doe\" ];"
1226 msgid "// Specify the output type #[ crate_type = \"lib\" ];"
1231 msgid "// Turn on a warning #[ warn(non_camel_case_types) ]; ~~~~~~~~"
1237 "A crate that contains a `main` function can be compiled to an executable. "
1238 "If a `main` function is present, its return type must be [`unit`](#primitive-"
1239 "types) and it must take no arguments."
1244 msgid "# Items and attributes"
1250 "Crates contain [items](#items), each of which may have some number of "
1251 "[attributes](#attributes) attached to it."
1263 "~~~~~~~~ {.ebnf .gram}\n"
1264 "item : mod_item | fn_item | type_item | struct_item | enum_item\n"
1265 " | static_item | trait_item | impl_item | extern_block ;\n"
1272 "An _item_ is a component of a crate; some module items can be defined in "
1273 "crate files, but most are defined in source files. Items are organized "
1274 "within a crate by a nested set of [modules](#modules). Every crate has a "
1275 "single \"outermost\" anonymous module; all further items within the crate "
1276 "have [paths](#paths) within the module tree of the crate."
1282 "Items are entirely determined at compile-time, generally remain fixed during "
1283 "execution, and may reside in read-only memory."
1288 msgid "There are several kinds of item:"
1291 #. type: Bullet: ' * '
1293 msgid "[modules](#modules)"
1296 #. type: Bullet: ' * '
1298 msgid "[functions](#functions)"
1301 #. type: Bullet: ' * '
1303 msgid "[type definitions](#type-definitions)"
1306 #. type: Bullet: ' * '
1308 msgid "[structures](#structures)"
1311 #. type: Bullet: ' * '
1313 msgid "[enumerations](#enumerations)"
1316 #. type: Bullet: ' * '
1318 msgid "[static items](#static-items)"
1321 #. type: Bullet: ' * '
1323 msgid "[traits](#traits)"
1326 #. type: Bullet: ' * '
1328 msgid "[implementations](#implementations)"
1334 "Some items form an implicit scope for the declaration of sub-items. In other "
1335 "words, within a function or module, declarations of items can (in many "
1336 "cases) be mixed with the statements, control blocks, and similar artifacts "
1337 "that otherwise compose the item body. The meaning of these scoped items is "
1338 "the same as if the item was declared outside the scope -- it is still a "
1339 "static item -- except that the item's *path name* within the module "
1340 "namespace is qualified by the name of the enclosing item, or is private to "
1341 "the enclosing item (in the case of functions). The grammar specifies the "
1342 "exact locations in which sub-item declarations may appear."
1347 msgid "### Type Parameters"
1353 "All items except modules may be *parameterized* by type. Type parameters are "
1354 "given as a comma-separated list of identifiers enclosed in angle brackets "
1355 "(`<...>`), after the name of the item and before its definition. The type "
1356 "parameters of an item are considered \"part of the name\", not part of the "
1357 "type of the item. A referencing [path](#paths) must (in principle) provide "
1358 "type arguments as a list of comma-separated types enclosed within angle "
1359 "brackets, in order to refer to the type-parameterized item. In practice, "
1360 "the type-inference system can usually infer such argument types from "
1361 "context. There are no general type-parametric types, only type-parametric "
1362 "items. That is, Rust has no notion of type abstraction: there are no first-"
1363 "class \"forall\" types."
1374 "~~~~~~~~ {.ebnf .gram} mod_item : \"mod\" ident ( ';' | '{' mod '}' ); mod : "
1375 "[ view_item | item ] * ; ~~~~~~~~"
1381 "A module is a container for zero or more [view items](#view-items) and zero "
1382 "or more [items](#items). The view items manage the visibility of the items "
1383 "defined within the module, as well as the visibility of names from outside "
1384 "the module when referenced from inside the module."
1390 "A _module item_ is a module, surrounded in braces, named, and prefixed with "
1391 "the keyword `mod`. A module item introduces a new, named module into the "
1392 "tree of modules making up a crate. Modules can nest arbitrarily."
1397 msgid "An example of a module:"
1406 " type complex = (f64, f64);\n"
1407 " fn sin(f: f64) -> f64 {\n"
1411 " fn cos(f: f64) -> f64 {\n"
1415 " fn tan(f: f64) -> f64 {\n"
1426 "Modules and types share the same namespace. Declaring a named type that has "
1427 "the same name as a module in scope is forbidden: that is, a type definition, "
1428 "trait, struct, enumeration, or type parameter can't shadow the name of a "
1429 "module in scope, or vice versa."
1435 "A module without a body is loaded from an external file, by default with the "
1436 "same name as the module, plus the `.rs` extension. When a nested submodule "
1437 "is loaded from an external file, it is loaded from a subdirectory path that "
1438 "mirrors the module hierarchy."
1443 msgid "~~~ {.xfail-test} // Load the `vec` module from `vec.rs` mod vec;"
1451 " // Load the `local_data` module from `task/local_data.rs`\n"
1452 " mod local_data;\n"
1460 "The directories and files used for loading external file modules can be "
1461 "influenced with the `path` attribute."
1468 "~~~ {.xfail-test}\n"
1469 "#[path = \"task_files\"]\n"
1471 " // Load the `local_data` module from `task_files/tls.rs`\n"
1472 " #[path = \"tls.rs\"]\n"
1473 " mod local_data;\n"
1480 msgid "#### View items"
1486 "~~~~~~~~ {.ebnf .gram} view_item : extern_mod_decl | use_decl ; ~~~~~~~~"
1492 "A view item manages the namespace of a module. View items do not define new "
1493 "items, but rather, simply change other items' visibility. There are several "
1494 "kinds of view item:"
1497 #. type: Bullet: ' * '
1499 msgid "[`extern mod` declarations](#extern-mod-declarations)"
1502 #. type: Bullet: ' * '
1504 msgid "[`use` declarations](#use-declarations)"
1509 msgid "##### Extern mod declarations"
1515 "~~~~~~~~ {.ebnf .gram} extern_mod_decl : \"extern\" \"mod\" ident [ '(' "
1516 "link_attrs ')' ] ? [ '=' string_lit ] ? ; link_attrs : link_attr [ ',' "
1517 "link_attrs ] + ; link_attr : ident '=' literal ; ~~~~~~~~"
1523 "An _`extern mod` declaration_ specifies a dependency on an external crate. "
1524 "The external crate is then bound into the declaring scope as the `ident` "
1525 "provided in the `extern_mod_decl`."
1531 "The external crate is resolved to a specific `soname` at compile time, and a "
1532 "runtime linkage requirement to that `soname` is passed to the linker for "
1533 "loading at runtime. The `soname` is resolved at compile time by scanning "
1534 "the compiler's library path and matching the `link_attrs` provided in the "
1535 "`use_decl` against any `#link` attributes that were declared on the external "
1536 "crate when it was compiled. If no `link_attrs` are provided, a default "
1537 "`name` attribute is assumed, equal to the `ident` given in the `use_decl`."
1543 "Optionally, an identifier in an `extern mod` declaration may be followed by "
1544 "an equals sign, then a string literal denoting a relative path on the "
1545 "filesystem. This path should exist in one of the directories in the Rust "
1546 "path, which by default contains the `.rust` subdirectory of the current "
1547 "directory and each of its parents, as well as any directories in the colon-"
1548 "separated (or semicolon-separated on Windows) list of paths that is the "
1549 "`RUST_PATH` environment variable. The meaning of `extern mod a = \"b/c/d\";"
1550 "`, supposing that `/a` is in the RUST_PATH, is that the name `a` should be "
1551 "taken as a reference to the crate whose absolute location is `/a/b/c/d`."
1556 msgid "Four examples of `extern mod` declarations:"
1562 "~~~~~~~~{.xfail-test} extern mod pcre (uuid = \"54aba0f8-"
1563 "a7b1-4beb-92f1-4cf625264841\");"
1569 "extern mod extra; // equivalent to: extern mod extra ( name = \"extra\" );"
1575 "extern mod rustextra (name = \"extra\"); // linking to 'extra' under another "
1581 msgid "extern mod complicated_mod = \"some-file/in/the-rust/path\"; ~~~~~~~~"
1586 msgid "##### Use declarations"
1593 "~~~~~~~~ {.ebnf .gram}\n"
1594 "use_decl : \"pub\"? \"use\" ident [ '=' path\n"
1595 " | \"::\" path_glob ] ;\n"
1602 "path_glob : ident [ \"::\" path_glob ] ?\n"
1604 " | '{' ident [ ',' ident ] * '}'\n"
1611 "A _use declaration_ creates one or more local name bindings synonymous with "
1612 "some other [path](#paths). Usually a `use` declaration is used to shorten "
1613 "the path required to refer to a module item."
1620 "*Note*: Unlike in many languages,\n"
1621 "`use` declarations in Rust do *not* declare linkage dependency with external crates.\n"
1622 "Rather, [`extern mod` declarations](#extern-mod-declarations) declare linkage dependencies.\n"
1627 msgid "Use declarations support a number of convenient shortcuts:"
1630 #. type: Bullet: ' * '
1633 "Rebinding the target name as a new local name, using the syntax `use x = p::"
1637 #. type: Bullet: ' * '
1640 "Simultaneously binding a list of paths differing only in their final "
1641 "element, using the glob-like brace syntax `use a::b::{c,d,e,f};`"
1644 #. type: Bullet: ' * '
1647 "Binding all paths matching a given prefix, using the asterisk wildcard "
1648 "syntax `use a::b::*;`"
1653 msgid "An example of `use` declarations:"
1658 msgid "~~~~ use std::num::sin; use std::option::{Some, None};"
1666 " // Equivalent to 'info!(std::num::sin(1.0));'\n"
1667 " info!(sin(1.0));\n"
1674 " // Equivalent to 'info!(~[std::option::Some(1.0), std::option::None]);'\n"
1675 " info!(~[Some(1.0), None]);\n"
1683 "Like items, `use` declarations are private to the containing module, by "
1684 "default. Also like items, a `use` declaration can be public, if qualified "
1685 "by the `pub` keyword. Such a `use` declaration serves to _re-export_ a "
1686 "name. A public `use` declaration can therefore _redirect_ some public name "
1687 "to a different target definition: even a definition with a private canonical "
1688 "path, inside a different module. If a sequence of such redirections form a "
1689 "cycle or cannot be resolved unambiguously, they represent a compile-time "
1697 "An example of re-exporting:\n"
1701 " pub use quux::foo::*;\n"
1709 " pub fn bar() { }\n"
1710 " pub fn baz() { }\n"
1719 "In this example, the module `quux` re-exports all of the public names "
1726 "Also note that the paths contained in `use` items are relative to the crate "
1727 "root. So, in the previous example, the `use` refers to `quux::foo::*`, and "
1728 "not simply to `foo::*`."
1733 msgid "### Functions"
1739 "A _function item_ defines a sequence of [statements](#statements) and an "
1740 "optional final [expression](#expressions), along with a name and a set of "
1741 "parameters. Functions are declared with the keyword `fn`. Functions "
1742 "declare a set of *input* [*slots*](#memory-slots) as parameters, through "
1743 "which the caller passes arguments into the function, and an *output* [*slot*]"
1744 "(#memory-slots) through which the function passes results back to the caller."
1750 "A function may also be copied into a first class *value*, in which case the "
1751 "value has the corresponding [*function type*](#function-types), and can be "
1752 "used otherwise exactly as a function item (with a minor additional cost of "
1753 "calling the function indirectly)."
1759 "Every control path in a function logically ends with a `return` expression "
1760 "or a diverging expression. If the outermost block of a function has a value-"
1761 "producing expression in its final-expression position, that expression is "
1762 "interpreted as an implicit `return` expression applied to the final-"
1768 msgid "An example of a function:"
1776 "fn add(x: int, y: int) -> int {\n"
1785 "As with `let` bindings, function arguments are irrefutable patterns, so any "
1786 "pattern that is valid in a let binding is also valid as an argument."
1791 msgid "~~~ fn first((value, _): (int, int)) -> int { value } ~~~"
1796 msgid "#### Generic functions"
1802 "A _generic function_ allows one or more _parameterized types_ to appear in "
1803 "its signature. Each type parameter must be explicitly declared, in an angle-"
1804 "bracket-enclosed, comma-separated list following the function name."
1811 "~~~~ {.xfail-test}\n"
1812 "fn iter<T>(seq: &[T], f: &fn(T)) {\n"
1813 " for elt in seq.iter() { f(elt); }\n"
1815 "fn map<T, U>(seq: &[T], f: &fn(T) -> U) -> ~[U] {\n"
1816 " let mut acc = ~[];\n"
1817 " for elt in seq.iter() { acc.push(f(elt)); }\n"
1826 "Inside the function signature and body, the name of the type parameter can "
1827 "be used as a type name."
1833 "When a generic function is referenced, its type is instantiated based on the "
1834 "context of the reference. For example, calling the `iter` function defined "
1835 "above on `[1, 2]` will instantiate type parameter `T` with `int`, and "
1836 "require the closure parameter to have type `fn(int)`."
1842 "The type parameters can also be explicitly supplied in a trailing [path]"
1843 "(#paths) component after the function name. This might be necessary if there "
1844 "is not sufficient context to determine the type parameters. For example, "
1845 "`sys::size_of::<u32>() == 4`."
1851 "Since a parameter type is opaque to the generic function, the set of "
1852 "operations that can be performed on it is limited. Values of parameter type "
1853 "can only be moved, not copied."
1858 msgid "~~~~ fn id<T>(x: T) -> T { x } ~~~~"
1864 "Similarly, [trait](#traits) bounds can be specified for type parameters to "
1865 "allow methods with that trait to be called on values of that type."
1870 msgid "#### Unsafe functions"
1876 "Unsafe functions are those containing unsafe operations that are not "
1877 "contained in an [`unsafe` block](#unsafe-blocks). Such a function must be "
1878 "prefixed with the keyword `unsafe`."
1884 "Unsafe operations are those that potentially violate the memory-safety "
1885 "guarantees of Rust's static semantics. Specifically, the following "
1886 "operations are considered unsafe:"
1889 #. type: Bullet: ' - '
1891 msgid "Dereferencing a [raw pointer](#pointer-types)."
1894 #. type: Bullet: ' - '
1896 msgid "Casting a [raw pointer](#pointer-types) to a safe pointer type."
1899 #. type: Bullet: ' - '
1901 msgid "Calling an unsafe function."
1906 msgid "##### Unsafe blocks"
1912 "A block of code can also be prefixed with the `unsafe` keyword, to permit a "
1913 "sequence of unsafe operations in an otherwise-safe function. This facility "
1914 "exists because the static semantics of Rust are a necessary approximation of "
1915 "the dynamic semantics. When a programmer has sufficient conviction that a "
1916 "sequence of unsafe operations is actually safe, they can encapsulate that "
1917 "sequence (taken as a whole) within an `unsafe` block. The compiler will "
1918 "consider uses of such code \"safe\", to the surrounding context."
1923 msgid "#### Diverging functions"
1929 "A special kind of function can be declared with a `!` character where the "
1930 "output slot type would normally be. For example:"
1938 "fn my_err(s: &str) -> ! {\n"
1948 "We call such functions \"diverging\" because they never return a value to "
1949 "the caller. Every control path in a diverging function must end with a `fail!"
1950 "()` or a call to another diverging function on every control path. The `!` "
1951 "annotation does *not* denote a type. Rather, the result type of a diverging "
1952 "function is a special type called $\\bot$ (\"bottom\") that unifies with any "
1953 "type. Rust has no syntax for $\\bot$."
1959 "It might be necessary to declare a diverging function because as mentioned "
1960 "previously, the typechecker checks that every control path in a function "
1961 "ends with a [`return`](#return-expressions) or diverging expression. So, if "
1962 "`my_err` were declared without the `!` annotation, the following code would "
1968 msgid "~~~~ # fn my_err(s: &str) -> ! { fail!() }"
1975 "fn f(i: int) -> int {\n"
1980 " my_err(\"Bad number!\");\n"
1989 "This will not compile without the `!` annotation on `my_err`, since the "
1990 "`else` branch of the conditional in `f` does not return an `int`, as "
1991 "required by the signature of `f`. Adding the `!` annotation to `my_err` "
1992 "informs the typechecker that, should control ever enter `my_err`, no further "
1993 "type judgments about `f` need to hold, since control will never resume in "
1994 "any context that relies on those judgments. Thus the return type on `f` "
1995 "only needs to reflect the `if` branch of the conditional."
2000 msgid "#### Extern functions"
2006 "Extern functions are part of Rust's foreign function interface, providing "
2007 "the opposite functionality to [external blocks](#external-blocks). Whereas "
2008 "external blocks allow Rust code to call foreign code, extern functions with "
2009 "bodies defined in Rust code _can be called by foreign code_. They are "
2010 "defined in the same way as any other Rust function, except that they have "
2011 "the `extern` modifier."
2016 msgid "~~~ extern fn new_vec() -> ~[int] { ~[] } ~~~"
2022 "Extern functions may not be called from Rust code, but Rust code may take "
2023 "their value as a raw `u8` pointer."
2029 "~~~ # extern fn new_vec() -> ~[int] { ~[] } let fptr: *u8 = new_vec; ~~~"
2035 "The primary motivation for extern functions is to create callbacks for "
2036 "foreign functions that expect to receive function pointers."
2041 msgid "### Type definitions"
2047 "A _type definition_ defines a new name for an existing [type](#types). Type "
2048 "definitions are declared with the keyword `type`. Every value has a single, "
2049 "specific type; the type-specified aspects of a value include:"
2052 #. type: Bullet: '* '
2054 msgid "Whether the value is composed of sub-values or is indivisible."
2057 #. type: Bullet: '* '
2059 msgid "Whether the value represents textual or numerical information."
2062 #. type: Bullet: '* '
2064 msgid "Whether the value represents integral or floating-point information."
2067 #. type: Bullet: '* '
2069 msgid "The sequence of memory operations required to access the value."
2072 #. type: Bullet: '* '
2074 msgid "The [kind](#type-kinds) of the type."
2080 "For example, the type `(u8, u8)` defines the set of immutable values that "
2081 "are composite pairs, each containing two unsigned 8-bit integers accessed by "
2082 "pattern-matching and laid out in memory with the `x` component preceding the "
2088 msgid "### Structures"
2094 "A _structure_ is a nominal [structure type](#structure-types) defined with "
2095 "the keyword `struct`."
2100 msgid "An example of a `struct` item and its use:"
2106 "~~~~ struct Point {x: int, y: int} let p = Point {x: 10, y: 11}; let px: int "
2113 "A _tuple structure_ is a nominal [tuple type](#tuple-types), also defined "
2114 "with the keyword `struct`. For example:"
2120 "~~~~ struct Point(int, int); let p = Point(10, 11); let px: int = match p "
2121 "{ Point(x, _) => x }; ~~~~"
2127 "A _unit-like struct_ is a structure without any fields, defined by leaving "
2128 "off the list of fields entirely. Such types will have a single value, just "
2129 "like the [unit value `()`](#unit-and-boolean-literals) of the unit type. "
2135 msgid "~~~~ struct Cookie; let c = [Cookie, Cookie, Cookie, Cookie]; ~~~~"
2140 msgid "### Enumerations"
2146 "An _enumeration_ is a simultaneous definition of a nominal [enumerated type]"
2147 "(#enumerated-types) as well as a set of *constructors*, that can be used to "
2148 "create or pattern-match values of the corresponding enumerated type."
2153 msgid "Enumerations are declared with the keyword `enum`."
2158 msgid "An example of an `enum` item and its use:"
2174 msgid "let mut a: Animal = Dog; a = Cat; ~~~~"
2181 "Enumeration constructors can have either named or unnamed fields:\n"
2184 " Dog (~str, float),\n"
2185 " Cat { name: ~str, weight: float }\n"
2192 "let mut a: Animal = Dog(~\"Cocoa\", 37.2); a = Cat{ name: ~\"Spotty\", "
2193 "weight: 2.7 }; ~~~~"
2199 "In this example, `Cat` is a _struct-like enum variant_, whereas `Dog` is "
2200 "simply called an enum variant."
2205 msgid "### Static items"
2211 "~~~~~~~~ {.ebnf .gram} static_item : \"static\" ident ':' type '=' expr "
2218 "A *static item* is a named _constant value_ stored in the global data "
2219 "section of a crate. Immutable static items are stored in the read-only data "
2220 "section. The constant value bound to a static item is, like all constant "
2221 "values, evaluated at compile time. Static items have the `static` lifetime, "
2222 "which outlives all other lifetimes in a Rust program. Static items are "
2223 "declared with the `static` keyword. A static item must have a _constant "
2224 "expression_ giving its definition."
2230 "Static items must be explicitly typed. The type may be ```bool```, "
2231 "```char```, a number, or a type derived from those primitive types. The "
2232 "derived types are borrowed pointers with the `'static` lifetime, fixed-size "
2233 "arrays, tuples, and structs."
2238 msgid "~~~~ static BIT1: uint = 1 << 0; static BIT2: uint = 1 << 1;"
2244 "static BITS: [uint, ..2] = [BIT1, BIT2]; static STRING: &'static str = "
2252 "struct BitsNStrings<'self> {\n"
2253 " mybits: [uint, ..2],\n"
2254 " mystring: &'self str\n"
2262 "static bits_n_strings: BitsNStrings<'static> = BitsNStrings {\n"
2264 " mystring: STRING\n"
2271 msgid "#### Mutable statics"
2277 "If a static item is declared with the ```mut``` keyword, then it is allowed "
2278 "to be modified by the program. One of Rust's goals is to make concurrency "
2279 "bugs hard to run into, and this is obviously a very large source of race "
2280 "conditions or other bugs. For this reason, an ```unsafe``` block is required "
2281 "when either reading or writing a mutable static variable. Care should be "
2282 "taken to ensure that modifications to a mutable static are safe with respect "
2283 "to other tasks running in the same process."
2289 "Mutable statics are still very useful, however. They can be used with C "
2290 "libraries and can also be bound from C libraries (in an ```extern``` block)."
2295 msgid "~~~ # fn atomic_add(_: &mut uint, _: uint) -> uint { 2 }"
2300 msgid "static mut LEVELS: uint = 0;"
2307 "// This violates the idea of no shared state, and this doesn't internally\n"
2308 "// protect against races, so this function is `unsafe`\n"
2309 "unsafe fn bump_levels_unsafe1() -> uint {\n"
2310 " let ret = LEVELS;\n"
2320 "// Assuming that we have an atomic_add function which returns the old value,\n"
2321 "// this function is \"safe\" but the meaning of the return value may not be what\n"
2322 "// callers expect, so it's still marked as `unsafe`\n"
2323 "unsafe fn bump_levels_unsafe2() -> uint {\n"
2324 " return atomic_add(&mut LEVELS, 1);\n"
2340 msgid "A _trait_ describes a set of method types."
2346 "Traits can include default implementations of methods, written in terms of "
2347 "some unknown [`self` type](#self-types); the `self` type may either be "
2348 "completely unspecified, or constrained by some other trait."
2354 "Traits are implemented for specific types through separate [implementations]"
2355 "(#implementations)."
2360 msgid "~~~~ # type Surface = int; # type BoundingBox = int;"
2368 " fn draw(&self, Surface);\n"
2369 " fn bounding_box(&self) -> BoundingBox;\n"
2377 "This defines a trait with two methods. All values that have "
2378 "[implementations](#implementations) of this trait in scope can have their "
2379 "`draw` and `bounding_box` methods called, using `value.bounding_box()` "
2380 "[syntax](#method-call-expressions)."
2386 "Type parameters can be specified for a trait to make it generic. These "
2387 "appear after the trait name, using the same syntax used in [generic "
2388 "functions](#generic-functions)."
2397 " fn len(&self) -> uint;\n"
2398 " fn elt_at(&self, n: uint) -> T;\n"
2399 " fn iter(&self, &fn(T));\n"
2407 "Generic functions may use traits as _bounds_ on their type parameters. This "
2408 "will have two effects: only types that have the trait may instantiate the "
2409 "parameter, and within the generic function, the methods of the trait can be "
2410 "called on values that have the parameter's type. For example:"
2415 msgid "~~~~ # type Surface = int; # trait Shape { fn draw(&self, Surface); }"
2422 "fn draw_twice<T: Shape>(surface: Surface, sh: T) {\n"
2423 " sh.draw(surface);\n"
2424 " sh.draw(surface);\n"
2432 "Traits also define an [object type](#object-types) with the same name as the "
2433 "trait. Values of this type are created by [casting](#type-cast-expressions) "
2434 "pointer values (pointing to a type for which an implementation of the given "
2435 "trait is in scope) to pointers to the trait name, used as a type."
2440 msgid "~~~~ # trait Shape { } # impl Shape for int { } # let mycircle = 0;"
2445 msgid "let myshape: @Shape = @mycircle as @Shape; ~~~~"
2451 "The resulting value is a managed box containing the value that was cast, "
2452 "along with information that identifies the methods of the implementation "
2453 "that was used. Values with a trait type can have [methods called](#method-"
2454 "call-expressions) on them, for any method in the trait, and can be used to "
2455 "instantiate type parameters that are bounded by the trait."
2461 "Trait methods may be static, which means that they lack a `self` argument. "
2462 "This means that they can only be called with function call syntax (`f(x)`) "
2463 "and not method call syntax (`obj.f()`). The way to refer to the name of a "
2464 "static method is to qualify it with the trait name, treating the trait name "
2465 "like a module. For example:"
2474 " fn from_int(n: int) -> Self;\n"
2476 "impl Num for float {\n"
2477 " fn from_int(n: int) -> float { n as float }\n"
2479 "let x: float = Num::from_int(42);\n"
2485 msgid "Traits may inherit from other traits. For example, in"
2491 "~~~~ trait Shape { fn area() -> float; } trait Circle : Shape { fn radius() -"
2498 "the syntax `Circle : Shape` means that types that implement `Circle` must "
2499 "also have an implementation for `Shape`. Multiple supertraits are separated "
2500 "by spaces, `trait Circle : Shape Eq { }`. In an implementation of `Circle` "
2501 "for a given type `T`, methods can refer to `Shape` methods, since the "
2502 "typechecker checks that any type with an implementation of `Circle` also has "
2503 "an implementation of `Shape`."
2507 #: doc/rust.md:1277 doc/tutorial.md:2176
2509 "In type-parameterized functions, methods of the supertrait may be called on "
2510 "values of subtrait-bound type parameters. Refering to the previous example "
2511 "of `trait Circle : Shape`:"
2513 "型パラメータを持つ関数では、サブトレイトの境界型パラメータの値によりスーパー"
2514 "トレイトのメソッドを呼び出すことになります。前の例の `trait Circle : Shape` "
2518 #: doc/rust.md:1286 doc/tutorial.md:2185
2522 "# trait Shape { fn area(&self) -> float; }\n"
2523 "# trait Circle : Shape { fn radius(&self) -> float; }\n"
2524 "fn radius_times_area<T: Circle>(c: T) -> float {\n"
2525 " // `c` is both a Circle and a Shape\n"
2526 " c.radius() * c.area()\n"
2531 "# trait Shape { fn area(&self) -> float; }\n"
2532 "# trait Circle : Shape { fn radius(&self) -> float; }\n"
2533 "fn radius_times_area<T: Circle>(c: T) -> float {\n"
2534 " // `c` は Circle でもあり、Shape でもある\n"
2535 " c.radius() * c.area()\n"
2540 #: doc/rust.md:1288 doc/tutorial.md:2187
2541 msgid "Likewise, supertrait methods may also be called on trait objects."
2543 "同様に、スーパートレイトのメソッドは、トレイトオブジェクトについても呼び出す"
2549 "~~~ {.xfail-test} # trait Shape { fn area(&self) -> float; } # trait "
2550 "Circle : Shape { fn radius(&self) -> float; } # impl Shape for int { fn "
2551 "area(&self) -> float { 0.0 } } # impl Circle for int { fn radius(&self) -> "
2552 "float { 0.0 } } # let mycircle = 0;"
2558 "let mycircle: Circle = @mycircle as @Circle; let nonsense = mycircle."
2559 "radius() * mycircle.area(); ~~~"
2564 msgid "### Implementations"
2570 "An _implementation_ is an item that implements a [trait](#traits) for a "
2576 msgid "Implementations are defined with the keyword `impl`."
2582 "~~~~ # struct Point {x: float, y: float}; # type Surface = int; # struct "
2583 "BoundingBox {x: float, y: float, width: float, height: float}; # trait Shape "
2584 "{ fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; } # fn "
2585 "do_draw_circle(s: Surface, c: Circle) { }"
2602 "impl Shape for Circle {\n"
2603 " fn draw(&self, s: Surface) { do_draw_circle(s, *self); }\n"
2604 " fn bounding_box(&self) -> BoundingBox {\n"
2605 " let r = self.radius;\n"
2606 " BoundingBox{x: self.center.x - r, y: self.center.y - r,\n"
2607 " width: 2.0 * r, height: 2.0 * r}\n"
2616 "It is possible to define an implementation without referring to a trait. "
2617 "The methods in such an implementation can only be used as direct calls on "
2618 "the values of the type that the implementation targets. In such an "
2619 "implementation, the trait type and `for` after `impl` are omitted. Such "
2620 "implementations are limited to nominal types (enums, structs), and the "
2621 "implementation must appear in the same module or a sub-module as the `self` "
2628 "When a trait _is_ specified in an `impl`, all methods declared as part of "
2629 "the trait must be implemented, with matching types and type parameter counts."
2635 "An implementation can take type parameters, which can be different from the "
2636 "type parameters taken by the trait it implements. Implementation parameters "
2637 "are written after the `impl` keyword."
2642 msgid "~~~~ # trait Seq<T> { }"
2649 "impl<T> Seq<T> for ~[T] {\n"
2652 "impl Seq<bool> for u32 {\n"
2653 " /* Treat the integer as a sequence of bits */\n"
2660 msgid "### External blocks"
2666 "~~~ {.ebnf .gram} extern_block_item : \"extern\" '{' extern_block '} ; "
2667 "extern_block : [ foreign_fn ] * ; ~~~"
2673 "External blocks form the basis for Rust's foreign function interface. "
2674 "Declarations in an external block describe symbols in external, non-Rust "
2681 "Functions within external blocks are declared in the same way as other Rust "
2682 "functions, with the exception that they may not have a body and are instead "
2683 "terminated by a semicolon."
2688 msgid "~~~ # use std::libc::{c_char, FILE}; # #[nolink]"
2696 " fn fopen(filename: *c_char, mode: *c_char) -> *FILE;\n"
2704 "Functions within external blocks may be called by Rust code, just like "
2705 "functions defined in Rust. The Rust compiler automatically translates "
2706 "between the Rust ABI and the foreign ABI."
2712 "A number of [attributes](#attributes) control the behavior of external "
2719 "By default external blocks assume that the library they are calling uses the "
2720 "standard C \"cdecl\" ABI. Other ABIs may be specified using the `abi` "
2727 "~~~{.xfail-test} // Interface to the Windows API #[abi = \"stdcall\"] extern "
2734 "The `link_name` attribute allows the name of the library to be specified."
2739 msgid "~~~{.xfail-test} #[link_name = \"crypto\"] extern { } ~~~"
2745 "The `nolink` attribute tells the Rust compiler not to do any linking for the "
2746 "external block. This is particularly useful for creating external blocks "
2747 "for libc, which tends to not follow standard library naming conventions and "
2748 "is linked to all Rust programs anyway."
2753 msgid "## Attributes"
2760 "~~~~~~~~{.ebnf .gram}\n"
2761 "attribute : '#' '[' attr_list ']' ;\n"
2762 "attr_list : attr [ ',' attr_list ]*\n"
2763 "attr : ident [ '=' literal\n"
2764 " | '(' attr_list ')' ] ? ;\n"
2771 "Static entities in Rust -- crates, modules and items -- may have "
2772 "_attributes_ applied to them. ^[Attributes in Rust are modeled on Attributes "
2773 "in ECMA-335, C#] An attribute is a general, free-form metadatum that is "
2774 "interpreted according to name, convention, and language and compiler "
2775 "version. Attributes may appear as any of"
2778 #. type: Bullet: '* '
2780 msgid "A single identifier, the attribute name"
2783 #. type: Bullet: '* '
2786 "An identifier followed by the equals sign '=' and a literal, providing a key/"
2790 #. type: Bullet: '* '
2793 "An identifier followed by a parenthesized list of sub-attribute arguments"
2799 "Attributes terminated by a semi-colon apply to the entity that the attribute "
2800 "is declared within. Attributes that are not terminated by a semi-colon apply "
2801 "to the next entity."
2806 msgid "An example of attributes:"
2812 "~~~~~~~~{.xfail-test} // General metadata applied to the enclosing module or "
2813 "crate. #[license = \"BSD\"];"
2820 "// A function marked as a unit test\n"
2831 "// A conditionally-compiled module\n"
2832 "#[cfg(target_os=\"linux\")]\n"
2841 "// A lint attribute used to suppress a warning/error "
2842 "#[allow(non_camel_case_types)] pub type int8_t = i8; ~~~~~~~~"
2848 "> **Note:** In future versions of Rust, user-provided extensions to the "
2849 "compiler will be able to interpret attributes. > When this facility is "
2850 "provided, the compiler will distinguish between language-reserved and user-"
2851 "available attributes."
2857 "At present, only the Rust compiler interprets attributes, so all attribute "
2858 "names are effectively reserved. Some significant attributes include:"
2861 #. type: Bullet: '* '
2863 msgid "The `doc` attribute, for documenting code in-place."
2866 #. type: Bullet: '* '
2869 "The `cfg` attribute, for conditional-compilation by build-configuration."
2872 #. type: Bullet: '* '
2875 "The `lang` attribute, for custom definitions of traits and functions that "
2876 "are known to the Rust compiler (see [Language items](#language-items))."
2879 #. type: Bullet: '* '
2881 msgid "The `link` attribute, for describing linkage metadata for a crate."
2884 #. type: Bullet: '* '
2886 msgid "The `test` attribute, for marking functions as unit tests."
2889 #. type: Bullet: '* '
2892 "The `allow`, `warn`, `forbid`, and `deny` attributes, for controlling lint "
2893 "checks (see [Lint check attributes](#lint-check-attributes))."
2896 #. type: Bullet: '* '
2899 "The `deriving` attribute, for automatically generating implementations of "
2903 #. type: Bullet: '* '
2906 "The `static_assert` attribute, for asserting that a static bool is true at "
2913 "Other attributes may be added or removed during development of the language."
2918 msgid "### Lint check attributes"
2924 "A lint check names a potentially undesirable coding pattern, such as "
2925 "unreachable code or omitted documentation, for the static entity to which "
2926 "the attribute applies."
2931 msgid "For any lint check `C`:"
2934 #. type: Bullet: ' * '
2936 msgid "`warn(C)` warns about violations of `C` but continues compilation,"
2939 #. type: Bullet: ' * '
2941 msgid "`deny(C)` signals an error after encountering a violation of `C`,"
2948 " * `allow(C)` overrides the check for `C` so that violations will go\n"
2950 " * `forbid(C)` is the same as `deny(C)`, but also forbids uses of\n"
2951 " `allow(C)` within the entity.\n"
2957 "The lint checks supported by the compiler can be found via `rustc -W help`, "
2958 "along with their default settings."
2965 "~~~{.xfail-test}\n"
2967 " // Missing documentation is ignored here\n"
2968 " #[allow(missing_doc)]\n"
2969 " pub fn undocumented_one() -> int { 1 }\n"
2976 " // Missing documentation signals a warning here\n"
2977 " #[warn(missing_doc)]\n"
2978 " pub fn undocumented_too() -> int { 2 }\n"
2985 " // Missing documentation signals an error here\n"
2986 " #[deny(missing_doc)]\n"
2987 " pub fn undocumented_end() -> int { 3 }\n"
2995 "This example shows how one can use `allow` and `warn` to toggle a particular "
3003 "~~~{.xfail-test}\n"
3004 "#[warn(missing_doc)]\n"
3006 " #[allow(missing_doc)]\n"
3008 " // Missing documentation is ignored here\n"
3009 " pub fn undocumented_one() -> int { 1 }\n"
3016 " // Missing documentation signals a warning here,\n"
3017 " // despite the allow above.\n"
3018 " #[warn(missing_doc)]\n"
3019 " pub fn undocumented_two() -> int { 2 }\n"
3027 " // Missing documentation signals a warning here\n"
3028 " pub fn undocumented_too() -> int { 3 }\n"
3036 "This example shows how one can use `forbid` to disallow uses of `allow` for "
3044 "~~~{.xfail-test}\n"
3045 "#[forbid(missing_doc)]\n"
3047 " // Attempting to toggle warning signals an error here\n"
3048 " #[allow(missing_doc)]\n"
3050 " pub fn undocumented_too() -> int { 2 }\n"
3057 msgid "### Language items"
3063 "Some primitive Rust operations are defined in Rust code, rather than being "
3064 "implemented directly in C or assembly language. The definitions of these "
3065 "operations have to be easy for the compiler to find. The `lang` attribute "
3066 "makes it possible to declare these operations. For example, the `str` "
3067 "module in the Rust standard library defines the string equality function:"
3074 "~~~ {.xfail-test}\n"
3075 "#[lang=\"str_eq\"]\n"
3076 "pub fn eq_slice(a: &str, b: &str) -> bool {\n"
3077 " // details elided\n"
3085 "The name `str_eq` has a special meaning to the Rust compiler, and the "
3086 "presence of this definition means that it will use this definition when "
3087 "generating calls to the string equality function."
3092 msgid "A complete list of the built-in language items follows:"
3105 " : Cannot be mutated.\n"
3107 " : Are uniquely owned.\n"
3109 " : Contain borrowed pointers.\n"
3111 " : Have finalizers.\n"
3113 " : Elements can be added (for example, integers and floats).\n"
3115 " : Elements can be subtracted.\n"
3117 " : Elements can be multiplied.\n"
3119 " : Elements have a division operation.\n"
3121 " : Elements have a remainder operation.\n"
3123 " : Elements can be negated arithmetically.\n"
3125 " : Elements can be negated logically.\n"
3127 " : Elements have an exclusive-or operation.\n"
3129 " : Elements have a bitwise `and` operation.\n"
3131 " : Elements have a bitwise `or` operation.\n"
3133 " : Elements have a left shift operation.\n"
3135 " : Elements have a right shift operation.\n"
3137 " : Elements can be indexed.\n"
3139 " : Elements can be compared for equality.\n"
3141 " : Elements have a partial ordering.\n"
3146 msgid "#### Operations"
3154 " : Compare two strings for equality.\n"
3156 " : Compare two owned strings for equality.\n"
3158 " : Destroy a box before freeing it.\n"
3160 " : Generically print a string representation of any type.\n"
3162 " : Abort the program with an error.\n"
3163 "`fail_bounds_check`\n"
3164 " : Abort the program with a bounds check error.\n"
3165 "`exchange_malloc`\n"
3166 " : Allocate memory on the exchange heap.\n"
3168 " : Free memory that was allocated on the exchange heap.\n"
3170 " : Allocate memory on the managed heap.\n"
3172 " : Free memory that was allocated on the managed heap.\n"
3174 " : Create an immutable borrowed pointer to a mutable value.\n"
3176 " : Release a borrowed pointer created with `return_to_mut`\n"
3177 "`check_not_borrowed`\n"
3178 " : Fail if a value has existing borrowed pointers to it.\n"
3180 " : Return a new unique string\n"
3181 " containing a copy of the contents of a unique string.\n"
3187 "> **Note:** This list is likely to become out of date. We should auto-"
3188 "generate it > from `librustc/middle/lang_items.rs`."
3193 msgid "### Deriving"
3199 "The `deriving` attribute allows certain traits to be automatically "
3200 "implemented for data structures. For example, the following will create an "
3201 "`impl` for the `Eq` and `Clone` traits for `Foo`, the type parameter `T` "
3202 "will be given the `Eq` or `Clone` constraints for the appropriate `impl`:"
3210 "#[deriving(Eq, Clone)]\n"
3220 msgid "The generated `impl` for `Eq` is equivalent to"
3228 "# struct Foo<T> { a: int, b: T }\n"
3229 "impl<T: Eq> Eq for Foo<T> {\n"
3230 " fn eq(&self, other: &Foo<T>) -> bool {\n"
3231 " self.a == other.a && self.b == other.b\n"
3239 " fn ne(&self, other: &Foo<T>) -> bool {\n"
3240 " self.a != other.a || self.b != other.b\n"
3248 msgid "Supported traits for `deriving` are:"
3251 #. type: Bullet: '* '
3253 msgid "Comparison traits: `Eq`, `TotalEq`, `Ord`, `TotalOrd`."
3256 #. type: Bullet: '* '
3258 msgid "Serialization: `Encodable`, `Decodable`. These require `extra`."
3261 #. type: Bullet: '* '
3263 msgid "`Clone` and `DeepClone`, to perform (deep) copies."
3266 #. type: Bullet: '* '
3268 msgid "`IterBytes`, to iterate over the bytes in a data type."
3271 #. type: Bullet: '* '
3273 msgid "`Rand`, to create a random instance of a data type."
3276 #. type: Bullet: '* '
3278 msgid "`Zero`, to create an zero (or empty) instance of a data type."
3281 #. type: Bullet: '* '
3284 "`ToStr`, to convert to a string. For a type with this instance, `obj."
3285 "to_str()` has similar output as `fmt!(\"%?\", obj)`, but it differs in that "
3286 "each constituent field of the type must also implement `ToStr` and will have "
3287 "`field.to_str()` invoked to build up the result."
3292 msgid "# Statements and expressions"
3298 "Rust is _primarily_ an expression language. This means that most forms of "
3299 "value-producing or effect-causing evaluation are directed by the uniform "
3300 "syntax category of _expressions_. Each kind of expression can typically "
3301 "_nest_ within each other kind of expression, and rules for evaluation of "
3302 "expressions involve specifying both the value produced by the expression and "
3303 "the order in which its sub-expressions are themselves evaluated."
3309 "In contrast, statements in Rust serve _mostly_ to contain and explicitly "
3310 "sequence expression evaluation."
3315 msgid "## Statements"
3321 "A _statement_ is a component of a block, which is in turn a component of an "
3322 "outer [expression](#expressions) or [function](#functions)."
3328 "Rust has two kinds of statement: [declaration statements](#declaration-"
3329 "statements) and [expression statements](#expression-statements)."
3334 msgid "### Declaration statements"
3340 "A _declaration statement_ is one that introduces one or more *names* into "
3341 "the enclosing statement block. The declared names may denote new slots or "
3347 msgid "#### Item declarations"
3353 "An _item declaration statement_ has a syntactic form identical to an [item]"
3354 "(#items) declaration within a module. Declaring an item -- a function, "
3355 "enumeration, structure, type, static, trait, implementation or module -- "
3356 "locally within a statement block is simply a way of restricting its scope to "
3357 "a narrow region containing all of its uses; it is otherwise identical in "
3358 "meaning to declaring the item outside the statement block."
3364 "Note: there is no implicit capture of the function's dynamic environment "
3365 "when declaring a function-local item."
3370 msgid "#### Slot declarations"
3376 "~~~~~~~~{.ebnf .gram} let_decl : \"let\" pat [':' type ] ? [ init ] ? ';' ; "
3377 "init : [ '=' ] expr ; ~~~~~~~~"
3383 "A _slot declaration_ introduces a new set of slots, given by a pattern. The "
3384 "pattern may be followed by a type annotation, and/or an initializer "
3385 "expression. When no type annotation is given, the compiler will infer the "
3386 "type, or signal an error if insufficient type information is available for "
3387 "definite inference. Any slots introduced by a slot declaration are visible "
3388 "from the point of declaration until the end of the enclosing block scope."
3393 msgid "### Expression statements"
3399 "An _expression statement_ is one that evaluates an [expression]"
3400 "(#expressions) and ignores its result. The type of an expression statement "
3401 "`e;` is always `()`, regardless of the type of `e`. As a rule, an "
3402 "expression statement's purpose is to trigger the effects of evaluating its "
3408 msgid "## Expressions"
3415 "An expression may have two roles: it always produces a *value*, and it may have *effects*\n"
3416 "(otherwise known as \"side effects\").\n"
3417 "An expression *evaluates to* a value, and has effects during *evaluation*.\n"
3418 "Many expressions contain sub-expressions (operands).\n"
3419 "The meaning of each kind of expression dictates several things:\n"
3420 " * Whether or not to evaluate the sub-expressions when evaluating the expression\n"
3421 " * The order in which to evaluate the sub-expressions\n"
3422 " * How to combine the sub-expressions' values to obtain the value of the expression.\n"
3428 "In this way, the structure of expressions dictates the structure of "
3429 "execution. Blocks are just another kind of expression, so blocks, "
3430 "statements, expressions, and blocks again can recursively nest inside each "
3431 "other to an arbitrary depth."
3436 msgid "#### Lvalues, rvalues and temporaries"
3442 "Expressions are divided into two main categories: _lvalues_ and _rvalues_. "
3443 "Likewise within each expression, sub-expressions may occur in _lvalue "
3444 "context_ or _rvalue context_. The evaluation of an expression depends both "
3445 "on its own category and the context it occurs within."
3451 "[Path](#path-expressions), [field](#field-expressions) and [index](#index-"
3452 "expressions) expressions are lvalues. All other expressions are rvalues."
3458 "The left operand of an [assignment](#assignment-expressions), [binary move]"
3459 "(#binary-move-expressions) or [compound-assignment](#compound-assignment-"
3460 "expressions) expression is an lvalue context, as is the single operand of a "
3461 "unary [borrow](#unary-operator-expressions), or [move](#unary-move-"
3462 "expressions) expression, and _both_ operands of a [swap](#swap-expressions) "
3463 "expression. All other expression contexts are rvalue contexts."
3469 "When an lvalue is evaluated in an _lvalue context_, it denotes a memory "
3470 "location; when evaluated in an _rvalue context_, it denotes the value held "
3471 "_in_ that memory location."
3477 "When an rvalue is used in lvalue context, a temporary un-named lvalue is "
3478 "created and used instead. A temporary's lifetime equals the largest "
3479 "lifetime of any borrowed pointer that points to it."
3484 msgid "#### Moved and copied types"
3490 "When a [local variable](#memory-slots) is used as an [rvalue](#lvalues-"
3491 "rvalues-and-temporaries) the variable will either be [moved](#move-"
3492 "expressions) or copied, depending on its type. For types that contain "
3493 "[owning pointers](#owning-pointers) or values that implement the special "
3494 "trait `Drop`, the variable is moved. All other types are copied."
3499 msgid "### Literal expressions"
3505 "A _literal expression_ consists of one of the [literal](#literals) forms "
3506 "described earlier. It directly describes a number, character, string, "
3507 "boolean value, or the unit value."
3514 "~~~~~~~~ {.literals}\n"
3515 "(); // unit type\n"
3516 "\"hello\"; // string type\n"
3517 "'5'; // character type\n"
3518 "5; // integer type\n"
3524 msgid "### Path expressions"
3530 "A [path](#paths) used as an expression context denotes either a local "
3531 "variable or an item. Path expressions are [lvalues](#lvalues-rvalues-and-"
3537 msgid "### Tuple expressions"
3543 "Tuples are written by enclosing one or more comma-separated expressions in "
3544 "parentheses. They are used to create [tuple-typed](#tuple-types) values."
3549 msgid "~~~~~~~~ {.tuple} (0,); (0f, 4.5f); (\"a\", 4u, true); ~~~~~~~~"
3554 msgid "### Structure expressions"
3561 "~~~~~~~~{.ebnf .gram}\n"
3562 "struct_expr : expr_path '{' ident ':' expr\n"
3563 " [ ',' ident ':' expr ] *\n"
3564 " [ \"..\" expr ] '}' |\n"
3565 " expr_path '(' expr\n"
3566 " [ ',' expr ] * ')' |\n"
3574 "There are several forms of structure expressions. A _structure expression_ "
3575 "consists of the [path](#paths) of a [structure item](#structures), followed "
3576 "by a brace-enclosed list of one or more comma-separated name-value pairs, "
3577 "providing the field values of a new instance of the structure. A field name "
3578 "can be any identifier, and is separated from its value expression by a "
3579 "colon. The location denoted by a structure field is mutable if and only if "
3580 "the enclosing structure is mutable."
3586 "A _tuple structure expression_ consists of the [path](#paths) of a "
3587 "[structure item](#structures), followed by a parenthesized list of one or "
3588 "more comma-separated expressions (in other words, the path of a structure "
3589 "item followed by a tuple expression). The structure item must be a tuple "
3596 "A _unit-like structure expression_ consists only of the [path](#paths) of a "
3597 "[structure item](#structures)."
3602 msgid "The following are examples of structure expressions:"
3608 "~~~~ # struct Point { x: float, y: float } # struct TuplePoint(float, "
3609 "float); # mod game { pub struct User<'self> { name: &'self str, age: uint, "
3610 "score: uint } } # struct Cookie; fn some_fn<T>(t: T) {} Point {x: 10f, y: "
3611 "20f}; TuplePoint(10f, 20f); let u = game::User {name: \"Joe\", age: 35, "
3612 "score: 100_000}; some_fn::<Cookie>(Cookie); ~~~~"
3618 "A structure expression forms a new value of the named structure type. Note "
3619 "that for a given *unit-like* structure type, this will always be the same "
3626 "A structure expression can terminate with the syntax `..` followed by an "
3627 "expression to denote a functional update. The expression following `..` "
3628 "(the base) must have the same structure type as the new structure type being "
3629 "formed. The entire expression denotes the result of allocating a new "
3630 "structure (with the same type as the base expression) with the given values "
3631 "for the fields that were explicitly specified and the values in the base "
3632 "record for all other fields."
3638 "~~~~ # struct Point3d { x: int, y: int, z: int } let base = Point3d {x: 1, "
3639 "y: 2, z: 3}; Point3d {y: 0, z: 10, .. base}; ~~~~"
3644 msgid "### Record expressions"
3651 "~~~~~~~~{.ebnf .gram}\n"
3652 "rec_expr : '{' ident ':' expr\n"
3653 " [ ',' ident ':' expr ] *\n"
3654 " [ \"..\" expr ] '}'\n"
3660 msgid "### Method-call expressions"
3666 "~~~~~~~~{.ebnf .gram} method_call_expr : expr '.' ident paren_expr_list ; "
3673 "A _method call_ consists of an expression followed by a single dot, an "
3674 "identifier, and a parenthesized expression-list. Method calls are resolved "
3675 "to methods on specific traits, either statically dispatching to a method if "
3676 "the exact `self`-type of the left-hand-side is known, or dynamically "
3677 "dispatching if the left-hand-side expression is an indirect [object type]"
3683 msgid "### Field expressions"
3688 msgid "~~~~~~~~{.ebnf .gram} field_expr : expr '.' ident ~~~~~~~~"
3694 "A _field expression_ consists of an expression followed by a single dot and "
3695 "an identifier, when not immediately followed by a parenthesized expression-"
3696 "list (the latter is a [method call expression](#method-call-expressions)). "
3697 "A field expression denotes a field of a [structure](#structure-types)."
3702 msgid "~~~~~~~~ {.field} myrecord.myfield; {a: 10, b: 20}.a; ~~~~~~~~"
3708 "A field access on a record is an [lvalue](#lvalues-rvalues-and-temporaries) "
3709 "referring to the value of that field. When the field is mutable, it can be "
3710 "[assigned](#assignment-expressions) to."
3716 "When the type of the expression to the left of the dot is a pointer to a "
3717 "record or structure, it is automatically derferenced to make the field "
3723 msgid "### Vector expressions"
3728 msgid "~~~~~~~~{.ebnf .gram} vec_expr : '[' \"mut\"? vec_elems? ']'"
3733 msgid "vec_elems : [expr [',' expr]*] | [expr ',' \"..\" expr] ~~~~~~~~"
3739 "A [_vector_](#vector-types) _expression_ is written by enclosing zero or "
3740 "more comma-separated expressions of uniform type in square brackets."
3746 "In the `[expr ',' \"..\" expr]` form, the expression after the `\"..\"` must "
3747 "be a constant expression that can be evaluated at compile time, such as a "
3748 "[literal](#literals) or a [static item](#static-items)."
3757 "[\"a\", \"b\", \"c\", \"d\"];\n"
3758 "[0, ..128]; // vector with 128 zeros\n"
3759 "[0u8, 0u8, 0u8, 0u8];\n"
3765 msgid "### Index expressions"
3770 msgid "~~~~~~~~{.ebnf .gram} idx_expr : expr '[' expr ']' ~~~~~~~~"
3776 "[Vector](#vector-types)-typed expressions can be indexed by writing a square-"
3777 "bracket-enclosed expression (the index) after them. When the vector is "
3778 "mutable, the resulting [lvalue](#lvalues-rvalues-and-temporaries) can be "
3785 "Indices are zero-based, and may be of any integral type. Vector access is "
3786 "bounds-checked at run-time. When the check fails, it will put the task in a "
3792 msgid "~~~~ # use std::task; # do task::spawn_unlinked {"
3797 msgid "([1, 2, 3, 4])[0]; ([\"a\", \"b\"])[10]; // fails"
3801 #: doc/rust.md:1966 doc/tutorial-tasks.md:648
3807 msgid "### Unary operator expressions"
3813 "Rust defines six symbolic unary operators. They are all written as prefix "
3814 "operators, before the expression they apply to."
3822 " : Negation. May only be applied to numeric types.\n"
3824 " : Dereference. When applied to a [pointer](#pointer-types) it denotes the pointed-to location.\n"
3825 " For pointers to mutable locations, the resulting [lvalue](#lvalues-rvalues-and-temporaries) can be assigned to.\n"
3826 " For [enums](#enumerated-types) that have only a single variant, containing a single parameter,\n"
3827 " the dereference operator accesses this parameter.\n"
3829 " : Logical negation. On the boolean type, this flips between `true` and\n"
3830 " `false`. On integer types, this inverts the individual bits in the\n"
3831 " two's complement representation of the value.\n"
3833 " : [Boxing](#pointer-types) operators. Allocate a box to hold the value they are applied to,\n"
3834 " and store the value in it. `@` creates a managed box, whereas `~` creates an owned box.\n"
3836 " : Borrow operator. Returns a borrowed pointer, pointing to its operand.\n"
3837 " The operand of a borrowed pointer is statically proven to outlive the resulting pointer.\n"
3838 " If the borrow-checker cannot prove this, it is a compilation error.\n"
3843 msgid "### Binary operator expressions"
3848 msgid "~~~~~~~~{.ebnf .gram} binop_expr : expr binop expr ; ~~~~~~~~"
3854 "Binary operators expressions are given in terms of [operator precedence]"
3855 "(#operator-precedence)."
3860 msgid "#### Arithmetic operators"
3866 "Binary arithmetic expressions are syntactic sugar for calls to built-in "
3867 "traits, defined in the `std::ops` module of the `std` library. This means "
3868 "that arithmetic operators can be overridden for user-defined types. The "
3869 "default meaning of the operators on standard types is given here."
3877 " : Addition and vector/string concatenation.\n"
3878 " Calls the `add` method on the `std::ops::Add` trait.\n"
3881 " Calls the `sub` method on the `std::ops::Sub` trait.\n"
3883 " : Multiplication.\n"
3884 " Calls the `mul` method on the `std::ops::Mul` trait.\n"
3887 " Calls the `div` method on the `std::ops::Div` trait.\n"
3890 " Calls the `rem` method on the `std::ops::Rem` trait.\n"
3895 msgid "#### Bitwise operators"
3901 "Like the [arithmetic operators](#arithmetic-operators), bitwise operators "
3902 "are syntactic sugar for calls to methods of built-in traits. This means "
3903 "that bitwise operators can be overridden for user-defined types. The "
3904 "default meaning of the operators on standard types is given here."
3913 " Calls the `bitand` method of the `std::ops::BitAnd` trait.\n"
3915 " : Inclusive or.\n"
3916 " Calls the `bitor` method of the `std::ops::BitOr` trait.\n"
3918 " : Exclusive or.\n"
3919 " Calls the `bitxor` method of the `std::ops::BitXor` trait.\n"
3921 " : Logical left shift.\n"
3922 " Calls the `shl` method of the `std::ops::Shl` trait.\n"
3924 " : Logical right shift.\n"
3925 " Calls the `shr` method of the `std::ops::Shr` trait.\n"
3930 msgid "#### Lazy boolean operators"
3936 "The operators `||` and `&&` may be applied to operands of boolean type. The "
3937 "`||` operator denotes logical 'or', and the `&&` operator denotes logical "
3938 "'and'. They differ from `|` and `&` in that the right-hand operand is only "
3939 "evaluated when the left-hand operand does not already determine the result "
3940 "of the expression. That is, `||` only evaluates its right-hand operand when "
3941 "the left-hand operand evaluates to `false`, and `&&` only when it evaluates "
3947 msgid "#### Comparison operators"
3953 "Comparison operators are, like the [arithmetic operators](#arithmetic-"
3954 "operators), and [bitwise operators](#bitwise-operators), syntactic sugar for "
3955 "calls to built-in traits. This means that comparison operators can be "
3956 "overridden for user-defined types. The default meaning of the operators on "
3957 "standard types is given here."
3966 " Calls the `eq` method on the `std::cmp::Eq` trait.\n"
3969 " Calls the `ne` method on the `std::cmp::Eq` trait.\n"
3972 " Calls the `lt` method on the `std::cmp::Ord` trait.\n"
3974 " : Greater than.\n"
3975 " Calls the `gt` method on the `std::cmp::Ord` trait.\n"
3977 " : Less than or equal.\n"
3978 " Calls the `le` method on the `std::cmp::Ord` trait.\n"
3980 " : Greater than or equal.\n"
3981 " Calls the `ge` method on the `std::cmp::Ord` trait.\n"
3986 msgid "#### Type cast expressions"
3991 msgid "A type cast expression is denoted with the binary operator `as`."
3997 "Executing an `as` expression casts the value on the left-hand side to the "
3998 "type on the right-hand side."
4004 "A numeric value can be cast to any numeric type. A raw pointer value can be "
4005 "cast to or from any integral type or raw pointer type. Any other cast is "
4006 "unsupported and will fail to compile."
4011 msgid "An example of an `as` expression:"
4017 "~~~~ # fn sum(v: &[float]) -> float { 0.0 } # fn len(v: &[float]) -> int "
4025 "fn avg(v: &[float]) -> float {\n"
4026 " let sum: float = sum(v);\n"
4027 " let sz: float = len(v) as float;\n"
4028 " return sum / sz;\n"
4035 msgid "#### Assignment expressions"
4041 "An _assignment expression_ consists of an [lvalue](#lvalues-rvalues-and-"
4042 "temporaries) expression followed by an equals sign (`=`) and an [rvalue]"
4043 "(#lvalues-rvalues-and-temporaries) expression."
4049 "Evaluating an assignment expression [either copies or moves](#moved-and-"
4050 "copied-types) its right-hand operand to its left-hand operand."
4055 msgid "~~~~ # let mut x = 0; # let y = 0;"
4065 msgid "#### Compound assignment expressions"
4071 "The `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, and `>>` operators may be "
4072 "composed with the `=` operator. The expression `lval OP= val` is equivalent "
4073 "to `lval = lval OP val`. For example, `x = x + 1` may be written as `x += 1`."
4078 msgid "Any such expression always has the [`unit`](#primitive-types) type."
4083 msgid "#### Operator precedence"
4089 "The precedence of Rust binary operators is ordered as follows, going from "
4097 "~~~~ {.precedence}\n"
4113 #: doc/rust.md:2150 doc/rust.md:2237 doc/tutorial-macros.md:323
4120 "Operators at the same precedence level are evaluated left-to-right. [Unary "
4121 "operators](#unary-operator-expressions) have the same precedence level and "
4122 "it is stronger than any of the binary operators'."
4127 msgid "### Grouped expressions"
4133 "An expression enclosed in parentheses evaluates to the result of the "
4134 "enclosed expression. Parentheses can be used to explicitly specify "
4135 "evaluation order within an expression."
4140 msgid "~~~~~~~~{.ebnf .gram} paren_expr : '(' expr ')' ; ~~~~~~~~"
4145 msgid "An example of a parenthesized expression:"
4150 msgid "~~~~ let x = (2 + 3) * 4; ~~~~"
4155 msgid "### Call expressions"
4161 "~~~~~~~~ {.abnf .gram} expr_list : [ expr [ ',' expr ]* ] ? ; "
4162 "paren_expr_list : '(' expr_list ')' ; call_expr : expr paren_expr_list ; "
4169 "A _call expression_ invokes a function, providing zero or more input slots "
4170 "and an optional reference slot to serve as the function's output, bound to "
4171 "the `lval` on the right hand side of the call. If the function eventually "
4172 "returns, then the expression completes."
4177 msgid "Some examples of call expressions:"
4183 "~~~~ # use std::from_str::FromStr; # fn add(x: int, y: int) -> int { 0 }"
4189 "let x: int = add(1, 2); let pi = FromStr::from_str::<f32>(\"3.14\"); ~~~~"
4194 msgid "### Lambda expressions"
4200 "~~~~~~~~ {.abnf .gram} ident_list : [ ident [ ',' ident ]* ] ? ; "
4201 "lambda_expr : '|' ident_list '|' expr ; ~~~~~~~~"
4207 "A _lambda expression_ (sometimes called an \"anonymous function expression"
4208 "\") defines a function and denotes it as a value, in a single expression. A "
4209 "lambda expression is a pipe-symbol-delimited (`|`) list of identifiers "
4210 "followed by an expression."
4216 "A lambda expression denotes a function that maps a list of parameters "
4217 "(`ident_list`) onto the expression that follows the `ident_list`. The "
4218 "identifiers in the `ident_list` are the parameters to the function. These "
4219 "parameters' types need not be specified, as the compiler infers them from "
4226 "Lambda expressions are most useful when passing functions as arguments to "
4227 "other functions, as an abbreviation for defining and capturing a separate "
4234 "Significantly, lambda expressions _capture their environment_, which regular "
4235 "[function definitions](#functions) do not. The exact type of capture "
4236 "depends on the [function type](#function-types) inferred for the lambda "
4237 "expression. In the simplest and least-expensive form (analogous to a "
4238 "```&fn() { }``` expression), the lambda expression captures its environment "
4239 "by reference, effectively borrowing pointers to all outer variables "
4240 "mentioned inside the function. Alternately, the compiler may infer that a "
4241 "lambda expression should copy or move values (depending on their type.) "
4242 "from the environment into the lambda expression's captured environment."
4248 "In this example, we define a function `ten_times` that takes a higher-order "
4249 "function argument, and call it with a lambda expression as an argument."
4257 "fn ten_times(f: &fn(int)) {\n"
4268 msgid "ten_times(|j| println(fmt!(\"hello, %d\", j)));"
4273 msgid "### While loops"
4279 "~~~~~~~~{.ebnf .gram} while_expr : \"while\" expr '{' block '}' ; ~~~~~~~~"
4285 "A `while` loop begins by evaluating the boolean loop conditional "
4286 "expression. If the loop conditional expression evaluates to `true`, the "
4287 "loop body block executes and control returns to the loop conditional "
4288 "expression. If the loop conditional expression evaluates to `false`, the "
4289 "`while` expression completes."
4299 msgid "~~~~ let mut i = 0;"
4307 " println(\"hello\\n\");\n"
4315 msgid "### Infinite loops"
4321 "The keyword `loop` in Rust appears both in _loop expressions_ and in "
4322 "_continue expressions_. A loop expression denotes an infinite loop; see "
4323 "[Continue expressions](#continue-expressions) for continue expressions."
4329 "~~~~~~~~{.ebnf .gram} loop_expr : [ lifetime ':' ] \"loop\" '{' block '}'; "
4336 "A `loop` expression may optionally have a _label_. If a label is present, "
4337 "then labeled `break` and `loop` expressions nested within this loop may exit "
4338 "out of this loop or return control to its head. See [Break expressions]"
4339 "(#break-expressions)."
4344 msgid "### Break expressions"
4349 msgid "~~~~~~~~{.ebnf .gram} break_expr : \"break\" [ lifetime ]; ~~~~~~~~"
4355 "A `break` expression has an optional `label`. If the label is absent, then "
4356 "executing a `break` expression immediately terminates the innermost loop "
4357 "enclosing it. It is only permitted in the body of a loop. If the label is "
4358 "present, then `break foo` terminates the loop with label `foo`, which need "
4359 "not be the innermost label enclosing the `break` expression, but must "
4365 msgid "### Continue expressions"
4370 msgid "~~~~~~~~{.ebnf .gram} continue_expr : \"loop\" [ lifetime ]; ~~~~~~~~"
4376 "A continue expression, written `loop`, also has an optional `label`. If the "
4377 "label is absent, then executing a `loop` expression immediately terminates "
4378 "the current iteration of the innermost loop enclosing it, returning control "
4379 "to the loop *head*. In the case of a `while` loop, the head is the "
4380 "conditional expression controlling the loop. In the case of a `for` loop, "
4381 "the head is the call-expression controlling the loop. If the label is "
4382 "present, then `loop foo` returns control to the head of the loop with label "
4383 "`foo`, which need not be the innermost label enclosing the `break` "
4384 "expression, but must enclose it."
4389 msgid "A `loop` expression is only permitted in the body of a loop."
4394 msgid "### Do expressions"
4400 "~~~~~~~~{.ebnf .gram} do_expr : \"do\" expr [ '|' ident_list '|' ] ? '{' "
4401 "block '}' ; ~~~~~~~~"
4407 "A _do expression_ provides a more-familiar block-syntax for a [lambda "
4408 "expression](#lambda-expressions), including a special translation of [return "
4409 "expressions](#return-expressions) inside the supplied block."
4415 "Any occurrence of a [return expression](#return-expressions) inside this "
4416 "`block` expression is rewritten as a reference to an (anonymous) flag set in "
4417 "the caller's environment, which is checked on return from the `expr` and, if "
4418 "set, causes a corresponding return from the caller. In this way, the "
4419 "meaning of `return` statements in language built-in control blocks is "
4420 "preserved, if they are rewritten using lambda functions and `do` expressions "
4427 "The optional `ident_list` and `block` provided in a `do` expression are "
4428 "parsed as though they constitute a lambda expression; if the `ident_list` is "
4429 "missing, an empty `ident_list` is implied."
4435 "The lambda expression is then provided as a _trailing argument_ to the "
4436 "outermost [call](#call-expressions) or [method call](#method-call-"
4437 "expressions) expression in the `expr` following `do`. If the `expr` is a "
4438 "[path expression](#path-expressions), it is parsed as though it is a call "
4439 "expression. If the `expr` is a [field expression](#field-expressions), it "
4440 "is parsed as though it is a method call expression."
4445 msgid "In this example, both calls to `f` are equivalent:"
4450 msgid "~~~~ # fn f(f: &fn(int)) { } # fn g(i: int) { }"
4455 msgid "f(|j| g(j));"
4471 "In this example, both calls to the (binary) function `k` are equivalent:"
4476 msgid "~~~~ # fn k(x:int, f: &fn(int)) { } # fn l(i: int) { }"
4481 msgid "k(3, |j| l(j));"
4496 msgid "### For expressions"
4502 "~~~~~~~~{.ebnf .gram} for_expr : \"for\" expr [ '|' ident_list '|' ] ? '{' "
4503 "block '}' ; ~~~~~~~~"
4509 "A _for expression_ is similar to a [`do` expression](#do-expressions), in "
4510 "that it provides a special block-form of lambda expression, suited to "
4511 "passing the `block` function to a higher-order function implementing a loop."
4517 "In contrast to a `do` expression, a `for` expression is designed to work "
4518 "with methods such as `each` and `times`, that require the body block to "
4519 "return a boolean. The `for` expression accommodates this by implicitly "
4520 "returning `true` at the end of each block, unless a `break` expression is "
4527 "In addition, [`break`](#break-expressions) and [`loop`](#loop-expressions) "
4528 "expressions are rewritten inside `for` expressions in the same way that "
4529 "`return` expressions are, with a combination of local flag variables, and "
4530 "early boolean-valued returns from the `block` function, such that the "
4531 "meaning of `break` and `loop` is preserved in a primitive loop when "
4532 "rewritten as a `for` loop controlled by a higher order function."
4537 msgid "An example of a for loop over the contents of a vector:"
4543 "~~~~ # type foo = int; # fn bar(f: foo) { } # let a = 0; # let b = 0; # let "
4549 msgid "let v: &[foo] = &[a, b, c];"
4556 "for e in v.iter() {\n"
4564 msgid "An example of a for loop over a series of integers:"
4572 "# fn bar(b:uint) { }\n"
4573 "for i in range(0u, 256) {\n"
4581 msgid "### If expressions"
4588 "~~~~~~~~{.ebnf .gram}\n"
4589 "if_expr : \"if\" expr '{' block '}'\n"
4597 "else_tail : \"else\" [ if_expr\n"
4598 " | '{' block '}' ] ;\n"
4605 "An `if` expression is a conditional branch in program control. The form of "
4606 "an `if` expression is a condition expression, followed by a consequent "
4607 "block, any number of `else if` conditions and blocks, and an optional "
4608 "trailing `else` block. The condition expressions must have type `bool`. If a "
4609 "condition expression evaluates to `true`, the consequent block is executed "
4610 "and any subsequent `else if` or `else` block is skipped. If a condition "
4611 "expression evaluates to `false`, the consequent block is skipped and any "
4612 "subsequent `else if` condition is evaluated. If all `if` and `else if` "
4613 "conditions evaluate to `false` then any `else` block is executed."
4618 msgid "### Match expressions"
4624 "~~~~~~~~{.ebnf .gram} match_expr : \"match\" expr '{' match_arm [ '|' "
4625 "match_arm ] * '}' ;"
4630 msgid "match_arm : match_pat '=>' [ expr \",\" | '{' block '}' ] ;"
4635 msgid "match_pat : pat [ \"..\" pat ] ? [ \"if\" expr ] ; ~~~~~~~~"
4641 "A `match` expression branches on a *pattern*. The exact form of matching "
4642 "that occurs depends on the pattern. Patterns consist of some combination of "
4643 "literals, destructured enum constructors, structures, records and tuples, "
4644 "variable binding specifications, wildcards (`*`), and placeholders (`_`). A "
4645 "`match` expression has a *head expression*, which is the value to compare to "
4646 "the patterns. The type of the patterns must equal the type of the head "
4653 "In a pattern whose head expression has an `enum` type, a placeholder (`_`) "
4654 "stands for a *single* data field, whereas a wildcard `*` stands for *all* "
4655 "the fields of a particular variant. For example:"
4660 msgid "~~~~ enum List<X> { Nil, Cons(X, @List<X>) }"
4664 #: doc/rust.md:2457 doc/rust.md:2486
4665 msgid "let x: List<int> = Cons(10, @Cons(11, @Nil));"
4673 " Cons(_, @Nil) => fail!(\"singleton list\"),\n"
4674 " Cons(*) => return,\n"
4675 " Nil => fail!(\"empty list\")\n"
4683 "The first pattern matches lists constructed by applying `Cons` to any head "
4684 "value, and a tail value of `@Nil`. The second pattern matches _any_ list "
4685 "constructed with `Cons`, ignoring the values of its arguments. The "
4686 "difference between `_` and `*` is that the pattern `C(_)` is only type-"
4687 "correct if `C` has exactly one argument, while the pattern `C(*)` is type-"
4688 "correct for any enum variant `C`, regardless of how many arguments `C` has."
4694 "To execute an `match` expression, first the head expression is evaluated, "
4695 "then its value is sequentially compared to the patterns in the arms until a "
4696 "match is found. The first arm with a matching pattern is chosen as the "
4697 "branch target of the `match`, any variables bound by the pattern are "
4698 "assigned to local variables in the arm's block, and control enters the block."
4703 msgid "An example of an `match` expression:"
4708 msgid "~~~~ # fn process_pair(a: int, b: int) { } # fn process_ten() { }"
4713 msgid "enum List<X> { Nil, Cons(X, @List<X>) }"
4721 " Cons(a, @Cons(b, _)) => {\n"
4722 " process_pair(a,b);\n"
4724 " Cons(10, _) => {\n"
4740 "Patterns that bind variables default to binding to a copy or move of the "
4741 "matched value (depending on the matched value's type). This can be changed "
4742 "to bind to a borrowed pointer by using the ```ref``` keyword, or to a "
4743 "mutable borrowed pointer using ```ref mut```."
4749 "A pattern that's just an identifier, like `Nil` in the previous answer, "
4750 "could either refer to an enum variant that's in scope, or bind a new "
4751 "variable. The compiler resolves this ambiguity by forbidding variable "
4752 "bindings that occur in ```match``` patterns from shadowing names of variants "
4753 "that are in scope. For example, wherever ```List``` is in scope, a "
4754 "```match``` pattern would not be able to bind ```Nil``` as a new name. The "
4755 "compiler interprets a variable pattern `x` as a binding _only_ if there is "
4756 "no variant named `x` in scope. A convention you can use to avoid conflicts "
4757 "is simply to name variants with upper-case letters, and local variables with "
4758 "lower-case letters."
4764 "Multiple match patterns may be joined with the `|` operator. A range of "
4765 "values may be specified with `..`. For example:"
4770 msgid "~~~~ # let x = 2;"
4777 "let message = match x {\n"
4778 " 0 | 1 => \"not many\",\n"
4779 " 2 .. 9 => \"a few\",\n"
4788 "Range patterns only work on scalar types (like integers and characters; not "
4789 "like vectors and structs, which have sub-components). A range pattern may "
4790 "not be a sub-range of another range pattern inside the same `match`."
4796 "Finally, match patterns can accept *pattern guards* to further refine the "
4797 "criteria for matching a case. Pattern guards appear after the pattern and "
4798 "consist of a bool-typed expression following the `if` keyword. A pattern "
4799 "guard may refer to the variables bound within the pattern they follow."
4805 "~~~~ # let maybe_digit = Some(0); # fn process_digit(i: int) { } # fn "
4806 "process_other(i: int) { }"
4813 "let message = match maybe_digit {\n"
4814 " Some(x) if x < 10 => process_digit(x),\n"
4815 " Some(x) => process_other(x),\n"
4816 " None => fail!()\n"
4823 msgid "### Return expressions"
4828 msgid "~~~~~~~~{.ebnf .gram} return_expr : \"return\" expr ? ; ~~~~~~~~"
4834 "Return expressions are denoted with the keyword `return`. Evaluating a "
4835 "`return` expression moves its argument into the output slot of the current "
4836 "function, destroys the current function activation frame, and transfers "
4837 "control to the caller frame."
4842 msgid "An example of a `return` expression:"
4850 "fn max(a: int, b: int) -> int {\n"
4861 msgid "# Type system"
4872 "Every slot, item and value in a Rust program has a type. The _type_ of a "
4873 "*value* defines the interpretation of the memory holding it."
4879 "Built-in types and type-constructors are tightly integrated into the "
4880 "language, in nontrivial ways that are not possible to emulate in user-"
4881 "defined types. User-defined types have limited capabilities."
4886 msgid "### Primitive types"
4891 msgid "The primitive types are the following:"
4894 #. type: Bullet: '* '
4897 "The \"unit\" type `()`, having the single \"unit\" value `()` (occasionally "
4898 "called \"nil\"). ^[The \"unit\" value `()` is *not* a sentinel \"null "
4899 "pointer\" value for reference slots; the \"unit\" type is the implicit "
4900 "return type from functions otherwise lacking a return type, and can be used "
4901 "in other contexts (such as message-sending or type-parametric code) as a "
4905 #. type: Bullet: '* '
4907 msgid "The boolean type `bool` with values `true` and `false`."
4910 #. type: Bullet: '* '
4912 msgid "The machine types."
4915 #. type: Bullet: '* '
4917 msgid "The machine-dependent integer and floating-point types."
4922 msgid "#### Machine types"
4927 msgid "The machine types are the following:"
4930 #. type: Bullet: '* '
4933 "The unsigned word types `u8`, `u16`, `u32` and `u64`, with values drawn from "
4934 "the integer intervals $[0, 2^8 - 1]$, $[0, 2^{16} - 1]$, $[0, 2^{32} - 1]$ "
4935 "and $[0, 2^{64} - 1]$ respectively."
4938 #. type: Bullet: '* '
4941 "The signed two's complement word types `i8`, `i16`, `i32` and `i64`, with "
4942 "values drawn from the integer intervals $[-(2^7), 2^7 - 1]$, $[-(2^{15}), "
4943 "2^{15} - 1]$, $[-(2^{31}), 2^{31} - 1]$, $[-(2^{63}), 2^{63} - 1]$ "
4947 #. type: Bullet: '* '
4950 "The IEEE 754-2008 `binary32` and `binary64` floating-point types: `f32` and "
4951 "`f64`, respectively."
4956 msgid "#### Machine-dependent integer types"
4962 "The Rust type `uint`^[A Rust `uint` is analogous to a C99 `uintptr_t`.] is "
4963 "an unsigned integer type with target-machine-dependent size. Its size, in "
4964 "bits, is equal to the number of bits required to hold any memory address on "
4965 "the target machine."
4971 "The Rust type `int`^[A Rust `int` is analogous to a C99 `intptr_t`.] is a "
4972 "two's complement signed integer type with target-machine-dependent size. Its "
4973 "size, in bits, is equal to the size of the rust type `uint` on the same "
4979 msgid "#### Machine-dependent floating point type"
4985 "The Rust type `float` is a machine-specific type equal to one of the "
4986 "supported Rust floating-point machine types (`f32` or `f64`). It is the "
4987 "largest floating-point type that is directly supported by hardware on the "
4988 "target machine, or if the target machine has no floating-point hardware "
4989 "support, the largest floating-point type supported by the software floating-"
4990 "point library used to support the other floating-point machine types."
4996 "Note that due to the preference for hardware-supported floating-point, the "
4997 "type `float` may not be equal to the largest *supported* floating-point type."
5002 msgid "### Textual types"
5007 msgid "The types `char` and `str` hold textual data."
5013 "A value of type `char` is a Unicode character, represented as a 32-bit "
5014 "unsigned word holding a UCS-4 codepoint."
5020 "A value of type `str` is a Unicode string, represented as a vector of 8-bit "
5021 "unsigned bytes holding a sequence of UTF-8 codepoints. Since `str` is of "
5022 "unknown size, it is not a _first class_ type, but can only be instantiated "
5023 "through a pointer type, such as `&str`, `@str` or `~str`."
5028 msgid "### Tuple types"
5034 "The tuple type-constructor forms a new heterogeneous product of values "
5035 "similar to the record type-constructor. The differences are as follows:"
5038 #. type: Bullet: '* '
5040 msgid "tuple elements cannot be mutable, unlike record fields"
5043 #. type: Bullet: '* '
5046 "tuple elements are not named and can be accessed only by pattern-matching"
5052 "Tuple types and values are denoted by listing the types or values of their "
5053 "elements, respectively, in a parenthesized, comma-separated list."
5059 "The members of a tuple are laid out in memory contiguously, like a record, "
5060 "in order specified by the tuple type."
5065 msgid "An example of a tuple type and its use:"
5071 "~~~~ type Pair<'self> = (int,&'self str); let p: Pair<'static> = (10,\"hello"
5072 "\"); let (a, b) = p; assert!(b != \"world\"); ~~~~"
5077 msgid "### Vector types"
5083 "The vector type constructor represents a homogeneous array of values of a "
5084 "given type. A vector has a fixed size. (Operations like `vec.push` operate "
5085 "solely on owned vectors.) A vector type can be annotated with a _definite_ "
5086 "size, written with a trailing asterisk and integer literal, such as `[int * "
5087 "10]`. Such a definite-sized vector type is a first-class type, since its "
5088 "size is known statically. A vector without such a size is said to be of "
5089 "_indefinite_ size, and is therefore not a _first-class_ type. An indefinite-"
5090 "size vector can only be instantiated through a pointer type, such as `&[T]`, "
5091 "`@[T]` or `~[T]`. The kind of a vector type depends on the kind of its "
5092 "element type, as with other simple structural types."
5098 "Expressions producing vectors of definite size cannot be evaluated in a "
5099 "context expecting a vector of indefinite size; one must copy the definite-"
5100 "sized vector contents into a distinct vector of indefinite size."
5105 msgid "An example of a vector type and its use:"
5111 "~~~~ let v: &[int] = &[7, 5, 3]; let i: int = v[2]; assert!(i == 3); ~~~~"
5117 "All in-bounds elements of a vector are always initialized, and access to a "
5118 "vector is always bounds-checked."
5123 msgid "### Structure types"
5129 "A `struct` *type* is a heterogeneous product of other types, called the "
5130 "*fields* of the type. ^[`struct` types are analogous `struct` types in C, "
5131 "the *record* types of the ML family, or the *structure* types of the Lisp "
5138 "New instances of a `struct` can be constructed with a [struct expression]"
5139 "(#struct-expressions)."
5145 "The memory order of fields in a `struct` is given by the item defining it. "
5146 "Fields may be given in any order in a corresponding struct *expression*; the "
5147 "resulting `struct` value will always be laid out in memory in the order "
5148 "specified by the corresponding *item*."
5154 "The fields of a `struct` may be qualified by [visibility modifiers]"
5155 "(#visibility-modifiers), to restrict access to implementation-private data "
5162 "A _tuple struct_ type is just like a structure type, except that the fields "
5169 "A _unit-like struct_ type is like a structure type, except that it has no "
5170 "fields. The one value constructed by the associated [structure expression]"
5171 "(#structure-expression) is the only value that inhabits such a type."
5176 msgid "### Enumerated types"
5182 "An *enumerated type* is a nominal, heterogeneous disjoint union type, "
5183 "denoted by the name of an [`enum` item](#enumerations). ^[The `enum` type "
5184 "is analogous to a `data` constructor declaration in ML, or a *pick ADT* in "
5191 "An [`enum` item](#enumerations) declares both the type and a number of "
5192 "*variant constructors*, each of which is independently named and takes an "
5193 "optional tuple of arguments."
5199 "New instances of an `enum` can be constructed by calling one of the variant "
5200 "constructors, in a [call expression](#call-expressions)."
5206 "Any `enum` value consumes as much memory as the largest variant constructor "
5207 "for its corresponding `enum` type."
5213 "Enum types cannot be denoted *structurally* as types, but must be denoted by "
5214 "named reference to an [`enum` item](#enumerations)."
5219 msgid "### Recursive types"
5225 "Nominal types -- [enumerations](#enumerated-types) and [structures]"
5226 "(#structure-types) -- may be recursive. That is, each `enum` constructor or "
5227 "`struct` field may refer, directly or indirectly, to the enclosing `enum` or "
5228 "`struct` type itself. Such recursion has restrictions:"
5235 "* Recursive types must include a nominal type in the recursion\n"
5236 " (not mere [type definitions](#type-definitions),\n"
5237 " or other structural types such as [vectors](#vector-types) or [tuples](#tuple-types)).\n"
5238 "* A recursive `enum` item must have at least one non-recursive constructor\n"
5239 " (in order to give the recursion a basis case).\n"
5240 "* The size of a recursive type must be finite;\n"
5241 " in other words the recursive fields of the type must be [pointer types](#pointer-types).\n"
5242 "* Recursive type definitions can cross module boundaries, but not module *visibility* boundaries,\n"
5243 " or crate boundaries (in order to simplify the module system and type checker).\n"
5248 msgid "An example of a *recursive* type and its use:"
5258 " Cons(T, @List<T>)\n"
5264 msgid "let a: List<int> = Cons(7, @Cons(13, @Nil)); ~~~~"
5269 msgid "### Pointer types"
5275 "All pointers in Rust are explicit first-class values. They can be copied, "
5276 "stored into data structures, and returned from functions. There are four "
5277 "varieties of pointer in Rust:"
5284 "Managed pointers (`@`)\n"
5285 " : These point to managed heap allocations (or \"boxes\") in the task-local, managed heap.\n"
5286 " Managed pointers are written `@content`,\n"
5287 " for example `@int` means a managed pointer to a managed box containing an integer.\n"
5288 " Copying a managed pointer is a \"shallow\" operation:\n"
5289 " it involves only copying the pointer itself\n"
5290 " (as well as any reference-count or GC-barriers required by the managed heap).\n"
5291 " Dropping a managed pointer does not necessarily release the box it points to;\n"
5292 " the lifecycles of managed boxes are subject to an unspecified garbage collection algorithm.\n"
5299 "Owning pointers (`~`)\n"
5300 " : These point to owned heap allocations (or \"boxes\") in the shared, inter-task heap.\n"
5301 " Each owned box has a single owning pointer; pointer and pointee retain a 1:1 relationship at all times.\n"
5302 " Owning pointers are written `~content`,\n"
5303 " for example `~int` means an owning pointer to an owned box containing an integer.\n"
5304 " Copying an owned box is a \"deep\" operation:\n"
5305 " it involves allocating a new owned box and copying the contents of the old box into the new box.\n"
5306 " Releasing an owning pointer immediately releases its corresponding owned box.\n"
5313 "Borrowed pointers (`&`)\n"
5314 " : These point to memory _owned by some other value_.\n"
5315 " Borrowed pointers arise by (automatic) conversion from owning pointers, managed pointers,\n"
5316 " or by applying the borrowing operator `&` to some other value,\n"
5317 " including [lvalues, rvalues or temporaries](#lvalues-rvalues-and-temporaries).\n"
5318 " Borrowed pointers are written `&content`, or in some cases `&f/content` for some lifetime-variable `f`,\n"
5319 " for example `&int` means a borrowed pointer to an integer.\n"
5320 " Copying a borrowed pointer is a \"shallow\" operation:\n"
5321 " it involves only copying the pointer itself.\n"
5322 " Releasing a borrowed pointer typically has no effect on the value it points to,\n"
5323 " with the exception of temporary values,\n"
5324 " which are released when the last borrowed pointer to them is released.\n"
5331 "Raw pointers (`*`)\n"
5332 " : Raw pointers are pointers without safety or liveness guarantees.\n"
5333 " Raw pointers are written `*content`,\n"
5334 " for example `*int` means a raw pointer to an integer.\n"
5335 " Copying or dropping a raw pointer is has no effect on the lifecycle of any other value.\n"
5336 " Dereferencing a raw pointer or converting it to any other pointer type is an [`unsafe` operation](#unsafe-functions).\n"
5337 " Raw pointers are generally discouraged in Rust code;\n"
5338 " they exist to support interoperability with foreign code,\n"
5339 " and writing performance-critical or low-level functions.\n"
5344 msgid "### Function types"
5350 "The function type constructor `fn` forms new function types. A function "
5351 "type consists of a possibly-empty set of function-type modifiers (such as "
5352 "`unsafe` or `extern`), a sequence of input types and an output type."
5357 msgid "An example of a `fn` type:"
5365 "fn add(x: int, y: int) -> int {\n"
5372 msgid "let mut x = add(5,7);"
5378 "type Binop<'self> = &'self fn(int,int) -> int; let bo: Binop = add; x = "
5384 msgid "### Object types"
5390 "Every trait item (see [traits](#traits)) defines a type with the same name "
5391 "as the trait. This type is called the _object type_ of the trait. Object "
5392 "types permit \"late binding\" of methods, dispatched using _virtual method "
5393 "tables_ (\"vtables\"). Whereas most calls to trait methods are \"early bound"
5394 "\" (statically resolved) to specific implementations at compile time, a call "
5395 "to a method on an object type is only resolved to a vtable entry at compile "
5396 "time. The actual implementation for each vtable entry can vary on an object-"
5403 "Given a pointer-typed expression `E` of type `&T`, `~T` or `@T`, where `T` "
5404 "implements trait `R`, casting `E` to the corresponding pointer type `&R`, "
5405 "`~R` or `@R` results in a value of the _object type_ `R`. This result is "
5406 "represented as a pair of pointers: the vtable pointer for the `T` "
5407 "implementation of `R`, and the pointer value of `E`."
5412 msgid "An example of an object type:"
5421 "trait Printable {\n"
5422 " fn to_str(&self) -> ~str;\n"
5430 "impl Printable for int {\n"
5431 " fn to_str(&self) -> ~str { int::to_str(*self) }\n"
5439 "fn print(a: @Printable) {\n"
5440 " println(a.to_str());\n"
5449 " print(@10 as @Printable);\n"
5457 "In this example, the trait `Printable` occurs as an object type in both the "
5458 "type signature of `print`, and the cast expression in `main`."
5463 msgid "### Type parameters"
5469 "Within the body of an item that has type parameter declarations, the names "
5470 "of its type parameters are types:"
5478 "fn map<A: Clone, B: Clone>(f: &fn(A) -> B, xs: &[A]) -> ~[B] {\n"
5479 " if xs.len() == 0 {\n"
5482 " let first: B = f(xs[0].clone());\n"
5483 " let rest: ~[B] = map(f, xs.slice(1, xs.len()));\n"
5484 " return ~[first] + rest;\n"
5492 "Here, `first` has type `B`, referring to `map`'s `B` type parameter; and "
5493 "`rest` has type `~[B]`, a vector type with element type `B`."
5498 msgid "### Self types"
5504 "The special type `self` has a meaning within methods inside an impl item. It "
5505 "refers to the type of the implicit `self` argument. For example, in:"
5513 "trait Printable {\n"
5514 " fn make_string(&self) -> ~str;\n"
5522 "impl Printable for ~str {\n"
5523 " fn make_string(&self) -> ~str {\n"
5524 " (*self).clone()\n"
5533 "`self` refers to the value of type `~str` that is the receiver for a call to "
5534 "the method `make_string`."
5539 msgid "## Type kinds"
5545 "Types in Rust are categorized into kinds, based on various properties of the "
5546 "components of the type. The kinds are:"
5554 " : Types of this kind are deeply immutable;\n"
5555 " they contain no mutable memory locations\n"
5556 " directly or indirectly via pointers.\n"
5558 " : Types of this kind can be safely sent between tasks.\n"
5559 " This kind includes scalars, owning pointers, owned closures, and\n"
5560 " structural types containing only other owned types.\n"
5561 " All `Send` types are `'static`.\n"
5563 " : Types of this kind do not contain any borrowed pointers;\n"
5564 " this can be a useful guarantee for code\n"
5565 " that breaks borrowing assumptions\n"
5566 " using [`unsafe` operations](#unsafe-functions).\n"
5568 " : This is not strictly a kind,\n"
5569 " but its presence interacts with kinds:\n"
5570 " the `Drop` trait provides a single method `drop`\n"
5571 " that takes no parameters,\n"
5572 " and is run when values of the type are dropped.\n"
5573 " Such a method is called a \"destructor\",\n"
5574 " and are always executed in \"top-down\" order:\n"
5575 " a value is completely destroyed\n"
5576 " before any of the values it owns run their destructors.\n"
5577 " Only `Send` types can implement `Drop`.\n"
5585 " : Types with destructors, closure environments,\n"
5586 " and various other _non-first-class_ types,\n"
5587 " are not copyable at all.\n"
5588 " Such types can usually only be accessed through pointers,\n"
5589 " or in some cases, moved between mutable locations.\n"
5595 "Kinds can be supplied as _bounds_ on type parameters, like traits, in which "
5596 "case the parameter is constrained to types satisfying that kind."
5602 "By default, type parameters do not carry any assumed kind-bounds at all. "
5603 "When instantiating a type parameter, the kind bounds on the parameter are "
5604 "checked to be the same or narrower than the kind of the type that it is "
5605 "instantiated with."
5611 "Sending operations are not part of the Rust language, but are implemented in "
5612 "the library. Generic functions that send values bound the kind of these "
5613 "values to sendable."
5618 msgid "# Memory and concurrency models"
5624 "Rust has a memory model centered around concurrently-executing _tasks_. Thus "
5625 "its memory model and its concurrency model are best discussed "
5626 "simultaneously, as parts of each only make sense when considered from the "
5627 "perspective of the other."
5633 "When reading about the memory model, keep in mind that it is partitioned in "
5634 "order to support tasks; and when reading about tasks, keep in mind that "
5635 "their isolation and communication mechanisms are only possible due to the "
5636 "ownership and lifetime semantics of the memory model."
5641 msgid "## Memory model"
5647 "A Rust program's memory consists of a static set of *items*, a set of [tasks]"
5648 "(#tasks) each with its own *stack*, and a *heap*. Immutable portions of the "
5649 "heap may be shared between tasks, mutable portions may not."
5655 "Allocations in the stack consist of *slots*, and allocations in the heap "
5656 "consist of *boxes*."
5661 msgid "### Memory allocation and lifetime"
5667 "The _items_ of a program are those functions, modules and types that have "
5668 "their value calculated at compile-time and stored uniquely in the memory "
5669 "image of the rust process. Items are neither dynamically allocated nor freed."
5675 "A task's _stack_ consists of activation frames automatically allocated on "
5676 "entry to each function as the task executes. A stack allocation is reclaimed "
5677 "when control leaves the frame containing it."
5683 "The _heap_ is a general term that describes two separate sets of boxes: "
5684 "managed boxes -- which may be subject to garbage collection -- and owned "
5685 "boxes. The lifetime of an allocation in the heap depends on the lifetime of "
5686 "the box values pointing to it. Since box values may themselves be passed in "
5687 "and out of frames, or stored in the heap, heap allocations may outlive the "
5688 "frame they are allocated within."
5693 msgid "### Memory ownership"
5699 "A task owns all memory it can *safely* reach through local variables, as "
5700 "well as managed, owning and borrowed pointers."
5706 "When a task sends a value that has the `Send` trait to another task, it "
5707 "loses ownership of the value sent and can no longer refer to it. This is "
5708 "statically guaranteed by the combined use of \"move semantics\", and the "
5709 "compiler-checked _meaning_ of the `Send` trait: it is only instantiated for "
5710 "(transitively) sendable kinds of data constructor and pointers, never "
5711 "including managed or borrowed pointers."
5717 "When a stack frame is exited, its local allocations are all released, and "
5718 "its references to boxes (both managed and owned) are dropped."
5724 "A managed box may (in the case of a recursive, mutable managed type) be "
5725 "cyclic; in this case the release of memory inside the managed structure may "
5726 "be deferred until task-local garbage collection can reclaim it. Code can "
5727 "ensure no such delayed deallocation occurs by restricting itself to owned "
5728 "boxes and similar unmanaged kinds of data."
5734 "When a task finishes, its stack is necessarily empty and it therefore has no "
5735 "references to any boxes; the remainder of its heap is immediately freed."
5740 msgid "### Memory slots"
5745 msgid "A task's stack contains slots."
5751 "A _slot_ is a component of a stack frame, either a function parameter, a "
5752 "[temporary](#lvalues-rvalues-and-temporaries), or a local variable."
5758 "A _local variable_ (or *stack-local* allocation) holds a value directly, "
5759 "allocated within the stack's memory. The value is a part of the stack frame."
5765 "Local variables are immutable unless declared with `let mut`. The `mut` "
5766 "keyword applies to all local variables declared within that declaration (so "
5767 "`let mut (x, y) = ...` declares two mutable variables, `x` and `y`)."
5773 "Function parameters are immutable unless declared with `mut`. The `mut` "
5774 "keyword applies only to the following parameter (so `|mut x, y|` and `fn "
5775 "f(mut x: ~int, y: ~int)` declare one mutable variable `x` and one immutable "
5782 "Local variables are not initialized when allocated; the entire frame worth "
5783 "of local variables are allocated at once, on frame-entry, in an "
5784 "uninitialized state. Subsequent statements within a function may or may not "
5785 "initialize the local variables. Local variables can be used only after they "
5786 "have been initialized; this is enforced by the compiler."
5791 msgid "### Memory boxes"
5797 "A _box_ is a reference to a heap allocation holding another value. There are "
5798 "two kinds of boxes: *managed boxes* and *owned boxes*."
5804 "A _managed box_ type or value is constructed by the prefix *at* sigil `@`."
5810 "An _owned box_ type or value is constructed by the prefix *tilde* sigil `~`."
5816 "Multiple managed box values can point to the same heap allocation; copying a "
5817 "managed box value makes a shallow copy of the pointer (optionally "
5818 "incrementing a reference count, if the managed box is implemented through "
5819 "reference-counting)."
5825 "Owned box values exist in 1:1 correspondence with their heap allocation."
5831 "An example of constructing one managed box type and value, and one owned box "
5837 msgid "~~~~~~~~ let x: @int = @10; let x: ~int = ~10; ~~~~~~~~"
5843 "Some operations (such as field selection) implicitly dereference boxes. An "
5844 "example of an _implicit dereference_ operation performed on box values:"
5850 "~~~~~~~~ struct Foo { y: int } let x = @Foo{y: 10}; assert!(x.y == 10); "
5857 "Other operations act on box values as single-word-sized address values. For "
5858 "these operations, to access the value held in the box requires an explicit "
5859 "dereference of the box value. Explicitly dereferencing a box is indicated "
5860 "with the unary *star* operator `*`. Examples of such _explicit dereference_ "
5864 #. type: Bullet: '* '
5866 msgid "copying box values (`x = y`)"
5869 #. type: Bullet: '* '
5871 msgid "passing box values to functions (`f(x,y)`)"
5877 "An example of an explicit-dereference operation performed on box values:"
5882 msgid "~~~~~~~~ fn takes_boxed(b: @int) { }"
5887 msgid "fn takes_unboxed(b: int) { }"
5895 " let x: @int = @10;\n"
5896 " takes_boxed(x);\n"
5897 " takes_unboxed(*x);\n"
5910 "An executing Rust program consists of a tree of tasks. A Rust _task_ "
5911 "consists of an entry function, a stack, a set of outgoing communication "
5912 "channels and incoming communication ports, and ownership of some portion of "
5913 "the heap of a single operating-system process. (We expect that many "
5914 "programs will not use channels and ports directly, but will instead use "
5915 "higher-level abstractions provided in standard libraries, such as pipes.)"
5921 "Multiple Rust tasks may coexist in a single operating-system process. The "
5922 "runtime scheduler maps tasks to a certain number of operating-system "
5923 "threads. By default, the scheduler chooses the number of threads based on "
5924 "the number of concurrent physical CPUs detected at startup. It's also "
5925 "possible to override this choice at runtime. When the number of tasks "
5926 "exceeds the number of threads -- which is likely -- the scheduler "
5927 "multiplexes the tasks onto threads.^[ This is an M:N scheduler, which is "
5928 "known to give suboptimal results for CPU-bound concurrency problems. In "
5929 "such cases, running with the same number of threads and tasks can yield "
5930 "better results. Rust has M:N scheduling in order to support very large "
5931 "numbers of tasks in contexts where threads are too resource-intensive to use "
5932 "in large number. The cost of threads varies substantially per operating "
5933 "system, and is sometimes quite low, so this flexibility is not always worth "
5939 msgid "### Communication between tasks"
5945 "Rust tasks are isolated and generally unable to interfere with one another's "
5946 "memory directly, except through [`unsafe` code](#unsafe-functions). All "
5947 "contact between tasks is mediated by safe forms of ownership transfer, and "
5948 "data races on memory are prohibited by the type system."
5954 "Inter-task communication and co-ordination facilities are provided in the "
5955 "standard library. These include:"
5958 #. type: Bullet: ' - '
5961 "synchronous and asynchronous communication channels with various "
5962 "communication topologies"
5965 #. type: Bullet: ' - '
5968 "read-only and read-write shared variables with various safe mutual exclusion "
5972 #. type: Bullet: ' - '
5974 msgid "simple locks and semaphores"
5980 "When such facilities carry values, the values are restricted to the [`Send` "
5981 "type-kind](#type-kinds). Restricting communication interfaces to this kind "
5982 "ensures that no borrowed or managed pointers move between tasks. Thus "
5983 "access to an entire data structure can be mediated through its owning \"root"
5984 "\" value; no further locking or copying is required to avoid data races "
5985 "within the substructure of such a value."
5990 msgid "### Task lifecycle"
5996 "The _lifecycle_ of a task consists of a finite set of states and events that "
5997 "cause transitions between the states. The lifecycle states of a task are:"
6000 #. type: Bullet: '* '
6005 #. type: Bullet: '* '
6010 #. type: Bullet: '* '
6015 #. type: Bullet: '* '
6023 "A task begins its lifecycle -- once it has been spawned -- in the *running* "
6024 "state. In this state it executes the statements of its entry function, and "
6025 "any functions called by the entry function."
6031 "A task may transition from the *running* state to the *blocked* state any "
6032 "time it makes a blocking communication call. When the call can be completed "
6033 "-- when a message arrives at a sender, or a buffer opens to receive a "
6034 "message -- then the blocked task will unblock and transition back to "
6041 "A task may transition to the *failing* state at any time, due being killed "
6042 "by some external event or internally, from the evaluation of a `fail!()` "
6043 "macro. Once *failing*, a task unwinds its stack and transitions to the "
6044 "*dead* state. Unwinding the stack of a task is done by the task itself, on "
6045 "its own control stack. If a value with a destructor is freed during "
6046 "unwinding, the code for the destructor is run, also on the task's control "
6047 "stack. Running the destructor code causes a temporary transition to a "
6048 "*running* state, and allows the destructor code to cause any subsequent "
6049 "state transitions. The original task of unwinding and failing thereby may "
6050 "suspend temporarily, and may involve (recursive) unwinding of the stack of a "
6051 "failed destructor. Nonetheless, the outermost unwinding activity will "
6052 "continue until the stack is unwound and the task transitions to the *dead* "
6053 "state. There is no way to \"recover\" from task failure. Once a task has "
6054 "temporarily suspended its unwinding in the *failing* state, failure "
6055 "occurring from within this destructor results in *hard* failure. The "
6056 "unwinding procedure of hard failure frees resources but does not execute "
6057 "destructors. The original (soft) failure is still resumed at the point "
6058 "where it was temporarily suspended."
6064 "A task in the *dead* state cannot transition to other states; it exists only "
6065 "to have its termination status inspected by other tasks, and/or to await "
6066 "reclamation when the last reference to it drops."
6071 msgid "### Task scheduling"
6077 "The currently scheduled task is given a finite *time slice* in which to "
6078 "execute, after which it is *descheduled* at a loop-edge or similar "
6079 "preemption point, and another task within is scheduled, pseudo-randomly."
6085 "An executing task can yield control at any time, by making a library call to "
6086 "`std::task::yield`, which deschedules it immediately. Entering any other non-"
6087 "executing state (blocked, dead) similarly deschedules the task."
6092 msgid "# Runtime services, linkage and debugging"
6098 "The Rust _runtime_ is a relatively compact collection of C++ and Rust code "
6099 "that provides fundamental services and datatypes to all Rust tasks at run-"
6100 "time. It is smaller and simpler than many modern language runtimes. It is "
6101 "tightly integrated into the language's execution model of memory, tasks, "
6102 "communication and logging."
6108 "> **Note:** The runtime library will merge with the `std` library in future "
6114 msgid "### Memory allocation"
6120 "The runtime memory-management system is based on a _service-provider "
6121 "interface_, through which the runtime requests blocks of memory from its "
6122 "environment and releases them back to its environment when they are no "
6123 "longer needed. The default implementation of the service-provider interface "
6124 "consists of the C runtime functions `malloc` and `free`."
6130 "The runtime memory-management system, in turn, supplies Rust tasks with "
6131 "facilities for allocating, extending and releasing stacks, as well as "
6132 "allocating and freeing heap data."
6137 msgid "### Built in types"
6143 "The runtime provides C and Rust code to assist with various built-in types, "
6144 "such as vectors, strings, and the low level communication system (ports, "
6151 "Support for other built-in types such as simple types, tuples, records, and "
6152 "enums is open-coded by the Rust compiler."
6157 msgid "### Task scheduling and communication"
6163 "The runtime provides code to manage inter-task communication. This includes "
6164 "the system of task-lifecycle state transitions depending on the contents of "
6165 "queues, as well as code to copy values between queues and their recipients "
6166 "and to serialize values for transmission over operating-system inter-process "
6167 "communication facilities."
6172 msgid "### Logging system"
6178 "The runtime contains a system for directing [logging expressions](#log-"
6179 "expressions) to a logging console and/or internal logging buffers. Logging "
6180 "can be enabled per module."
6186 "Logging output is enabled by setting the `RUST_LOG` environment variable. "
6187 "`RUST_LOG` accepts a logging specification made up of a comma-separated list "
6188 "of paths, with optional log levels. For each module containing log "
6189 "expressions, if `RUST_LOG` contains the path to that module or a parent of "
6190 "that module, then logs of the appropriate level will be output to the "
6197 "The path to a module consists of the crate name, any parent modules, then "
6198 "the module itself, all separated by double colons (`::`). The optional log "
6199 "level can be appended to the module path with an equals sign (`=`) followed "
6200 "by the log level, from 1 to 4, inclusive. Level 1 is the error level, 2 is "
6201 "warning, 3 info, and 4 debug. Any logs less than or equal to the specified "
6202 "level will be output. If not specified then log level 4 is assumed."
6208 "As an example, to see all the logs generated by the compiler, you would set "
6209 "`RUST_LOG` to `rustc`, which is the crate name (as specified in its `link` "
6210 "[attribute](#attributes)). To narrow down the logs to just crate resolution, "
6211 "you would set it to `rustc::metadata::creader`. To see just error logging "
6218 "Note that when compiling source files that don't specify a crate name the "
6219 "crate is given a default name that matches the source file, with the "
6220 "extension removed. In that case, to turn on logging for a program compiled "
6221 "from, e.g. `helloworld.rs`, `RUST_LOG` should be set to `helloworld`."
6227 "As a convenience, the logging spec can also be set to a special pseudo-"
6228 "crate, `::help`. In this case, when the application starts, the runtime will "
6229 "simply output a list of loaded modules containing log expressions, then exit."
6235 "The Rust runtime itself generates logging information. The runtime's logs "
6236 "are generated for a number of artificial modules in the `::rt` pseudo-crate, "
6237 "and can be enabled just like the logs for any standard module. The full list "
6238 "of runtime logging modules follows."
6241 #. type: Bullet: '* '
6243 msgid "`::rt::mem` Memory management"
6246 #. type: Bullet: '* '
6248 msgid "`::rt::comm` Messaging and task communication"
6251 #. type: Bullet: '* '
6253 msgid "`::rt::task` Task management"
6256 #. type: Bullet: '* '
6258 msgid "`::rt::dom` Task scheduling"
6261 #. type: Bullet: '* '
6263 msgid "`::rt::trace` Unused"
6266 #. type: Bullet: '* '
6268 msgid "`::rt::cache` Type descriptor cache"
6271 #. type: Bullet: '* '
6273 msgid "`::rt::upcall` Compiler-generated runtime calls"
6276 #. type: Bullet: '* '
6278 msgid "`::rt::timer` The scheduler timer"
6281 #. type: Bullet: '* '
6283 msgid "`::rt::gc` Garbage collection"
6286 #. type: Bullet: '* '
6288 msgid "`::rt::stdlib` Functions used directly by the standard library"
6291 #. type: Bullet: '* '
6293 msgid "`::rt::kern` The runtime kernel"
6296 #. type: Bullet: '* '
6298 msgid "`::rt::backtrace` Log a backtrace on task failure"
6301 #. type: Bullet: '* '
6303 msgid "`::rt::callback` Unused"
6308 msgid "#### Logging Expressions"
6314 "Rust provides several macros to log information. Here's a simple Rust "
6315 "program that demonstrates all four of them:"
6324 " error!(\"This is an error log\")\n"
6325 " warn!(\"This is a warn log\")\n"
6326 " info!(\"this is an info log\")\n"
6327 " debug!(\"This is a debug log\")\n"
6335 "These four log levels correspond to levels 1-4, as controlled by `RUST_LOG`:"
6341 "```bash $ RUST_LOG=rust=3 ./rust rust: ~\"\\\"This is an error log\\\"\" "
6342 "rust: ~\"\\\"This is a warn log\\\"\" rust: ~\"\\\"this is an info log\\\"\" "
6348 msgid "# Appendix: Rationales and design tradeoffs"
6359 msgid "# Appendix: Influences and further references"
6364 msgid "## Influences"
6370 "> The essential problem that must be solved in making a fault-tolerant > "
6371 "software system is therefore that of fault-isolation. Different programmers "
6372 "> will write different modules, some modules will be correct, others will "
6373 "have > errors. We do not want the errors in one module to adversely affect "
6374 "the > behaviour of a module which does not have any errors. > > — Joe "
6381 "> In our approach, all data is private to some process, and processes can > "
6382 "only communicate through communications channels. *Security*, as used > in "
6383 "this paper, is the property which guarantees that processes in a system > "
6384 "cannot affect each other except by explicit communication. > > When "
6385 "security is absent, nothing which can be proven about a single module > in "
6386 "isolation can be guaranteed to hold when that module is embedded in a > "
6387 "system [...] > > — Robert Strom and Shaula Yemini"
6393 "> Concurrent and applicative programming complement each other. The > "
6394 "ability to send messages on channels provides I/O without side effects, > "
6395 "while the avoidance of shared data helps keep concurrent processes from > "
6396 "colliding. > > — Rob Pike"
6402 "Rust is not a particularly original language. It may however appear unusual "
6403 "by contemporary standards, as its design elements are drawn from a number of "
6404 "\"historical\" languages that have, with a few exceptions, fallen out of "
6405 "favour. Five prominent lineages contribute the most, though their influences "
6406 "have come and gone during the course of Rust's development:"
6409 #. type: Bullet: '* '
6412 "The NIL (1981) and Hermes (1990) family. These languages were developed by "
6413 "Robert Strom, Shaula Yemini, David Bacon and others in their group at IBM "
6414 "Watson Research Center (Yorktown Heights, NY, USA)."
6417 #. type: Bullet: '* '
6420 "The Erlang (1987) language, developed by Joe Armstrong, Robert Virding, "
6421 "Claes Wikström, Mike Williams and others in their group at the Ericsson "
6422 "Computer Science Laboratory (Älvsjö, Stockholm, Sweden) ."
6425 #. type: Bullet: '* '
6428 "The Sather (1990) language, developed by Stephen Omohundro, Chu-Cheow Lim, "
6429 "Heinz Schmidt and others in their group at The International Computer "
6430 "Science Institute of the University of California, Berkeley (Berkeley, CA, "
6434 #. type: Bullet: '* '
6437 "The Newsqueak (1988), Alef (1995), and Limbo (1996) family. These languages "
6438 "were developed by Rob Pike, Phil Winterbottom, Sean Dorward and others in "
6439 "their group at Bell Labs Computing Sciences Research Center (Murray Hill, "
6443 #. type: Bullet: '* '
6446 "The Napier (1985) and Napier88 (1988) family. These languages were developed "
6447 "by Malcolm Atkinson, Ron Morrison and others in their group at the "
6448 "University of St. Andrews (St. Andrews, Fife, UK)."
6454 "Additional specific influences can be seen from the following languages:"
6457 #. type: Bullet: '* '
6459 msgid "The stack-growth implementation of Go."
6462 #. type: Bullet: '* '
6464 msgid "The structural algebraic types and compilation manager of SML."
6467 #. type: Bullet: '* '
6469 msgid "The attribute and assembly systems of C#."
6472 #. type: Bullet: '* '
6474 msgid "The references and deterministic destructor system of C++."
6477 #. type: Bullet: '* '
6479 msgid "The memory region systems of the ML Kit and Cyclone."
6482 #. type: Bullet: '* '
6484 msgid "The typeclass system of Haskell."
6487 #. type: Bullet: '* '
6489 msgid "The lexical identifier rule of Python."
6492 #. type: Bullet: '* '
6494 msgid "The block syntax of Ruby."