]> git.lizzy.rs Git - rust.git/blobdiff - src/doc/rust.md
Replace all ~"" with "".to_owned()
[rust.git] / src / doc / rust.md
index f73b40a3ff47e396edd99216c87f64ce2125ef70..17941a152094fadf8165adb420c358a1eac5112c 100644 (file)
@@ -206,13 +206,12 @@ The keywords are the following strings:
 as
 break
 crate
-do
 else enum extern
 false fn for
 if impl in
 let loop
 match mod mut
-priv pub
+priv proc pub
 ref return
 self static struct super
 true trait type
@@ -433,7 +432,7 @@ operators](#binary-operator-expressions), or [keywords](#keywords).
 ## Paths
 
 ~~~~ {.notrust .ebnf .gram}
-expr_path : ident [ "::" expr_path_tail ] + ;
+expr_path : [ "::" ] ident [ "::" expr_path_tail ] + ;
 expr_path_tail : '<' type_expr [ ',' type_expr ] + '>'
                | expr_path ;
 
@@ -476,6 +475,51 @@ let x = id::<int>(10);         // Type arguments used in a call expression
 # }
 ~~~~
 
+Paths can be denoted with various leading qualifiers to change the meaning of
+how it is resolved:
+
+* Paths starting with `::` are considered to be global paths where the
+  components of the path start being resolved from the crate root. Each
+  identifier in the path must resolve to an item.
+
+  ```rust
+  mod a {
+      pub fn foo() {}
+  }
+  mod b {
+      pub fn foo() {
+          ::a::foo(); // call a's foo function
+      }
+  }
+  # fn main() {}
+  ```
+
+* Paths starting with the keyword `super` begin resolution relative to the
+  parent module. Each further identifier must resolve to an item
+
+  ```rust
+  mod a {
+      pub fn foo() {}
+  }
+  mod b {
+      pub fn foo() {
+          super::a::foo(); // call a's foo function
+      }
+  }
+  # fn main() {}
+  ```
+
+* Paths starting with the keyword `self` begin resolution relative to the
+  current module. Each further identifier must resolve to an item.
+
+  ```rust
+  fn foo() {}
+  fn bar() {
+      self::foo();
+  }
+  # fn main() {}
+  ```
+
 # Syntax extensions
 
 A number of minor features of Rust are not central enough to have their own
@@ -1197,8 +1241,8 @@ enum Animal {
     Cat { name: ~str, weight: f64 }
 }
 
-let mut a: Animal = Dog(~"Cocoa", 37.2);
-a = Cat{ name: ~"Spotty", weight: 2.7 };
+let mut a: Animal = Dog("Cocoa".to_owned(), 37.2);
+a = Cat{ name: "Spotty".to_owned(), weight: 2.7 };
 ~~~~
 
 In this example, `Cat` is a _struct-like enum variant_,
@@ -1472,11 +1516,13 @@ with the exception that they may not have a body
 and are instead terminated by a semicolon.
 
 ~~~~
-# use std::libc::{c_char, FILE};
+extern crate libc;
+use libc::{c_char, FILE};
 
 extern {
     fn fopen(filename: *c_char, mode: *c_char) -> *FILE;
 }
+# fn main() {}
 ~~~~
 
 Functions within external blocks may be called by Rust code,
@@ -1540,10 +1586,10 @@ pub struct Bar {
     field: int
 }
 
-// Declare a public enum with public and private variants
+// Declare a public enum with two public variants
 pub enum State {
     PubliclyAccessibleState,
-    priv PrivatelyAccessibleState
+    PubliclyAccessibleState2,
 }
 ~~~~
 
@@ -1961,110 +2007,110 @@ A complete list of the built-in language items follows:
 
 #### Built-in Traits
 
-`send`
+`send`
   : Able to be sent across task boundaries.
-`sized`
+`sized`
   : Has a size known at compile time.
-`copy`
+`copy`
   : Types that do not move ownership when used by-value.
-`share`
+`share`
   : Able to be safely shared between tasks when aliased.
-`drop`
+`drop`
   : Have destructors.
 
 #### Operators
 
 These language items are traits:
 
-`add`
+`add`
   : Elements can be added (for example, integers and floats).
-`sub`
+`sub`
   : Elements can be subtracted.
-`mul`
+`mul`
   : Elements can be multiplied.
-`div`
+`div`
   : Elements have a division operation.
-`rem`
+`rem`
   : Elements have a remainder operation.
-`neg`
+`neg`
   : Elements can be negated arithmetically.
-`not`
+`not`
   : Elements can be negated logically.
-`bitxor`
+`bitxor`
   : Elements have an exclusive-or operation.
-`bitand`
+`bitand`
   : Elements have a bitwise `and` operation.
-`bitor`
+`bitor`
   : Elements have a bitwise `or` operation.
-`shl`
+`shl`
   : Elements have a left shift operation.
-`shr`
+`shr`
   : Elements have a right shift operation.
-`index`
+`index`
   : Elements can be indexed.
-`eq`
+`eq`
   : Elements can be compared for equality.
-`ord`
+`ord`
   : Elements have a partial ordering.
-`deref`
+`deref`
   : `*` can be applied, yielding a reference to another type
-`deref_mut`
+`deref_mut`
   : `*` can be applied, yielding a mutable reference to another type
 
 
 These are functions:
 
-`str_eq`
+`str_eq`
   : Compare two strings (`&str`) for equality.
-`uniq_str_eq`
+`uniq_str_eq`
   : Compare two owned strings (`~str`) for equality.
-`strdup_uniq`
+`strdup_uniq`
   : Return a new unique string
     containing a copy of the contents of a unique string.
 
 #### Types
 
-`unsafe`
+`unsafe`
   : A type whose contents can be mutated through an immutable reference
-`type_id`
+`type_id`
   : The type returned by the `type_id` intrinsic.
 
 #### Marker types
 
 These types help drive the compiler's analysis
 
-`covariant_type`
+`covariant_type`
   : The type parameter should be considered covariant
-`contravariant_type`
+`contravariant_type`
   : The type parameter should be considered contravariant
-`invariant_type`
+`invariant_type`
   : The type parameter should be considered invariant
-`covariant_lifetime`
+`covariant_lifetime`
   : The lifetime parameter should be considered covariant
-`contravariant_lifetime`
+`contravariant_lifetime`
   : The lifetime parameter should be considered contravariant
-`invariant_lifetime`
+`invariant_lifetime`
   : The lifetime parameter should be considered invariant
-`no_send_bound`
+`no_send_bound`
   : This type does not implement "send", even if eligible
-`no_copy_bound`
+`no_copy_bound`
   : This type does not implement "copy", even if eligible
-`no_share_bound`
+`no_share_bound`
   : This type does not implement "share", even if eligible
-`managed_bound`
+`managed_bound`
   : This type implements "managed"
 
-`fail_`
+`fail_`
   : Abort the program with an error.
-`fail_bounds_check`
+`fail_bounds_check`
   : Abort the program with a bounds check error.
-`exchange_malloc`
+`exchange_malloc`
   : Allocate memory on the exchange heap.
-`exchange_free`
+`exchange_free`
   : Free memory that was allocated on the exchange heap.
-`malloc`
+`malloc`
   : Allocate memory on the managed heap.
-`free`
+`free`
   : Free memory that was allocated on the managed heap.
 
 > **Note:** This list is likely to become out of date. We should auto-generate it
@@ -2558,12 +2604,12 @@ task in a _failing state_.
 
 ~~~~ {.ignore}
 # use std::task;
-# do task::spawn {
+# task::spawn(proc() {
 
 ([1, 2, 3, 4])[0];
 (["a", "b"])[10]; // fails
 
-# }
+# })
 ~~~~
 
 ### Unary operator expressions
@@ -2572,9 +2618,9 @@ Rust defines six symbolic unary operators.
 They are all written as prefix operators,
 before the expression they apply to.
 
-`-`
+`-`
   : Negation. May only be applied to numeric types.
-`*`
+`*`
   : Dereference. When applied to a [pointer](#pointer-types) it denotes the pointed-to location.
     For pointers to mutable locations, the resulting [lvalue](#lvalues-rvalues-and-temporaries) can be assigned to.
     On non-pointer types, it calls the `deref` method of the `std::ops::Deref` trait, or the
@@ -2582,14 +2628,14 @@ before the expression they apply to.
     for an outer expression that will or could mutate the dereference), and produces the
     result of dereferencing the `&` or `&mut` borrowed pointer returned from the overload method.
 
-`!`
+`!`
   : Logical negation. On the boolean type, this flips between `true` and
     `false`. On integer types, this inverts the individual bits in the
     two's complement representation of the value.
-`~`
+`~`
   :  [Boxing](#pointer-types) operators. Allocate a box to hold the value they are applied to,
      and store the value in it. `~` creates an owned box.
-`&`
+`&`
   : Borrow operator. Returns a reference, pointing to its operand.
     The operand of a borrow is statically proven to outlive the resulting pointer.
     If the borrow-checker cannot prove this, it is a compilation error.
@@ -2610,19 +2656,19 @@ defined in the `std::ops` module of the `std` library.
 This means that arithmetic operators can be overridden for user-defined types.
 The default meaning of the operators on standard types is given here.
 
-`+`
+`+`
   : Addition and vector/string concatenation.
     Calls the `add` method on the `std::ops::Add` trait.
-`-`
+`-`
   : Subtraction.
     Calls the `sub` method on the `std::ops::Sub` trait.
-`*`
+`*`
   : Multiplication.
     Calls the `mul` method on the `std::ops::Mul` trait.
-`/`
+`/`
   : Quotient.
     Calls the `div` method on the `std::ops::Div` trait.
-`%`
+`%`
   : Remainder.
     Calls the `rem` method on the `std::ops::Rem` trait.
 
@@ -2633,19 +2679,19 @@ are syntactic sugar for calls to methods of built-in traits.
 This means that bitwise operators can be overridden for user-defined types.
 The default meaning of the operators on standard types is given here.
 
-`&`
+`&`
   : And.
     Calls the `bitand` method of the `std::ops::BitAnd` trait.
-`|`
+`|`
   : Inclusive or.
     Calls the `bitor` method of the `std::ops::BitOr` trait.
-`^`
+`^`
   : Exclusive or.
     Calls the `bitxor` method of the `std::ops::BitXor` trait.
-`<<`
+`<<`
   : Logical left shift.
     Calls the `shl` method of the `std::ops::Shl` trait.
-`>>`
+`>>`
   : Logical right shift.
     Calls the `shr` method of the `std::ops::Shr` trait.
 
@@ -2666,22 +2712,22 @@ syntactic sugar for calls to built-in traits.
 This means that comparison operators can be overridden for user-defined types.
 The default meaning of the operators on standard types is given here.
 
-`==`
+`==`
   : Equal to.
     Calls the `eq` method on the `std::cmp::Eq` trait.
-`!=`
+`!=`
   : Unequal to.
     Calls the `ne` method on the `std::cmp::Eq` trait.
-`<`
+`<`
   : Less than.
     Calls the `lt` method on the `std::cmp::Ord` trait.
-`>`
+`>`
   : Greater than.
     Calls the `gt` method on the `std::cmp::Ord` trait.
-`<=`
+`<=`
   : Less than or equal.
     Calls the `le` method on the `std::cmp::Ord` trait.
-`>=`
+`>=`
   : Greater than or equal.
     Calls the `ge` method on the `std::cmp::Ord` trait.
 
@@ -3367,7 +3413,7 @@ All pointers in Rust are explicit first-class values.
 They can be copied, stored into data structures, and returned from functions.
 There are four varieties of pointer in Rust:
 
-Owning pointers (`~`)
+Owning pointers (`~`)
   : These point to owned heap allocations (or "boxes") in the shared, inter-task heap.
     Each owned box has a single owning pointer; pointer and pointee retain a 1:1 relationship at all times.
     Owning pointers are written `~content`,
@@ -3376,7 +3422,7 @@ Owning pointers (`~`)
     it involves allocating a new owned box and copying the contents of the old box into the new box.
     Releasing an owning pointer immediately releases its corresponding owned box.
 
-References (`&`)
+References (`&`)
   : These point to memory _owned by some other value_.
     References arise by (automatic) conversion from owning pointers, managed pointers,
     or by applying the borrowing operator `&` to some other value,
@@ -3389,7 +3435,7 @@ References (`&`)
     with the exception of temporary values,
     which are released when the last reference to them is released.
 
-Raw pointers (`*`)
+Raw pointers (`*`)
   : Raw pointers are pointers without safety or liveness guarantees.
     Raw pointers are written `*content`,
     for example `*int` means a raw pointer to an integer.
@@ -3414,15 +3460,28 @@ fn add(x: int, y: int) -> int {
 
 let mut x = add(5,7);
 
-type Binop<'a> = 'a |int,int| -> int;
+type Binop<'a> = |int,int|: 'a -> int;
 let bo: Binop = add;
 x = bo(5,7);
 ~~~~
 
 ### Closure types
 
-The type of a closure mapping an input of type `A` to an output of type `B` is `|A| -> B`. A closure with no arguments or return values has type `||`.
+~~~~ {.notrust .ebnf .notation}
+closure_type := [ 'unsafe' ] [ '<' lifetime-list '>' ] '|' arg-list '|'
+                [ ':' bound-list ] [ '->' type ]
+procedure_type := 'proc' [ '<' lifetime-list '>' ] '(' arg-list ')'
+                  [ ':' bound-list ] [ '->' type ]
+lifetime-list := lifetime | lifetime ',' lifetime-list
+arg-list := ident ':' type | ident ':' type ',' arg-list
+bound-list := bound | bound '+' bound-list
+bound := path | lifetime
+~~~~
 
+The type of a closure mapping an input of type `A` to an output of type `B` is
+`|A| -> B`. A closure with no arguments or return values has type `||`.
+Similarly, a procedure mapping `A` to `B` is `proc(A) -> B` and a no-argument
+and no-return value closure has type `proc()`.
 
 An example of creating and calling a closure:
 
@@ -3445,6 +3504,30 @@ call_closure(closure_no_args, closure_args);
 
 ```
 
+Unlike closures, procedures may only be invoked once, but own their
+environment, and are allowed to move out of their environment. Procedures are
+allocated on the heap (unlike closures). An example of creating and calling a
+procedure:
+
+```rust
+let string = "Hello".to_owned();
+
+// Creates a new procedure, passing it to the `spawn` function.
+spawn(proc() {
+  println!("{} world!", string);
+});
+
+// the variable `string` has been moved into the previous procedure, so it is
+// no longer usable.
+
+
+// Create an invoke a procedure. Note that the procedure is *moved* when
+// invoked, so it cannot be invoked again.
+let f = proc(n: int) { n + 22 };
+println!("answer: {}", f(20));
+
+```
+
 ### Object types
 
 Every trait item (see [traits](#traits)) defines a type with the same name as the trait.
@@ -3526,24 +3609,24 @@ call to the method `make_string`.
 Types in Rust are categorized into kinds, based on various properties of the components of the type.
 The kinds are:
 
-`Send`
+`Send`
   : Types of this kind can be safely sent between tasks.
     This kind includes scalars, owning pointers, owned closures, and
     structural types containing only other owned types.
     All `Send` types are `'static`.
-`Copy`
+`Copy`
   : Types of this kind consist of "Plain Old Data"
     which can be copied by simply moving bits.
     All values of this kind can be implicitly copied.
     This kind includes scalars and immutable references,
     as well as structural types containing other `Copy` types.
-`'static`
+`'static`
   : Types of this kind do not contain any references (except for
     references with the `static` lifetime, which are allowed).
     This can be a useful guarantee for code
     that breaks borrowing assumptions
     using [`unsafe` operations](#unsafe-functions).
-`Drop`
+`Drop`
   : This is not strictly a kind,
     but its presence interacts with kinds:
     the `Drop` trait provides a single method `drop`
@@ -3555,7 +3638,7 @@ The kinds are:
     before any of the values it owns run their destructors.
     Only `Send` types can implement `Drop`.
 
-_Default_
+_Default_
   : Types with destructors, closure environments,
     and various other _non-first-class_ types,
     are not copyable at all.
@@ -3837,7 +3920,9 @@ link Rust crates together, and more information about native libraries can be
 found in the [ffi tutorial][ffi].
 
 In one session of compilation, the compiler can generate multiple artifacts
-through the usage of command line flags and the `crate_type` attribute.
+through the usage of either command line flags or the `crate_type` attribute.
+If one or more command line flag is specified, all `crate_type` attributes will
+be ignored in favor of only building the artifacts specified by command line.
 
 * `--crate-type=bin`, `#[crate_type = "bin"]` - A runnable executable will be
   produced.  This requires that there is a `main` function in the crate which
@@ -3880,7 +3965,10 @@ through the usage of command line flags and the `crate_type` attribute.
 
 Note that these outputs are stackable in the sense that if multiple are
 specified, then the compiler will produce each form of output at once without
-having to recompile.
+having to recompile. However, this only applies for outputs specified by the same
+method. If only `crate_type` attributes are specified, then they will all be
+built, but if one or more `--crate-type` command line flag is specified,
+then only those outputs will be built.
 
 With all these different kinds of outputs, if crate A depends on crate B, then
 the compiler could find B in various different forms throughout the system. The
@@ -3968,10 +4056,6 @@ crate name the crate is given a default name that matches the source file,
 with the extension removed. In that case, to turn on logging for a program
 compiled from, e.g. `helloworld.rs`, `RUST_LOG` should be set to `helloworld`.
 
-As a convenience, the logging spec can also be set to a special pseudo-crate,
-`::help`. In this case, when the application starts, the runtime will
-simply output a list of loaded modules containing log expressions, then exit.
-
 #### Logging Expressions
 
 Rust provides several macros to log information. Here's a simple Rust program