// Copyright 2010-2014 The Rust Project Developers.
```
+# Coordination and communication
+
+Get feedback from other developers on
+[discuss.rust-lang.org][discuss], and
+[#rust-internals][pound-rust-internals].
+
+[pound-rust-internals]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-internals
+[discuss]: http://discuss.rust-lang.org
+
For more details, please refer to
[Note-development-policy](https://github.com/rust-lang/rust/wiki/Note-development-policy).
\fB\-\-emit\fR [asm|llvm-bc|llvm-ir|obj|link|dep-info]
Configure the output that rustc will produce
.TP
-\fB\-\-print\fR [crate-name|output-file-names|sysroot]
+\fB\-\-print\fR [crate-name|file-names|sysroot]
Comma separated list of compiler information to print on stdout
.TP
\fB\-g\fR
################################################################################
TARGET_CRATES := libc std flate arena term \
- serialize getopts collections test time rand \
+ serialize getopts collections test rand \
log regex graphviz core rbml alloc \
unicode
RUSTC_CRATES := rustc rustc_typeck rustc_borrowck rustc_resolve rustc_driver \
rustc_trans rustc_back rustc_llvm
-HOST_CRATES := syntax $(RUSTC_CRATES) rustdoc regex_macros fmt_macros
+HOST_CRATES := syntax $(RUSTC_CRATES) rustdoc fmt_macros
CRATES := $(TARGET_CRATES) $(HOST_CRATES)
TOOLS := compiletest rustdoc rustc
DEPS_rustc_borrowck := rustc log graphviz syntax
DEPS_rustc_resolve := rustc log syntax
DEPS_rustc := syntax flate arena serialize getopts rbml \
- time log graphviz rustc_llvm rustc_back
+ log graphviz rustc_llvm rustc_back
DEPS_rustc_llvm := native:rustllvm libc std
DEPS_rustc_back := std syntax rustc_llvm flate log libc
DEPS_rustdoc := rustc rustc_driver native:hoedown serialize getopts \
- test time
+ test
DEPS_flate := std native:miniz
DEPS_arena := std
DEPS_graphviz := std
DEPS_getopts := std
DEPS_collections := core alloc unicode
DEPS_num := std
-DEPS_test := std getopts serialize rbml term time regex native:rust_test_helpers
-DEPS_time := std serialize
+DEPS_test := std getopts serialize rbml term regex native:rust_test_helpers
DEPS_rand := core
DEPS_log := std regex
DEPS_regex := std
-DEPS_regex_macros = rustc syntax std regex
DEPS_fmt_macros = std
TOOL_DEPS_compiletest := test getopts
$(filter-out rustc_driver, \
$(filter-out log, \
$(filter-out regex, \
- $(filter-out regex_macros, \
$(filter-out getopts, \
- $(filter-out time, \
- $(filter-out syntax, $(CRATES)))))))))))))
+ $(filter-out syntax, $(CRATES)))))))))))
COMPILER_DOC_CRATES := rustc rustc_trans rustc_borrowck rustc_resolve \
rustc_typeck rustc_driver syntax
check-build-lexer-verifier: $(BG)verify
ifeq ($(NO_REBUILD),)
-VERIFY_DEPS := rustc-stage2-H-$(CFG_BUILD) $(LD)stamp.regex_macros $(LD)stamp.rustc
+VERIFY_DEPS := rustc-stage2-H-$(CFG_BUILD) $(LD)stamp.rustc
else
VERIFY_DEPS :=
endif
# Remove tmp files because it's a decent amount of disk space
$(Q)rm -R tmp/dist
-ifeq ($(CFG_DISABLE_DOCS),)
-prepare_install: dist/$(PKG_NAME)-$(CFG_BUILD).tar.gz dist/$(DOC_PKG_NAME)-$(CFG_BUILD).tar.gz | tmp/empty_dir
-else
-prepare_install: dist/$(PKG_NAME)-$(CFG_BUILD).tar.gz | tmp/empty_dir
-endif
+prepare_install: dist-tar-bins | tmp/empty_dir
uninstall:
ifeq (root user, $(USER) $(patsubst %,user,$(SUDO_USER)))
# Remove tmp files because it's a decent amount of disk space
$(Q)rm -R tmp/dist
-prepare_uninstall: dist/$(PKG_NAME)-$(CFG_BUILD).tar.gz | tmp/empty_dir
+prepare_uninstall: dist-tar-bins | tmp/empty_dir
.PHONY: install prepare_install uninstall prepare_uninstall
$$(TLIB$(1)_T_$(2)_H_$(3))/stamp.$$(crate)) \
$$(CRATE_FULLDEPS_$(1)_T_$(2)_H_$(3)_$(4))
-# The regex crate depends on the regex_macros crate during testing, but it
-# notably depend on the *host* regex_macros crate, not the target version.
-# Additionally, this is not a dependency in stage1, only in stage2.
-ifeq ($(4),regex)
-ifneq ($(1),1)
-TESTDEP_$(1)_$(2)_$(3)_$(4) += $$(TLIB$(1)_T_$(3)_H_$(3))/stamp.regex_macros
-endif
-endif
-
else
TESTDEP_$(1)_$(2)_$(3)_$(4) = $$(RSINPUTS_$(4))
endif
CRATEDOCTESTDEP_$(1)_$(2)_$(3)_$(4) = $$(RSINPUTS_$(4))
endif
-# (Issues #13732, #13983, #14000) The doc for the regex crate includes
-# uses of the `regex!` macro from the regex_macros crate. There is
-# normally a dependence injected that makes the target's regex depend
-# upon the host's regex_macros (see #13845), but that dependency
-# injection is currently skipped for stage1 as a special case.
-#
-# Therefore, as a further special case, this conditional skips
-# attempting to run the doc tests for the regex crate atop stage1,
-# (since there is no regex_macros crate for the stage1 rustc to load).
-#
-# (Another approach for solving this would be to inject the desired
-# dependence for stage1 as well, by setting things up to generate a
-# regex_macros crate that was compatible with the stage1 rustc and
-# thus re-enable our ability to run this test.)
-ifeq (stage$(1)-crate-$(4),stage1-crate-regex)
-check-stage$(1)-T-$(2)-H-$(3)-doc-crate-$(4)-exec:
- @$$(call E, skipping doc-crate-$(4) as it uses macros and cannot run at stage$(1))
-else
check-stage$(1)-T-$(2)-H-$(3)-doc-crate-$(4)-exec: \
$$(call TEST_OK_FILE,$(1),$(2),$(3),doc-crate-$(4))
-endif
ifeq ($(2),$$(CFG_BUILD))
$$(call TEST_OK_FILE,$(1),$(2),$(3),doc-crate-$(4)): $$(CRATEDOCTESTDEP_$(1)_$(2)_$(3)_$(4))
use std::str::FromStr;
use regex::Regex;
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
pub enum Mode {
CompileFail,
RunFail,
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Config {
// The library paths required for running the compiler
pub compile_lib_path: String,
use std::os;
use std::io;
use std::io::fs;
-use std::str::{FromStr, from_str};
+use std::str::FromStr;
use std::thunk::Thunk;
use getopts::{optopt, optflag, reqopt};
use common::Config;
pub static EXPECTED_PATTERN : &'static str =
r"//~(?P<follow>\|)?(?P<adjusts>\^*)\s*(?P<kind>\S*)\s*(?P<msg>.*)";
-#[deriving(PartialEq, Show)]
+#[derive(PartialEq, Show)]
enum WhichLine { ThisLine, FollowPrevious(uint), AdjustBackward(uint) }
// Load any test directives embedded in the file
[Mibbit](http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust). Click
that link, and you'll be chatting with other Rustaceans (a silly nickname we
call ourselves), and we can help you out. Other great resources include [our
-mailing list](https://mail.mozilla.org/listinfo/rust-dev), [the /r/rust
+forum](http://discuss.rust-lang.org/), [the /r/rust
subreddit](http://www.reddit.com/r/rust), and [Stack
Overflow](http://stackoverflow.com/questions/tagged/rust).
its functionality. Eventually, we'll add more. Since we started off by using
Cargo, it'll be easy to add later.
-Let's convert Hello World to Cargo. The first thing we need to do to begin
-using Cargo is to install Cargo. Luckily for us, the script we ran to install
-Rust includes Cargo by default. If you installed Rust some other way, you may
-want to [check the Cargo
+If you installed Rust via the official installers you will also have
+Cargo. If you installed Rust some other way, you may want to [check
+the Cargo
README](https://github.com/rust-lang/cargo#installing-cargo-from-nightlies)
for specific instructions about installing it.
+Let's convert Hello World to Cargo.
+
To Cargo-ify our project, we need to do two things: Make a `Cargo.toml`
configuration file, and put our source file in the right place. Let's
do that part first:
```{rust}
fn main() {
- let x = 5i;
+ let x = 5;
}
```
This means we can do things like:
```{rust}
-let (x, y) = (1i, 2i);
+let (x, y) = (1, 2);
```
After this expression is evaluated, `x` will be one, and `y` will be two.
Patterns are really powerful, but this is about all we can do with them so far.
So let's just keep this in the back of our minds as we go forward.
-By the way, in these examples, `i` indicates that the number is an integer.
-
Rust is a statically typed language, which means that we specify our types up
front. So why does our first example compile? Well, Rust has this thing called
"type inference." If it can figure out what the type of something is, Rust
We can add the type if we want to, though. Types come after a colon (`:`):
```{rust}
-let x: int = 5;
+let x: i32 = 5;
```
If I asked you to read this out loud to the rest of the class, you'd say "`x`
-is a binding with the type `int` and the value `five`."
+is a binding with the type `i32` and the value `five`."
In future examples, we may annotate the type in a comment. The examples will
look like this:
```{rust}
fn main() {
- let x = 5i; // x: int
+ let x = 5; // x: i32
}
```
By default, bindings are **immutable**. This code will not compile:
```{ignore}
-let x = 5i;
-x = 10i;
+let x = 5;
+x = 10;
```
It will give you this error:
```text
error: re-assignment of immutable variable `x`
- x = 10i;
+ x = 10;
^~~~~~~
```
If you want a binding to be mutable, you can use `mut`:
```{rust}
-let mut x = 5i; // mut x: int
-x = 10i;
+let mut x = 5; // mut x: i32
+x = 10;
```
There is no single reason that bindings are immutable by default, but we can
Giving it a type will compile, though:
```{rust}
-let x: int;
+let x: i32;
```
Let's try it out. Change your `src/main.rs` file to look like this:
```{rust}
fn main() {
- let x: int;
+ let x: i32;
println!("Hello world!");
}
```text
Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default
-src/main.rs:2 let x: int;
+src/main.rs:2 let x: i32;
^
```
```{rust,ignore}
fn main() {
- let x: int;
+ let x: i32;
println!("The value of x is: {}", x);
}
In the case of `if`, there is one choice that leads down two paths:
```rust
-let x = 5i;
+let x = 5;
-if x == 5i {
+if x == 5 {
println!("x is five!");
}
```
If you want something to happen in the `false` case, use an `else`:
```{rust}
-let x = 5i;
+let x = 5;
-if x == 5i {
+if x == 5 {
println!("x is five!");
} else {
println!("x is not five :(");
```{rust}
-let x = 5i;
+let x = 5;
-let y = if x == 5i {
- 10i
+let y = if x == 5 {
+ 10
} else {
- 15i
-}; // y: int
+ 15
+}; // y: i32
```
Which we can (and probably should) write like this:
```{rust}
-let x = 5i;
+let x = 5;
-let y = if x == 5i { 10i } else { 15i }; // y: int
+let y = if x == 5 { 10 } else { 15 }; // y: i32
```
This reveals two interesting things about Rust: it is an expression-based
following will produce a compile-time error:
```{ignore}
-let x = (let y = 5i); // expected identifier, found keyword `let`
+let x = (let y = 5); // expected identifier, found keyword `let`
```
The compiler is telling us here that it was expecting to see the beginning of
an expression, and a `let` can only begin a statement, not an expression.
-Note that assigning to an already-bound variable (e.g. `y = 5i`) is still an
+Note that assigning to an already-bound variable (e.g. `y = 5`) is still an
expression, although its value is not particularly useful. Unlike C, where an
-assignment evaluates to the assigned value (e.g. `5i` in the previous example),
+assignment evaluates to the assigned value (e.g. `5` in the previous example),
in Rust the value of an assignment is the unit type `()` (which we'll cover later).
The second kind of statement in Rust is the **expression statement**. Its
code:
```{rust}
-let x = 5i;
+let x = 5;
-let y: int = if x == 5i { 10i } else { 15i };
+let y: i32 = if x == 5 { 10 } else { 15 };
```
Note that I've added the type annotation to `y`, to specify explicitly that I
This is not the same as this, which won't compile:
```{ignore}
-let x = 5i;
+let x = 5;
-let y: int = if x == 5i { 10i; } else { 15i; };
+let y: i32 = if x == 5 { 10; } else { 15; };
```
Note the semicolons after the 10 and 15. Rust will give us the following error:
```text
-error: mismatched types: expected `int` but found `()` (expected int but found ())
+error: mismatched types: expected `i32` but found `()` (expected i32 but found ())
```
We expected an integer, but we got `()`. `()` is pronounced 'unit', and is a
special type in Rust's type system. In Rust, `()` is _not_ a valid value for a
-variable of type `int`. It's only a valid value for variables of the type `()`,
+variable of type `i32`. It's only a valid value for variables of the type `()`,
which aren't very useful. Remember how we said statements don't return a value?
Well, that's the purpose of unit in this case. The semicolon turns any
expression into a statement by throwing away its value and returning unit
So, what about taking arguments? Here's a function that prints a number:
```{rust}
-fn print_number(x: int) {
+fn print_number(x: i32) {
println!("x is: {}", x);
}
```
print_number(5);
}
-fn print_number(x: int) {
+fn print_number(x: i32) {
println!("x is: {}", x);
}
```
print_sum(5, 6);
}
-fn print_sum(x: int, y: int) {
+fn print_sum(x: i32, y: i32) {
println!("sum is: {}", x + y);
}
```
What about returning a value? Here's a function that adds one to an integer:
```{rust}
-fn add_one(x: int) -> int {
+fn add_one(x: i32) -> i32 {
x + 1
}
```
You'll note the lack of a semicolon here. If we added it in:
```{ignore}
-fn add_one(x: int) -> int {
+fn add_one(x: i32) -> i32 {
x + 1;
}
```
```text
error: not all control paths return a value
-fn add_one(x: int) -> int {
+fn add_one(x: i32) -> i32 {
x + 1;
}
```
Remember our earlier discussions about semicolons and `()`? Our function claims
-to return an `int`, but with a semicolon, it would return `()` instead. Rust
+to return an `i32`, but with a semicolon, it would return `()` instead. Rust
realizes this probably isn't what we want, and suggests removing the semicolon.
This is very much like our `if` statement before: the result of the block
But what about early returns? Rust does have a keyword for that, `return`:
```{rust}
-fn foo(x: int) -> int {
+fn foo(x: i32) -> i32 {
if x < 5 { return x; }
x + 1
style:
```{rust}
-fn foo(x: int) -> int {
+fn foo(x: i32) -> i32 {
if x < 5 { return x; }
return x + 1;
```{rust}
// Line comments are anything after '//' and extend to the end of the line.
-let x = 5i; // this is also a line comment.
+let x = 5; // this is also a line comment.
// If you have a long explanation for something, you can put line comments next
// to each other. Put a space between the // and your comment so that it's
Tuples are an ordered list of a fixed size. Like this:
```rust
-let x = (1i, "hello");
+let x = (1, "hello");
```
The parentheses and commas form this two-length tuple. Here's the same code, but
with the type annotated:
```rust
-let x: (int, &str) = (1, "hello");
+let x: (i32, &str) = (1, "hello");
```
As you can see, the type of a tuple looks just like the tuple, but with each
position having a type name rather than the value. Careful readers will also
-note that tuples are heterogeneous: we have an `int` and a `&str` in this tuple.
+note that tuples are heterogeneous: we have an `i32` and a `&str` in this tuple.
You haven't seen `&str` as a type before, and we'll discuss the details of
strings later. In systems programming languages, strings are a bit more complex
than in other languages. For now, just read `&str` as "a string slice," and
an example:
```rust
-let (x, y, z) = (1i, 2i, 3i);
+let (x, y, z) = (1, 2, 3);
println!("x is {}", x);
```
arity and contained types.
```rust
-let mut x = (1i, 2i); // x: (int, int)
-let y = (2i, 3i); // y: (int, int)
+let mut x = (1, 2); // x: (i32, i32)
+let y = (2, 3); // y: (i32, i32)
x = y;
```
tuples have the same type.
```rust
-let x = (1i, 2i, 3i);
-let y = (2i, 2i, 4i);
+let x = (1, 2, 3);
+let y = (2, 2, 4);
if x == y {
println!("yes");
One other use of tuples is to return multiple values from a function:
```rust
-fn next_two(x: int) -> (int, int) { (x + 1i, x + 2i) }
+fn next_two(x: i32) -> (i32, i32) { (x + 1, x + 2) }
fn main() {
- let (x, y) = next_two(5i);
+ let (x, y) = next_two(5);
println!("x, y = {}, {}", x, y);
}
```
```rust
struct Point {
- x: int,
- y: int,
+ x: i32,
+ y: i32,
}
fn main() {
- let origin = Point { x: 0i, y: 0i }; // origin: Point
+ let origin = Point { x: 0, y: 0 }; // origin: Point
println!("The origin is at ({}, {})", origin.x, origin.y);
}
```{rust}
struct Point {
- x: int,
- y: int,
+ x: i32,
+ y: i32,
}
fn main() {
- let mut point = Point { x: 0i, y: 0i };
+ let mut point = Point { x: 0, y: 0 };
point.x = 5;
```{rust}
-struct Color(int, int, int);
-struct Point(int, int, int);
+struct Color(i32, i32, i32);
+struct Point(i32, i32, i32);
```
These two will not be equal, even if they have the same values:
```{rust}
-# struct Color(int, int, int);
-# struct Point(int, int, int);
+# struct Color(i32, i32, i32);
+# struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
```
```{rust}
struct Color {
- red: int,
- blue: int,
- green: int,
+ red: i32,
+ blue: i32,
+ green: i32,
}
struct Point {
- x: int,
- y: int,
- z: int,
+ x: i32,
+ y: i32,
+ z: i32,
}
```
you create a new type that's a synonym for another one:
```{rust}
-struct Inches(int);
+struct Inches(i32);
let length = Inches(10);
```{rust}
use std::cmp::Ordering;
-fn cmp(a: int, b: int) -> Ordering {
+fn cmp(a: i32, b: i32) -> Ordering {
if a < b { Ordering::Less }
else if a > b { Ordering::Greater }
else { Ordering::Equal }
}
fn main() {
- let x = 5i;
- let y = 10i;
+ let x = 5;
+ let y = 10;
let ordering = cmp(x, y); // ordering: Ordering
```
There's a symbol here we haven't seen before: the double colon (`::`).
-This is used to indicate a namesapce. In this case, `Ordering` lives in
+This is used to indicate a namespace. In this case, `Ordering` lives in
the `cmp` submodule of the `std` module. We'll talk more about modules
later in the guide. For now, all you need to know is that you can `use`
things from the standard library if you need them.
```{rust}
enum OptionalInt {
- Value(int),
+ Value(i32),
Missing,
}
```
-This enum represents an `int` that we may or may not have. In the `Missing`
+This enum represents an `i32` that we may or may not have. In the `Missing`
case, we have no value, but in the `Value` case, we do. This enum is specific
-to `int`s, though. We can make it usable by any type, but we haven't quite
+to `i32`s, though. We can make it usable by any type, but we haven't quite
gotten there yet!
You can also have any number of values in an enum:
```{rust}
enum OptionalColor {
- Color(int, int, int),
+ Color(i32, i32, i32),
Missing,
}
```
groupings with something more powerful. Check it out:
```{rust}
-let x = 5i;
+let x = 5;
match x {
1 => println!("one"),
In other words, Rust is trying to tell us we forgot a value. Because `x` is an
integer, Rust knows that it can have a number of different values – for example,
-`6i`. Without the `_`, however, there is no arm that could match, and so Rust refuses
+`6`. Without the `_`, however, there is no arm that could match, and so Rust refuses
to compile. `_` acts like a 'catch-all arm'. If none of the other arms match,
the arm with `_` will, and since we have this catch-all arm, we now have an arm
for every possible value of `x`, and so our program will compile successfully.
```{rust}
use std::cmp::Ordering;
-fn cmp(a: int, b: int) -> Ordering {
+fn cmp(a: i32, b: i32) -> Ordering {
if a < b { Ordering::Less }
else if a > b { Ordering::Greater }
else { Ordering::Equal }
}
fn main() {
- let x = 5i;
- let y = 10i;
+ let x = 5;
+ let y = 10;
let ordering = cmp(x, y);
```{rust}
use std::cmp::Ordering;
-fn cmp(a: int, b: int) -> Ordering {
+fn cmp(a: i32, b: i32) -> Ordering {
if a < b { Ordering::Less }
else if a > b { Ordering::Greater }
else { Ordering::Equal }
}
fn main() {
- let x = 5i;
- let y = 10i;
+ let x = 5;
+ let y = 10;
match cmp(x, y) {
Ordering::Less => println!("less"),
```{rust}
enum OptionalInt {
- Value(int),
+ Value(i32),
Missing,
}
That is how you can get and use the values contained in `enum`s.
It can also allow us to handle errors or unexpected computations; for example, a
-function that is not guaranteed to be able to compute a result (an `int` here)
+function that is not guaranteed to be able to compute a result (an `i32` here)
could return an `OptionalInt`, and we would handle that value with a `match`.
As you can see, `enum` and `match` used together are quite useful!
```{rust}
use std::cmp::Ordering;
-fn cmp(a: int, b: int) -> Ordering {
+fn cmp(a: i32, b: i32) -> Ordering {
if a < b { Ordering::Less }
else if a > b { Ordering::Greater }
else { Ordering::Equal }
}
fn main() {
- let x = 5i;
- let y = 10i;
+ let x = 5;
+ let y = 10;
println!("{}", match cmp(x, y) {
Ordering::Less => "less",
Instead, it looks like this:
```{rust}
-for x in range(0i, 10i) {
- println!("{}", x); // x: int
+for x in range(0, 10) {
+ println!("{}", x); // x: i32
}
```
iteration. This will only print the odd numbers:
```{rust}
-for x in range(0i, 10i) {
+for x in range(0, 10) {
if x % 2 == 0 { continue; }
println!("{}", x);
same type. By default, arrays are immutable.
```{rust}
-let a = [1i, 2i, 3i]; // a: [int; 3]
-let mut m = [1i, 2i, 3i]; // mut m: [int; 3]
+let a = [1, 2, 3]; // a: [i32; 3]
+let mut m = [1, 2, 3]; // mut m: [i32; 3]
```
There's a shorthand for initializing each element of an array to the same
-value. In this example, each element of `a` will be initialized to `0i`:
+value. In this example, each element of `a` will be initialized to `0`:
```{rust}
-let a = [0i; 20]; // a: [int; 20]
+let a = [0; 20]; // a: [i32; 20]
```
Arrays have type `[T; N]`. We'll talk about this `T` notation later, when we
number in order:
```{rust}
-let a = [1i, 2, 3]; // Only the first item needs a type suffix
+let a = [1, 2, 3];
println!("a has {} elements", a.len());
for e in a.iter() {
with the `vec!` macro:
```{rust}
-let v = vec![1i, 2, 3]; // v: Vec<int>
+let v = vec![1, 2, 3]; // v: Vec<i32>
```
(Notice that unlike the `println!` macro we've used in the past, we use square
arrays. In addition, (mutable) vectors can grow automatically:
```{rust}
-let mut nums = vec![1i, 2, 3]; // mut nums: Vec<int>
+let mut nums = vec![1, 2, 3]; // mut nums: Vec<i32>
nums.push(4);
arrays:
```{rust}
-let a = [0i, 1, 2, 3, 4];
+let a = [0, 1, 2, 3, 4];
let middle = a.slice(1, 4); // A slice of a: just the elements [1,2,3]
for e in middle.iter() {
```{rust}
enum OptionalInt {
- Value(int),
+ Value(i32),
Missing,
}
very similar to our `OptionalInt`: an `IoResult<T>`. We haven't talked about
`IoResult<T>` yet because it is the **generic** form of our `OptionalInt`.
Until then, you can think of it as being the same thing, just for any type –
-not just `int`s.
+not just `i32`s.
Rust provides a method on these `IoResult<T>`s called `ok()`, which does the
same thing as our `match` statement but assumes that we have a valid value.
fn main() {
println!("Guess the number!");
- let secret_number = (rand::random() % 100i) + 1i; // secret_number: int
+ let secret_number = (rand::random() % 100) + 1; // secret_number: i32
println!("The secret number is: {}", secret_number);
$ cargo build
Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
src/main.rs:7:26: 7:34 error: the type of this value must be known in this context
-src/main.rs:7 let secret_number = (rand::random() % 100i) + 1i;
+src/main.rs:7 let secret_number = (rand::random() % 100) + 1;
^~~~~~~~
error: aborting due to previous error
```
context." What's up with that? Well, as it turns out, `rand::random()` can
generate many kinds of random values, not just integers. And in this case, Rust
isn't sure what kind of value `random()` should generate. So we have to help
-it. With number literals, we just add an `i` onto the end to tell Rust they're
+it. With number literals, we can just add an `i32` onto the end to tell Rust they're
integers, but that does not work with functions. There's a different syntax,
and it looks like this:
```{rust,ignore}
-rand::random::<int>();
+rand::random::<i32>();
```
-This says "please give me a random `int` value." We can change our code to use
+This says "please give me a random `i32` value." We can change our code to use
this hint:
```{rust,no_run}
fn main() {
println!("Guess the number!");
- let secret_number = (rand::random::<int>() % 100i) + 1i;
+ let secret_number = (rand::random::<i32>() % 100) + 1;
println!("The secret number is: {}", secret_number);
}
}
-fn cmp(a: int, b: int) -> Ordering {
+fn cmp(a: i32, b: i32) -> Ordering {
if a < b { Ordering::Less }
else if a > b { Ordering::Greater }
else { Ordering::Equal }
```bash
$ cargo build
Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
-src/main.rs:20:15: 20:20 error: mismatched types: expected `int` but found `collections::string::String` (expected int but found struct collections::string::String)
+src/main.rs:20:15: 20:20 error: mismatched types: expected `i32` but found `collections::string::String` (expected i32 but found struct collections::string::String)
src/main.rs:20 match cmp(input, secret_number) {
^~~~~
-src/main.rs:20:22: 20:35 error: mismatched types: expected `int` but found `uint` (expected int but found uint)
+src/main.rs:20:22: 20:35 error: mismatched types: expected `i32` but found `uint` (expected i32 but found uint)
src/main.rs:20 match cmp(input, secret_number) {
^~~~~~~~~~~~~
error: aborting due to 2 previous errors
```{rust}
#[test]
fn is_one_equal_to_one() {
- assert_eq!(1i, 1i);
+ assert_eq!(1, 1);
}
```
```{rust,ignore}
#[test]
fn math_checks_out() {
- let result = add_three_times_four(5i);
+ let result = add_three_times_four(5);
- assert_eq!(32i, result);
+ assert_eq!(32, result);
}
```
$ cargo test
Compiling testing v0.0.1 (file:///home/you/projects/testing)
/home/you/projects/testing/tests/lib.rs:3:18: 3:38 error: unresolved name `add_three_times_four`.
-/home/you/projects/testing/tests/lib.rs:3 let result = add_three_times_four(5i);
+/home/you/projects/testing/tests/lib.rs:3 let result = add_three_times_four(5);
^~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Build failed, waiting for other jobs to finish...
```{rust}
# fn main() {}
-pub fn add_three_times_four(x: int) -> int {
+pub fn add_three_times_four(x: i32) -> i32 {
(x + 3) * 4
}
```
#[test]
fn math_checks_out() {
- let result = add_three_times_four(5i);
+ let result = add_three_times_four(5);
- assert_eq!(32i, result);
+ assert_eq!(32, result);
}
```
Change your `src/lib.rs` to look like this:
```{rust,ignore}
-pub fn add_three_times_four(x: int) -> int {
+pub fn add_three_times_four(x: i32) -> i32 {
times_four(add_three(x))
}
-fn add_three(x: int) -> int { x + 3 }
+fn add_three(x: i32) -> i32 { x + 3 }
-fn times_four(x: int) -> int { x * 4 }
+fn times_four(x: i32) -> i32 { x * 4 }
```
If you run `cargo test`, you should get the same output:
#[test]
fn math_checks_out() {
- let result = add_three_times_four(5i);
+ let result = add_three_times_four(5);
- assert_eq!(32i, result);
+ assert_eq!(32, result);
}
#[test]
fn test_add_three() {
- let result = add_three(5i);
+ let result = add_three(5);
- assert_eq!(8i, result);
+ assert_eq!(8, result);
}
```
unit test. Open up your `src/lib.rs` and add this:
```{rust,ignore}
-pub fn add_three_times_four(x: int) -> int {
+pub fn add_three_times_four(x: i32) -> i32 {
times_four(add_three(x))
}
-fn add_three(x: int) -> int { x + 3 }
+fn add_three(x: i32) -> i32 { x + 3 }
-fn times_four(x: int) -> int { x * 4 }
+fn times_four(x: i32) -> i32 { x * 4 }
#[cfg(test)]
mod test {
#[test]
fn test_add_three() {
- let result = add_three(5i);
+ let result = add_three(5);
- assert_eq!(8i, result);
+ assert_eq!(8, result);
}
#[test]
fn test_times_four() {
- let result = times_four(5i);
+ let result = times_four(5);
- assert_eq!(20i, result);
+ assert_eq!(20, result);
}
}
```
reference:
```{rust}
-let x = 5i;
+let x = 5;
let y = &x;
```
rather than the reference itself) `y`, we use the asterisk (`*`):
```{rust}
-let x = 5i;
+let x = 5;
let y = &x;
-assert_eq!(5i, *y);
+assert_eq!(5, *y);
```
Like any `let` binding, references are immutable by default.
You can declare that functions take a reference:
```{rust}
-fn add_one(x: &int) -> int { *x + 1 }
+fn add_one(x: &i32) -> i32 { *x + 1 }
fn main() {
assert_eq!(6, add_one(&5));
**alias** (point to the same place):
```{rust}
-let x = 5i;
+let x = 5;
let y = &x;
let z = &x;
```
We can make a mutable reference by using `&mut` instead of `&`:
```{rust}
-let mut x = 5i;
+let mut x = 5;
let y = &mut x;
```
Note that `x` must also be mutable. If it isn't, like this:
```{rust,ignore}
-let x = 5i;
+let x = 5;
let y = &mut x;
```
This won't work:
```{rust,ignore}
-let mut x = 5i;
+let mut x = 5;
let y = &mut x;
let z = &mut x;
```
^
note: previous borrow ends here
fn main() {
- let mut x = 5i;
+ let mut x = 5;
let y = &mut x;
let z = &mut x;
}
```{rust}
{
- let x = 5i; // x is the owner of this integer, which is memory on the stack.
+ let x = 5; // x is the owner of this integer, which is memory on the stack.
// other code here...
/// this function borrows an integer. It's given back automatically when the
/// function returns.
-fn foo(x: &int) -> &int { x }
+fn foo(x: &i32) -> &i32 { x }
{
// x is the owner of the integer, which is memory on the stack.
- let x = 5i;
+ let x = 5;
// privilege 2: you may lend that resource to as many borrowers as you like
let y = &x;
{
// x is the owner of this integer, which is memory on the stack.
- let mut x = 5i;
+ let mut x = 5;
// privilege 3: you may lend that resource to a single borrower, mutably
let y = &mut x;
The code:
```{rust,ignore}
-let mut x = 5i;
+let mut x = 5;
let y = &mut x;
let z = &mut x;
```
^
note: previous borrow ends here
fn main() {
- let mut x = 5i;
+ let mut x = 5;
let y = &mut x;
let z = &mut x;
}
```text
note: previous borrow ends here
fn main() {
- let mut x = 5i;
+ let mut x = 5;
let y = &mut x;
let z = &mut x;
}
```{rust}
{
- let x = box 5i;
+ let x = box 5;
println!("{}", *x); // Prints 5
}
```
```{c,ignore}
{
- int *x = (int *)malloc(sizeof(int));
+ i32 *x = (i32 *)malloc(sizeof(i32));
if (!x) abort();
*x = 5;
printf("%d\n", *x);
reference to them and then use the original box:
```{rust,ignore}
-let mut x = box 5i;
+let mut x = box 5;
let y = &mut x;
*x; // you might expect 5, but this is actually an error
done borrowing the value, we can use it again. This works fine:
```{rust}
-let mut x = box 5i;
+let mut x = box 5;
{
let y = &mut x;
```{rust}
use std::rc::Rc;
-let x = Rc::new(5i);
+let x = Rc::new(5);
let y = x.clone();
println!("{} {}", *x, *y); // Prints 5 5
'any' case:
```{rust}
-let x = 1i;
+let x = 1;
match x {
1 => println!("one"),
You can match multiple patterns with `|`:
```{rust}
-let x = 1i;
+let x = 1;
match x {
1 | 2 => println!("one or two"),
You can match a range of values with `...`:
```{rust}
-let x = 1i;
+let x = 1;
match x {
1 ... 5 => println!("one through five"),
the value to a name with `@`:
```{rust}
-let x = 1i;
+let x = 1;
match x {
e @ 1 ... 5 => println!("got a range element {}", e),
```{rust}
enum OptionalInt {
- Value(int),
+ Value(i32),
Missing,
}
-let x = OptionalInt::Value(5i);
+let x = OptionalInt::Value(5);
match x {
- OptionalInt::Value(..) => println!("Got an int!"),
+ OptionalInt::Value(..) => println!("Got an i32!"),
OptionalInt::Missing => println!("No such luck."),
}
```
```{rust}
enum OptionalInt {
- Value(int),
+ Value(i32),
Missing,
}
-let x = OptionalInt::Value(5i);
+let x = OptionalInt::Value(5);
match x {
- OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
- OptionalInt::Value(..) => println!("Got an int!"),
+ OptionalInt::Value(i) if i > 5 => println!("Got an i32 bigger than five!"),
+ OptionalInt::Value(..) => println!("Got an i32!"),
OptionalInt::Missing => println!("No such luck."),
}
```
with. First, `&`:
```{rust}
-let x = &5i;
+let x = &5;
match x {
&val => println!("Got a value: {}", val),
}
```
-Here, the `val` inside the `match` has type `int`. In other words, the left-hand
-side of the pattern destructures the value. If we have `&5i`, then in `&val`, `val`
-would be `5i`.
+Here, the `val` inside the `match` has type `i32`. In other words, the left-hand
+side of the pattern destructures the value. If we have `&5`, then in `&val`, `val`
+would be `5`.
If you want to get a reference, use the `ref` keyword:
```{rust}
-let x = 5i;
+let x = 5;
match x {
ref r => println!("Got a reference to {}", r),
}
```
-Here, the `r` inside the `match` has the type `&int`. In other words, the `ref`
+Here, the `r` inside the `match` has the type `&i32`. In other words, the `ref`
keyword _creates_ a reference, for use in the pattern. If you need a mutable
reference, `ref mut` will work in the same way:
```{rust}
-let mut x = 5i;
+let mut x = 5;
match x {
ref mut mr => println!("Got a mutable reference to {}", mr),
```{rust}
# #![allow(non_shorthand_field_patterns)]
struct Point {
- x: int,
- y: int,
+ x: i32,
+ y: i32,
}
-let origin = Point { x: 0i, y: 0i };
+let origin = Point { x: 0, y: 0 };
match origin {
Point { x: x, y: y } => println!("({},{})", x, y),
```{rust}
# #![allow(non_shorthand_field_patterns)]
struct Point {
- x: int,
- y: int,
+ x: i32,
+ y: i32,
}
-let origin = Point { x: 0i, y: 0i };
+let origin = Point { x: 0, y: 0 };
match origin {
Point { x: x, .. } => println!("x is {}", x),
```{rust}
# #![allow(non_shorthand_field_patterns)]
struct Point {
- x: int,
- y: int,
+ x: i32,
+ y: i32,
}
-let origin = Point { x: 0i, y: 0i };
+let origin = Point { x: 0, y: 0 };
match origin {
Point { y: y, .. } => println!("y is {}", y),
Let's make a closure:
```{rust}
-let add_one = |x| { 1i + x };
+let add_one = |x| { 1 + x };
-println!("The sum of 5 plus 1 is {}.", add_one(5i));
+println!("The sum of 5 plus 1 is {}.", add_one(5));
```
We create a closure using the `|...| { ... }` syntax, and then we create a
Let's compare syntax. The two are pretty close:
```{rust}
-let add_one = |x: int| -> int { 1i + x };
-fn add_one (x: int) -> int { 1i + x }
+let add_one = |x: i32| -> i32 { 1 + x };
+fn add_one (x: i32) -> i32 { 1 + x }
```
As you may have noticed, closures infer their argument and return types, so you
```{rust}
fn main() {
- let x = 5i;
+ let x = 5;
let printer = || { println!("x is: {}", x); };
```{rust,ignore}
fn main() {
- let mut x = 5i;
+ let mut x = 5;
let printer = || { println!("x is: {}", x); };
- x = 6i; // error: cannot assign to `x` because it is borrowed
+ x = 6; // error: cannot assign to `x` because it is borrowed
}
```
Closures are most useful as an argument to another function. Here's an example:
```{rust}
-fn twice(x: int, f: |int| -> int) -> int {
+fn twice(x: i32, f: |i32| -> i32) -> i32 {
f(x) + f(x)
}
fn main() {
- let square = |x: int| { x * x };
+ let square = |x: i32| { x * x };
- twice(5i, square); // evaluates to 50
+ twice(5, square); // evaluates to 50
}
```
Let's break the example down, starting with `main`:
```{rust}
-let square = |x: int| { x * x };
+let square = |x: i32| { x * x };
```
We've seen this before. We make a closure that takes an integer, and returns
its square.
```{rust}
-# fn twice(x: int, f: |int| -> int) -> int { f(x) + f(x) }
-# let square = |x: int| { x * x };
-twice(5i, square); // evaluates to 50
+# fn twice(x: i32, f: |i32| -> i32) -> i32 { f(x) + f(x) }
+# let square = |x: i32| { x * x };
+twice(5, square); // evaluates to 50
```
This line is more interesting. Here, we call our function, `twice`, and we pass
it two arguments: an integer, `5`, and our closure, `square`. This is just like
passing any other two variable bindings to a function, but if you've never
worked with closures before, it can seem a little complex. Just think: "I'm
-passing two variables: one is an int, and one is a function."
+passing two variables: one is an i32, and one is a function."
Next, let's look at how `twice` is defined:
```{rust,ignore}
-fn twice(x: int, f: |int| -> int) -> int {
+fn twice(x: i32, f: |i32| -> i32) -> i32 {
```
`twice` takes two arguments, `x` and `f`. That's why we called it with two
-arguments. `x` is an `int`, we've done that a ton of times. `f` is a function,
-though, and that function takes an `int` and returns an `int`. Notice
-how the `|int| -> int` syntax looks a lot like our definition of `square`
+arguments. `x` is an `i32`, we've done that a ton of times. `f` is a function,
+though, and that function takes an `i32` and returns an `i32`. Notice
+how the `|i32| -> i32` syntax looks a lot like our definition of `square`
above, if we added the return type in:
```{rust}
-let square = |x: int| -> int { x * x };
-// |int| -> int
+let square = |x: i32| -> i32 { x * x };
+// |i32| -> i32
```
-This function takes an `int` and returns an `int`.
+This function takes an `i32` and returns an `i32`.
This is the most complicated function signature we've seen yet! Give it a read
a few times until you can see how it works. It takes a teeny bit of practice, and
then it's easy.
-Finally, `twice` returns an `int` as well.
+Finally, `twice` returns an `i32` as well.
Okay, let's look at the body of `twice`:
```{rust}
-fn twice(x: int, f: |int| -> int) -> int {
+fn twice(x: i32, f: |i32| -> i32) -> i32 {
f(x) + f(x)
}
```
This example is the same as the previous one:
```{rust}
-fn twice(x: int, f: |int| -> int) -> int {
+fn twice(x: i32, f: |i32| -> i32) -> i32 {
f(x) + f(x)
}
fn main() {
- twice(5i, |x: int| { x * x }); // evaluates to 50
+ twice(5, |x: i32| { x * x }); // evaluates to 50
}
```
way of writing the previous example:
```{rust}
-fn twice(x: int, f: |int| -> int) -> int {
+fn twice(x: i32, f: |i32| -> i32) -> i32 {
f(x) + f(x)
}
-fn square(x: int) -> int { x * x }
+fn square(x: i32) -> i32 { x * x }
fn main() {
- twice(5i, square); // evaluates to 50
+ twice(5, square); // evaluates to 50
}
```
Remember Rust's `for` loop? Here's an example:
```{rust}
-for x in range(0i, 10i) {
+for x in range(0, 10) {
println!("{}", x);
}
```
Like this:
```{rust}
-let mut range = range(0i, 10i);
+let mut range = range(0, 10);
loop {
match range.next() {
We make a mutable binding to the return value of `range`, which is our iterator.
We then `loop`, with an inner `match`. This `match` is used on the result of
`range.next()`, which gives us a reference to the next value of the iterator.
-`next` returns an `Option<int>`, in this case, which will be `Some(int)` when
-we have a value and `None` once we run out. If we get `Some(int)`, we print it
+`next` returns an `Option<i32>`, in this case, which will be `Some(i32)` when
+we have a value and `None` once we run out. If we get `Some(i32)`, we print it
out, and if we get `None`, we `break` out of the loop.
This code sample is basically the same as our `for` loop version. The `for`
a vector, you may be tempted to write this:
```{rust}
-let nums = vec![1i, 2i, 3i];
+let nums = vec![1, 2, 3];
for i in range(0u, nums.len()) {
println!("{}", nums[i]);
of the vector in turn. So write this:
```{rust}
-let nums = vec![1i, 2i, 3i];
+let nums = vec![1, 2, 3];
for num in nums.iter() {
println!("{}", num);
know that we're safe.
There's another detail here that's not 100% clear because of how `println!`
-works. `num` is actually of type `&int`. That is, it's a reference to an `int`,
-not an `int` itself. `println!` handles the dereferencing for us, so we don't
+works. `num` is actually of type `&i32`. That is, it's a reference to an `i32`,
+not an `i32` itself. `println!` handles the dereferencing for us, so we don't
see it. This code works fine too:
```{rust}
-let nums = vec![1i, 2i, 3i];
+let nums = vec![1, 2, 3];
for num in nums.iter() {
println!("{}", *num);
but it shows the intention:
```{rust,ignore}
-let one_to_one_hundred = range(1i, 101i).collect();
+let one_to_one_hundred = range(1, 101).collect();
```
As you can see, we call `collect()` on our iterator. `collect()` takes
Here's the version that does compile:
```{rust}
-let one_to_one_hundred = range(1i, 101i).collect::<Vec<int>>();
+let one_to_one_hundred = range(1, 101).collect::<Vec<i32>>();
```
If you remember, the `::<>` syntax allows us to give a type hint,
is one:
```{rust}
-let greater_than_forty_two = range(0i, 100i)
+let greater_than_forty_two = range(0, 100)
.find(|x| *x > 42);
match greater_than_forty_two {
Another important consumer is `fold`. Here's what it looks like:
```{rust}
-let sum = range(1i, 4i)
- .fold(0i, |sum, x| sum + x);
+let sum = range(1, 4)
+ .fold(0, |sum, x| sum + x);
```
`fold()` is a consumer that looks like this:
| base | accumulator | element | closure result |
|------|-------------|---------|----------------|
-| 0i | 0i | 1i | 1i |
-| 0i | 1i | 2i | 3i |
-| 0i | 3i | 3i | 6i |
+| 0 | 0 | 1 | 1 |
+| 0 | 1 | 2 | 3 |
+| 0 | 3 | 3 | 6 |
We called `fold()` with these arguments:
```{rust}
-# range(1i, 4i)
-.fold(0i, |sum, x| sum + x);
+# range(1, 4)
+.fold(0, |sum, x| sum + x);
```
-So, `0i` is our base, `sum` is our accumulator, and `x` is our element. On the
-first iteration, we set `sum` to `0i`, and `x` is the first element of `nums`,
-`1i`. We then add `sum` and `x`, which gives us `0i + 1i = 1i`. On the second
+So, `0` is our base, `sum` is our accumulator, and `x` is our element. On the
+first iteration, we set `sum` to `0`, and `x` is the first element of `nums`,
+`1`. We then add `sum` and `x`, which gives us `0 + 1 = 1`. On the second
iteration, that value becomes our accumulator, `sum`, and the element is
-the second element of the array, `2i`. `1i + 2i = 3i`, and so that becomes
+the second element of the array, `2`. `1 + 2 = 3`, and so that becomes
the value of the accumulator for the last iteration. On that iteration,
-`x` is the last element, `3i`, and `3i + 3i = 6i`, which is our final
+`x` is the last element, `3`, and `3 + 3 = 6`, which is our final
result for our sum. `1 + 2 + 3 = 6`, and that's the result we got.
Whew. `fold` can be a bit strange the first few times you see it, but once it
`1-100`, and just creates a value that represents the sequence:
```{rust}
-let nums = range(1i, 100i);
+let nums = range(1, 100);
```
Since we didn't do anything with the range, it didn't generate the sequence.
Let's add the consumer:
```{rust}
-let nums = range(1i, 100i).collect::<Vec<int>>();
+let nums = range(1, 100).collect::<Vec<i32>>();
```
Now, `collect()` will require that `range()` give it some numbers, and so
that gives you each element in turn:
```{rust}
-let nums = [1i, 2i, 3i];
+let nums = [1, 2, 3];
for num in nums.iter() {
println!("{}", num);
advanced iterators, including ones that are infinite. Like `count`:
```{rust}
-std::iter::count(1i, 5i);
+std::iter::count(1, 5);
```
This iterator counts up from one, adding five each time. It will give
you a new integer every time, forever (well, technically, until it reaches the
-maximum number representable by an `int`). But since iterators are lazy,
+maximum number representable by an `i32`). But since iterators are lazy,
that's okay! You probably don't want to use `collect()` on it, though...
That's enough about iterators. Iterator adapters are the last concept
a new iterator. The simplest one is called `map`:
```{rust,ignore}
-range(1i, 100i).map(|x| x + 1i);
+range(1, 100).map(|x| x + 1);
```
`map` is called upon another iterator, and produces a new iterator where each
```text
warning: unused result which must be used: iterator adaptors are lazy and
do nothing unless consumed, #[warn(unused_must_use)] on by default
- range(1i, 100i).map(|x| x + 1i);
+ range(1, 100).map(|x| x + 1);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
doesn't print any numbers:
```{rust,ignore}
-range(1i, 100i).map(|x| println!("{}", x));
+range(1, 100).map(|x| println!("{}", x));
```
If you are trying to execute a closure on an iterator for its side effects,
iterator from before, `count()`:
```{rust}
-for i in std::iter::count(1i, 5i).take(5) {
+for i in std::iter::count(1, 5).take(5) {
println!("{}", i);
}
```
only the elements that that closure returns `true` for:
```{rust}
-for i in range(1i, 100i).filter(|&x| x % 2 == 0) {
+for i in range(1, 100).filter(|&x| x % 2 == 0) {
println!("{}", i);
}
```
a few times, and then consume the result. Check it out:
```{rust}
-range(1i, 1000i)
+range(1, 1000)
.filter(|&x| x % 2 == 0)
.filter(|&x| x % 3 == 0)
.take(5)
- .collect::<Vec<int>>();
+ .collect::<Vec<i32>>();
```
This will give you a vector containing `6`, `12`, `18`, `24`, and `30`.
```{rust}
enum OptionalInt {
- Value(int),
+ Value(i32),
Missing,
}
```
generic data type. `T` is called a **type parameter**. When we create instances
of `Option`, we need to provide a concrete type in place of the type
parameter. For example, if we wanted something like our `OptionalInt`, we would
-need to instantiate an `Option<int>`. Inside the declaration of our enum,
+need to instantiate an `Option<i32>`. Inside the declaration of our enum,
wherever we see a `T`, we replace it with the type specified (or inferred by the
the compiler).
```{rust}
-let x: Option<int> = Some(5i);
+let x: Option<i32> = Some(5);
```
-In this particular `Option`, `T` has the value of `int`. On the right-hand side
-of the binding, we do make a `Some(T)`, where `T` is `5i`. Since that's an
-`int`, the two sides match, and Rust is happy. If they didn't match, we'd get an
+In this particular `Option`, `T` has the value of `i32`. On the right-hand side
+of the binding, we do make a `Some(T)`, where `T` is `5`. Since that's an
+`i32`, the two sides match, and Rust is happy. If they didn't match, we'd get an
error:
```{rust,ignore}
-let x: Option<f64> = Some(5i);
+let x: Option<f64> = Some(5);
// error: mismatched types: expected `core::option::Option<f64>`,
-// found `core::option::Option<int>` (expected f64, found int)
+// found `core::option::Option<i32>` (expected f64, found i32)
```
That doesn't mean we can't make `Option<T>`s that hold an `f64`! They just have to
match up:
```{rust}
-let x: Option<int> = Some(5i);
+let x: Option<i32> = Some(5);
let y: Option<f64> = Some(5.0f64);
```
have passed in the correct types. If we pass in an incorrect type:
```{rust,ignore}
-print_area(5i);
+print_area(5);
```
We get a compile-time error:
```text
-error: failed to find an implementation of trait main::HasArea for int
+error: failed to find an implementation of trait main::HasArea for i32
```
So far, we've only added trait implementations to structs, but you can
implement a trait for any type. So technically, we _could_ implement
-`HasArea` for `int`:
+`HasArea` for `i32`:
```{rust}
trait HasArea {
fn area(&self) -> f64;
}
-impl HasArea for int {
+impl HasArea for i32 {
fn area(&self) -> f64 {
println!("this is silly");
}
}
-5i.area();
+5.area();
```
It is considered poor style to implement methods on such primitive types, even
```
Requiring us to `use` traits whose methods we want means that even if someone
-does something bad like add methods to `int`, it won't affect us, unless you
+does something bad like add methods to `i32`, it won't affect us, unless you
`use` that trait.
The second condition allows us to `impl` built-in `trait`s for types we define,
from mixing and matching third party or built-in `impl`s with third party or
built-in types.
-We could `impl` the `HasArea` trait for `int`, because `HasArea` is in our
+We could `impl` the `HasArea` trait for `i32`, because `HasArea` is in our
crate. But if we tried to implement `Float`, a standard library `trait`, for
-`int`, we could not, because neither the `trait` nor the `type` are in our
+`i32`, we could not, because neither the `trait` nor the `type` are in our
crate.
## Monomorphization
parent thread after the child thread is spawned:
```{rust,ignore}
-let mut x = vec![1i, 2i, 3i];
+let mut x = vec![1, 2, 3];
spawn(move || {
println!("The value of x[0] is: {}", x[0]);
let mut delayed_value = Future::spawn(move || {
// just return anything for examples' sake
- 12345i
+ 12345
});
println!("value = {}", delayed_value.get());
```
is write code that generates more code. So when we call `println!` like this:
```{rust}
-let x = 5i;
+let x = 5;
println!("x is: {}", x);
```
```{rust}
fn main() {
- let x = 5i;
+ let x = 5;
println!("x is: {}", x);
}
```
#[prelude_import]
use std::prelude::*;
fn main() {
- let x = 5i;
+ let x = 5;
match (&x,) {
(__arg0,) => {
#[inline]
}
```
-Whew! This isn't too terrible. You can see that we still `let x = 5i`,
+Whew! This isn't too terrible. You can see that we still `let x = 5`,
but then things get a little bit hairy. Three more bindings get set: a
static format string, an argument vector, and the arguments. We then
invoke the `println_args` function with the generated arguments.
* [Strings](guide-strings.html)
* [Pointers](guide-pointers.html)
* [Crates and modules](guide-crates.html)
-* [Threads and Communication](guide-threads.html)
+* [Threads and Communication](guide-tasks.html)
* [Error Handling](guide-error-handling.html)
* [Foreign Function Interface](guide-ffi.html)
* [Writing Unsafe and Low-Level Code](guide-unsafe.html)
data are being stored, or single-address and mutability properties are required.
```
-use std::sync::atomic;
+use std::sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};;
// Note that ATOMIC_UINT_INIT is a *const*, but it may be used to initialize a
// static. This static can be modified, so it is not placed in read-only memory.
-static COUNTER: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT;
+static COUNTER: AtomicUint = ATOMIC_UINT_INIT;
// This table is a candidate to be placed in read-only memory.
static TABLE: &'static [uint] = &[1, 2, 3, /* ... */];
for slot in TABLE.iter() {
println!("{}", slot);
}
-COUNTER.fetch_add(1, atomic::SeqCst);
+COUNTER.fetch_add(1, Ordering::SeqCst);
```
#### Mutable statics
}
create_tmp_dir() {
- local TMP_DIR=./rustup-tmp-install
+ local TMP_DIR=`pwd`/rustup-tmp-install
rm -Rf "${TMP_DIR}"
need_ok "failed to remove temporary installation directory"
probe_need CFG_TAR tar
probe_need CFG_FILE file
+probe CFG_SHA256SUM sha256sum
+probe CFG_SHASUM shasum
+
+if [ -z "$CFG_SHA256SUM" -a -z "$CFG_SHASUM" ]; then
+ err "unable to find either sha256sum or shasum"
+fi
+
+calculate_hash() {
+ if [ -n "$CFG_SHA256SUM" ]; then
+ ${CFG_SHA256SUM} $@
+ else
+ ${CFG_SHASUM} -a 256 $@
+ fi
+}
+
CFG_SRC_DIR="$(cd $(dirname $0) && pwd)/"
CFG_SELF="$0"
CFG_ARGS="$@"
flag uninstall "only uninstall from the installation prefix"
valopt prefix "" "set installation prefix"
-opt cargo 1 "install cargo with rust"
+valopt date "" "use the YYYY-MM-DD nightly instead of the current nightly"
+flag save "save the downloaded nightlies to ~/.rustup"
if [ $HELP -eq 1 ]
then
|| mktemp -d -t 'rustup-tmp-install' 2>/dev/null \
|| create_tmp_dir)
+# If we're saving nightlies and we didn't specify which one, grab todays.
+# Otherwise we'll use the latest version.
+if [ -n "${CFG_SAVE}" -a -z "${CFG_DATE}" ];
+then
+ CFG_DATE=`date "+%Y-%m-%d"`
+fi
+
RUST_URL="https://static.rust-lang.org/dist"
RUST_PACKAGE_NAME=rust-nightly
RUST_PACKAGE_NAME_AND_TRIPLE="${RUST_PACKAGE_NAME}-${HOST_TRIPLE}"
RUST_LOCAL_INSTALL_DIR="${CFG_TMP_DIR}/${RUST_PACKAGE_NAME_AND_TRIPLE}"
RUST_LOCAL_INSTALL_SCRIPT="${RUST_LOCAL_INSTALL_DIR}/install.sh"
-CARGO_URL="https://static.rust-lang.org/cargo-dist"
-CARGO_PACKAGE_NAME=cargo-nightly
-CARGO_PACKAGE_NAME_AND_TRIPLE="${CARGO_PACKAGE_NAME}-${HOST_TRIPLE}"
-CARGO_TARBALL_NAME="${CARGO_PACKAGE_NAME_AND_TRIPLE}.tar.gz"
-CARGO_LOCAL_INSTALL_DIR="${CFG_TMP_DIR}/${CARGO_PACKAGE_NAME_AND_TRIPLE}"
-CARGO_LOCAL_INSTALL_SCRIPT="${CARGO_LOCAL_INSTALL_DIR}/install.sh"
+# add a date suffix if we want a particular nighly.
+if [ -n "${CFG_DATE}" ];
+then
+ RUST_URL="${RUST_URL}/${CFG_DATE}"
+fi
+
+verify_hash() {
+ remote_sha256="$1"
+ local_file="$2"
+
+ msg "Downloading ${remote_sha256}"
+ remote_sha256=`"${CFG_CURL}" -f "${remote_sha256}"`
+ if [ "$?" -ne 0 ]; then
+ rm -Rf "${CFG_TMP_DIR}"
+ err "Failed to download ${remote_url}"
+ fi
+
+ msg "Verifying hash"
+ local_sha256=$(calculate_hash "${local_file}")
+ if [ "$?" -ne 0 ]; then
+ rm -Rf "${CFG_TMP_DIR}"
+ err "Failed to compute hash for ${local_tarball}"
+ fi
+
+ # We only need the sha, not the filenames
+ remote_sha256=`echo ${remote_sha256} | cut -f 1 -d ' '`
+ local_sha256=`echo ${local_sha256} | cut -f 1 -d ' '`
+
+ if [ "${remote_sha256}" != "${local_sha256}" ]; then
+ rm -Rf "${CFG_TMP_DIR}"
+ errmsg="invalid sha256.\n"
+ errmsg="$errmsg ${remote_sha256}\t${remote_tarball}\n"
+ errmsg="$errmsg ${local_sha256}\t${local_tarball}"
+ err "$errmsg"
+ fi
+}
-# Fetch the package.
+# Fetch the package. Optionally caches the tarballs.
download_package() {
remote_tarball="$1"
local_tarball="$2"
+ remote_sha256="${remote_tarball}.sha256"
- msg "Downloading ${remote_tarball} to ${local_tarball}"
+ # Check if we've already downloaded this file.
+ if [ -e "${local_tarball}.tmp" ]; then
+ msg "Resuming ${remote_tarball} to ${local_tarball}"
- "${CFG_CURL}" -f -o "${local_tarball}" "${remote_tarball}"
- if [ $? -ne 0 ]
- then
- rm -Rf "${CFG_TMP_DIR}"
- err "failed to download installer"
+ "${CFG_CURL}" -f -C - -o "${local_tarball}.tmp" "${remote_tarball}"
+ if [ $? -ne 0 ]
+ then
+ rm -Rf "${CFG_TMP_DIR}"
+ err "failed to download installer"
+ fi
+
+ mv "${local_tarball}.tmp" "${local_tarball}"
+ elif [ ! -e "${local_tarball}" ]; then
+ msg "Downloading ${remote_tarball} to ${local_tarball}"
+
+ "${CFG_CURL}" -f -o "${local_tarball}.tmp" "${remote_tarball}"
+ if [ $? -ne 0 ]
+ then
+ rm -Rf "${CFG_TMP_DIR}"
+ err "failed to download installer"
+ fi
+
+ mv "${local_tarball}.tmp" "${local_tarball}"
fi
+
+ verify_hash "${remote_sha256}" "${local_tarball}"
}
# Wrap all the commands needed to install a package.
install_package() {
- tarball_name="$1"
+ local_tarball="$1"
install_script="$2"
- msg "Extracting ${tarball_name}"
- (cd "${CFG_TMP_DIR}" && "${CFG_TAR}" -xzf "${tarball_name}")
+ msg "Extracting ${local_tarball}"
+ (cd "${CFG_TMP_DIR}" && "${CFG_TAR}" -xzf "${local_tarball}")
if [ $? -ne 0 ]; then
rm -Rf "${CFG_TMP_DIR}"
err "failed to unpack installer"
mkdir -p "${CFG_TMP_DIR}"
need_ok "failed to create create temporary installation directory"
- RUST_LOCAL_TARBALL="${CFG_TMP_DIR}/${RUST_TARBALL_NAME}"
- CARGO_LOCAL_TARBALL="${CFG_TMP_DIR}/${CARGO_TARBALL_NAME}"
+ # If we're saving our nightlies, put them in $HOME/.rustup.
+ if [ -n "${CFG_SAVE}" ]
+ then
+ RUST_DOWNLOAD_DIR="${HOME}/.rustup/${CFG_DATE}"
+ else
+ RUST_DOWNLOAD_DIR="${CFG_TMP_DIR}"
+ fi
+
+ mkdir -p "${RUST_DOWNLOAD_DIR}"
+ need_ok "failed to create create download directory"
+
+ RUST_LOCAL_TARBALL="${RUST_DOWNLOAD_DIR}/${RUST_TARBALL_NAME}"
download_package \
"${RUST_URL}/${RUST_TARBALL_NAME}" \
"${RUST_LOCAL_TARBALL}"
- if [ -z "${CFG_DISABLE_CARGO}" ]; then
- download_package \
- "${CARGO_URL}/${CARGO_TARBALL_NAME}" \
- "${CARGO_LOCAL_TARBALL}"
- fi
-
install_package \
- "${RUST_TARBALL_NAME}" \
+ "${RUST_LOCAL_TARBALL}" \
"${RUST_LOCAL_INSTALL_SCRIPT}"
- if [ -z "${CFG_DISABLE_CARGO}" ]; then
- install_package \
- "${CARGO_TARBALL_NAME}" \
- "${CARGO_LOCAL_INSTALL_SCRIPT}"
- fi
-
rm -Rf "${CFG_TMP_DIR}"
need_ok "couldn't rm temporary installation directory"
}
syn region rustString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=rustEscape,rustEscapeUnicode,rustEscapeError,rustStringContinuation,@Spell
syn region rustString start='b\?r\z(#*\)"' end='"\z1' contains=@Spell
-syn region rustAttribute start="#!\?\[" end="\]" contains=rustString,rustDeriving
-syn region rustDeriving start="deriving(" end=")" contained contains=rustTrait
+syn region rustAttribute start="#!\?\[" end="\]" contains=rustString,rustDerive
+syn region rustDerive start="derive(" end=")" contained contains=rustTrait
" Number literals
syn match rustDecNumber display "\<[0-9][0-9_]*\%([iu]\%(8\|16\|32\|64\)\=\)\="
hi def link rustType Type
hi def link rustTodo Todo
hi def link rustAttribute PreProc
-hi def link rustDeriving PreProc
+hi def link rustDerive PreProc
hi def link rustStorage StorageClass
hi def link rustObsoleteStorage Error
hi def link rustLifetime Special
" Other Suggestions:
" hi rustAttribute ctermfg=cyan
-" hi rustDeriving ctermfg=cyan
+" hi rustDerive ctermfg=cyan
" hi rustAssert ctermfg=yellow
" hi rustPanic ctermfg=red
" hi rustMacro ctermfg=magenta
#[phase(link, plugin)]
extern crate log;
-#[phase(plugin)] extern crate regex_macros;
-
use std::collections::HashMap;
use std::io::File;
+use regex::Regex;
use syntax::parse;
use syntax::parse::lexer;
-use rustc::session::{mod, config};
+use rustc::session::{self, config};
use syntax::ast;
use syntax::ast::Name;
}
fn parse_antlr_token(s: &str, tokens: &HashMap<String, token::Token>) -> TokenAndSpan {
- let re = regex!(
+ let re = Regex::new(
r"\[@(?P<seq>\d+),(?P<start>\d+):(?P<end>\d+)='(?P<content>.+?)',<(?P<toknum>-?\d+)>,\d+:\d+]"
- );
+ ).unwrap();
let m = re.captures(s).expect(format!("The regex didn't match {}", s).as_slice());
let start = m.name("start").unwrap_or("");
use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst};
use core::borrow::BorrowFrom;
use core::clone::Clone;
-use core::fmt::{mod, Show};
+use core::fmt::{self, Show};
use core::cmp::{Eq, Ord, PartialEq, PartialOrd, Ordering};
use core::default::Default;
use core::kinds::{Sync, Send};
use core::ops::{Drop, Deref};
use core::option::Option;
use core::option::Option::{Some, None};
-use core::ptr::{mod, PtrExt};
+use core::ptr::{self, PtrExt};
use heap::deallocate;
/// An atomically reference counted wrapper for shared state.
use std::ops::Drop;
use std::option::Option;
use std::option::Option::{Some, None};
- use std::str::Str;
use std::sync::atomic;
use std::sync::atomic::Ordering::{Acquire, SeqCst};
- use std::task;
- use std::kinds::Send;
+ use std::thread::Thread;
use std::vec::Vec;
use super::{Arc, Weak, weak_count, strong_count};
use std::sync::Mutex;
let (tx, rx) = channel();
- task::spawn(move || {
+ let _t = Thread::spawn(move || {
let arc_v: Arc<Vec<int>> = rx.recv().unwrap();
assert_eq!((*arc_v)[3], 4);
});
}
// Make sure deriving works with Arc<T>
- #[deriving(Eq, Ord, PartialEq, PartialOrd, Clone, Show, Default)]
+ #[derive(Eq, Ord, PartialEq, PartialOrd, Clone, Show, Default)]
struct Foo { inner: Arc<int> }
}
#![stable]
-use core::any::{Any, AnyRefExt};
+use core::any::Any;
use core::clone::Clone;
use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
use core::default::Default;
use core::fmt;
-use core::hash::{mod, Hash};
+use core::hash::{self, Hash};
use core::kinds::Sized;
use core::mem;
use core::option::Option;
#[cfg(test)] #[phase(plugin, link)] extern crate std;
#[cfg(test)] #[phase(plugin, link)] extern crate log;
-// The deprecated name of the boxed module
-
-#[deprecated = "use boxed instead"]
-#[cfg(not(test))]
-pub use boxed as owned;
-
// Heaps provided for low-level allocation strategies
pub mod heap;
use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
use core::default::Default;
use core::fmt;
-use core::hash::{mod, Hash};
+use core::hash::{self, Hash};
use core::kinds::marker;
use core::mem::{transmute, min_align_of, size_of, forget};
use core::nonzero::NonZero;
use core::ops::{Deref, Drop};
use core::option::Option;
use core::option::Option::{Some, None};
-use core::ptr::{mod, PtrExt};
+use core::ptr::{self, PtrExt};
use core::result::Result;
use core::result::Result::{Ok, Err};
/// # Example
///
/// ```
-/// use std::rc::{mod, Rc};
+/// use std::rc::{self, Rc};
///
/// let x = Rc::new(3u);
/// assert_eq!(rc::try_unwrap(x), Ok(3u));
/// # Example
///
/// ```
-/// use std::rc::{mod, Rc};
+/// use std::rc::{self, Rc};
///
/// let mut x = Rc::new(3u);
/// *rc::get_mut(&mut x).unwrap() = 4u;
// The way arena uses arrays is really deeply awful. The arrays are
// allocated, and have capacities reserved, but the fill for the array
// will always stay at 0.
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
struct Chunk {
data: Rc<RefCell<Vec<u8>>>,
fill: Cell<uint>,
{
// setup
let mut rng = rand::weak_rng();
- let mut keys = Vec::from_fn(n, |_| rng.gen::<uint>() % n);
+ let mut keys = range(0, n).map(|_| rng.gen::<uint>() % n)
+ .collect::<Vec<_>>();
for k in keys.iter() {
insert(map, *k);
//! use std::collections::BinaryHeap;
//! use std::uint;
//!
-//! #[deriving(Copy, Eq, PartialEq)]
+//! #[derive(Copy, Eq, PartialEq)]
//! struct State {
//! cost: uint,
//! position: uint,
use core::ptr;
use slice;
-use vec::{mod, Vec};
+use vec::{self, Vec};
/// A priority queue implemented with a binary heap.
///
/// This will be a max-heap.
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct BinaryHeap<T> {
data: Vec<T>,
iter: slice::Iter<'a, T>,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, T> Clone for Iter<'a, T> {
fn clone(&self) -> Iter<'a, T> {
Iter { iter: self.iter.clone() }
use core::hash;
use core::iter::RandomAccessIterator;
use core::iter::{Chain, Enumerate, Repeat, Skip, Take, repeat, Cloned};
-use core::iter::{mod, FromIterator};
+use core::iter::{self, FromIterator};
use core::num::Int;
use core::ops::Index;
use core::slice;
).collect()
}
- /// Deprecated: Use `iter().collect()`.
- #[deprecated = "Use `iter().collect()`"]
- pub fn to_bools(&self) -> Vec<bool> {
- self.iter().collect()
- }
-
/// Compares a `Bitv` to a slice of `bool`s.
/// Both the `Bitv` and slice must have the same length.
///
}
}
-/// Deprecated: Now a static method on Bitv.
-#[deprecated = "Now a static method on Bitv"]
-pub fn from_bytes(bytes: &[u8]) -> Bitv {
- Bitv::from_bytes(bytes)
-}
-
-/// Deprecated: Now a static method on Bitv.
-#[deprecated = "Now a static method on Bitv"]
-pub fn from_fn<F>(len: uint, f: F) -> Bitv where F: FnMut(uint) -> bool {
- Bitv::from_fn(len, f)
-}
-
#[stable]
impl Default for Bitv {
#[inline]
/// An iterator for `Bitv`.
#[stable]
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Iter<'a> {
bitv: &'a Bitv,
next_idx: uint,
/// let bv: Bitv = s.into_bitv();
/// assert!(bv[3]);
/// ```
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct BitvSet {
bitv: Bitv,
}
/// An iterator for `BitvSet`.
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct SetIter<'a> {
set: &'a BitvSet,
}
/// An iterator combining two `BitvSet` iterators.
-#[deriving(Clone)]
+#[derive(Clone)]
struct TwoBitPositions<'a> {
set: &'a BitvSet,
other: &'a BitvSet,
#[cfg(test)]
mod tests {
use prelude::*;
- use core::iter::range_step;
use core::u32;
- use std::rand;
- use std::rand::Rng;
- use test::{Bencher, black_box};
- use super::{Bitv, BitvSet, from_fn, from_bytes};
- use bitv;
+ use super::Bitv;
#[test]
fn test_to_str() {
#[test]
fn test_0_elements() {
let act = Bitv::new();
- let exp = Vec::from_elem(0u, false);
+ let exp = Vec::new();
assert!(act.eq_vec(exp.as_slice()));
assert!(act.none() && act.all());
}
assert_eq!(bitv.iter().collect::<Vec<bool>>(), bools);
- let long = Vec::from_fn(10000, |i| i % 2 == 0);
+ let long = range(0, 10000).map(|i| i % 2 == 0).collect::<Vec<_>>();
let bitv: Bitv = long.iter().map(|n| *n).collect();
assert_eq!(bitv.iter().collect::<Vec<bool>>(), long)
}
use self::Continuation::{Continue, Finished};
use self::StackOp::*;
use super::node::ForceResult::{Leaf, Internal};
-use super::node::TraversalItem::{mod, Elem, Edge};
+use super::node::TraversalItem::{self, Elem, Edge};
use super::node::{Traversal, MutTraversal, MoveTraversal};
-use super::node::{mod, Node, Found, GoDown};
+use super::node::{self, Node, Found, GoDown};
// FIXME(conventions): implement bounded iterators
/// force this degenerate behaviour to occur on every operation. While the total amount of work
/// done on each operation isn't *catastrophic*, and *is* still bounded by O(B log<sub>B</sub>n),
/// it is certainly much slower when it does.
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct BTreeMap<K, V> {
root: Node<K, V>,
for _ in mem::replace(self, BTreeMap::with_b(b)).into_iter() {};
}
- /// Deprecated: renamed to `get`.
- #[deprecated = "renamed to `get`"]
- pub fn find(&self, key: &K) -> Option<&V> {
- self.get(key)
- }
-
// Searching in a B-Tree is pretty straightforward.
//
// Start at the root. Try to find the key in the current node. If we find it, return it.
self.get(key).is_some()
}
- /// Deprecated: renamed to `get_mut`.
- #[deprecated = "renamed to `get_mut`"]
- pub fn find_mut(&mut self, key: &K) -> Option<&mut V> {
- self.get_mut(key)
- }
-
/// Returns a mutable reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the map's key type, but the ordering
}
}
- /// Deprecated: renamed to `insert`.
- #[deprecated = "renamed to `insert`"]
- pub fn swap(&mut self, key: K, value: V) -> Option<V> {
- self.insert(key, value)
- }
-
// Insertion in a B-Tree is a bit complicated.
//
// First we do the same kind of search described in `find`. But we need to maintain a stack of
// the underflow handling process on the parent. If merging merges the last two children
// of the root, then we replace the root with the merged node.
- /// Deprecated: renamed to `remove`.
- #[deprecated = "renamed to `remove`"]
- pub fn pop(&mut self, key: &K) -> Option<V> {
- self.remove(key)
- }
-
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
///
use core::mem;
use core::ops::{Deref, DerefMut};
use super::BTreeMap;
- use super::super::node::{mod, Node, Fit, Split, Internal, Leaf};
+ use super::super::node::{self, Node, Fit, Split, Internal, Leaf};
use super::super::node::handle;
use vec::Vec;
let size = 10000u;
// Forwards
- let mut map: BTreeMap<uint, uint> = Vec::from_fn(size, |i| (i, i)).into_iter().collect();
+ let mut map: BTreeMap<uint, uint> = range(0, size).map(|i| (i, i)).collect();
{
let mut iter = map.iter();
let size = 10000u;
// Forwards
- let mut map: BTreeMap<uint, uint> = Vec::from_fn(size, |i| (i, i)).into_iter().collect();
+ let mut map: BTreeMap<uint, uint> = range(0, size).map(|i| (i, i)).collect();
{
let mut iter = map.iter().rev();
/// println!("Uninitialized memory: {}", handle.into_kv());
/// }
/// ```
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Handle<NodeRef, Type, NodeType> {
node: NodeRef,
index: uint
use core::prelude::*;
use core::borrow::BorrowFrom;
-use core::cmp::Ordering::{mod, Less, Greater, Equal};
+use core::cmp::Ordering::{self, Less, Greater, Equal};
use core::default::Default;
use core::fmt::Show;
use core::fmt;
///
/// See BTreeMap's documentation for a detailed discussion of this collection's performance
/// benefits and drawbacks.
-#[deriving(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
+#[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
#[stable]
pub struct BTreeSet<T>{
map: BTreeMap<T, ()>,
use core::default::Default;
use core::fmt;
use core::hash::{Writer, Hash};
-use core::iter::{mod, FromIterator};
+use core::iter::{self, FromIterator};
use core::mem;
use core::ptr;
}
/// An iterator over mutable references to the items of a `DList`.
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct IntoIter<T> {
list: DList<T>
DList{list_head: None, list_tail: Rawlink::none(), length: 0}
}
- /// Deprecated: Not clearly useful enough; use split and append when available.
- #[deprecated = "Not clearly useful enough; use split and append when available"]
- pub fn rotate_forward(&mut self) {
- self.pop_back_node().map(|tail| {
- self.push_front_node(tail)
- });
- }
-
- /// Deprecated: Not clearly useful enough; use split and append when available.
- #[deprecated = "Not clearly useful enough; use split and append when available"]
- pub fn rotate_backward(&mut self) {
- self.pop_front_node().map(|head| {
- self.push_back_node(head)
- });
- }
-
/// Adds all elements from `other` to the end of the list.
///
/// This operation should compute in O(1) time.
}
}
- /// Deprecated: Use append and a swap instead.
- #[deprecated = "Use append and a swap instead"]
- pub fn prepend(&mut self, mut other: DList<T>) {
- mem::swap(self, &mut other);
- self.append(other);
- }
-
- /// Deprecated: Use custom methods on IterMut.
- #[deprecated = "Use custom methods on IterMut"]
- pub fn insert_when<F>(&mut self, elt: T, mut f: F) where F: FnMut(&T, &T) -> bool {
- let mut it = self.iter_mut();
- loop {
- match it.peek_next() {
- None => break,
- Some(x) => if f(x, &elt) { break }
- }
- it.next();
- }
- it.insert_next(elt);
- }
-
- /// Deprecated: Use custom methods on IterMut.
- #[deprecated = "Use custom methods on IterMut"]
- pub fn merge<F>(&mut self, mut other: DList<T>, mut f: F) where F: FnMut(&T, &T) -> bool {
- {
- let mut it = self.iter_mut();
- loop {
- let take_a = match (it.peek_next(), other.front()) {
- (_ , None) => return,
- (None, _ ) => break,
- (Some(ref mut x), Some(y)) => f(*x, y),
- };
- if take_a {
- it.next();
- } else {
- it.insert_next_node(other.pop_front_node().unwrap());
- }
- }
- }
- self.append(other);
- }
-
-
/// Provides a forward iterator.
#[inline]
#[stable]
self.pop_front_node().map(|box Node{value, ..}| value)
}
- /// Deprecated: Renamed to `push_back`.
- #[deprecated = "Renamed to `push_back`"]
- pub fn push(&mut self, elt: T) {
- self.push_back(elt)
- }
-
/// Appends an element to the back of a list
///
/// # Examples
self.push_back_node(box Node::new(elt))
}
- /// Deprecated: Renamed to `pop_back`.
- #[deprecated = "Renamed to `pop_back`"]
- pub fn pop(&mut self) -> Option<T> {
- self.pop_back()
- }
-
/// Removes the last element from a list and returns it, or `None` if
/// it is empty.
///
}
}
-impl<T: Ord> DList<T> {
- /// Deprecated: Why are you maintaining a sorted DList?
- #[deprecated = "Why are you maintaining a sorted DList?"]
- #[allow(deprecated)]
- pub fn insert_ordered(&mut self, elt: T) {
- self.insert_when(elt, |a, b| a >= b)
- }
-}
-
#[unsafe_destructor]
#[stable]
impl<T> Drop for DList<T> {
#[stable]
impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
-/// Allows mutating a `DList` while iterating.
-#[deprecated = "Trait is deprecated, use inherent methods on the iterator instead"]
-pub trait ListInsertion<A> {
- /// Inserts `elt` just after to the element most recently returned by
- /// `.next()`
- ///
- /// The inserted element does not appear in the iteration.
- fn insert_next(&mut self, elt: A);
-
- /// Provides a reference to the next element, without changing the iterator
- fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
-}
-
// private methods for IterMut
impl<'a, A> IterMut<'a, A> {
fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
use prelude::*;
use std::rand;
use std::hash;
- use std::task::spawn;
+ use std::thread::Thread;
use test::Bencher;
use test;
v.iter().map(|x| (*x).clone()).collect()
}
- #[test]
- #[allow(deprecated)]
- fn test_append() {
- {
- let mut m = DList::new();
- let mut n = DList::new();
- n.push_back(2i);
- m.append(n);
- assert_eq!(m.len(), 1);
- assert_eq!(m.pop_back(), Some(2));
- check_links(&m);
- }
- {
- let mut m = DList::new();
- let n = DList::new();
- m.push_back(2i);
- m.append(n);
- assert_eq!(m.len(), 1);
- assert_eq!(m.pop_back(), Some(2));
- check_links(&m);
- }
-
- let v = vec![1i,2,3,4,5];
- let u = vec![9i,8,1,2,3,4,5];
- let mut m = list_from(v.as_slice());
- m.append(list_from(u.as_slice()));
- check_links(&m);
- let mut sum = v;
- sum.push_all(u.as_slice());
- assert_eq!(sum.len(), m.len());
- for elt in sum.into_iter() {
- assert_eq!(m.pop_front(), Some(elt))
- }
- }
-
- #[test]
- fn test_prepend() {
- {
- let mut m = DList::new();
- let mut n = DList::new();
- n.push_back(2i);
- m.prepend(n);
- assert_eq!(m.len(), 1);
- assert_eq!(m.pop_back(), Some(2));
- check_links(&m);
- }
-
- let v = vec![1i,2,3,4,5];
- let mut u = vec![9i,8,1,2,3,4,5];
- let mut m = list_from(v.as_slice());
- m.prepend(list_from(u.as_slice()));
- check_links(&m);
- u.extend(v.iter().map(|&b| b));
- assert_eq!(u.len(), m.len());
- for elt in u.into_iter() {
- assert_eq!(m.pop_front(), Some(elt))
- }
- }
-
- #[test]
- fn test_rotate() {
- let mut n: DList<int> = DList::new();
- n.rotate_backward(); check_links(&n);
- assert_eq!(n.len(), 0);
- n.rotate_forward(); check_links(&n);
- assert_eq!(n.len(), 0);
-
- let v = vec![1i,2,3,4,5];
- let mut m = list_from(v.as_slice());
- m.rotate_backward(); check_links(&m);
- m.rotate_forward(); check_links(&m);
- assert_eq!(v.iter().collect::<Vec<&int>>(), m.iter().collect::<Vec<_>>());
- m.rotate_forward(); check_links(&m);
- m.rotate_forward(); check_links(&m);
- m.pop_front(); check_links(&m);
- m.rotate_forward(); check_links(&m);
- m.rotate_backward(); check_links(&m);
- m.push_front(9); check_links(&m);
- m.rotate_forward(); check_links(&m);
- assert_eq!(vec![3i,9,5,1,2], m.into_iter().collect::<Vec<_>>());
- }
-
#[test]
fn test_iterator() {
let m = generate_test();
assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
}
- #[test]
- fn test_merge() {
- let mut m = list_from(&[0i, 1, 3, 5, 6, 7, 2]);
- let n = list_from(&[-1i, 0, 0, 7, 7, 9]);
- let len = m.len() + n.len();
- m.merge(n, |a, b| a <= b);
- assert_eq!(m.len(), len);
- check_links(&m);
- let res = m.into_iter().collect::<Vec<int>>();
- assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
- }
-
- #[test]
- fn test_insert_ordered() {
- let mut n = DList::new();
- n.insert_ordered(1i);
- assert_eq!(n.len(), 1);
- assert_eq!(n.pop_front(), Some(1));
-
- let mut m = DList::new();
- m.push_back(2i);
- m.push_back(4);
- m.insert_ordered(3);
- check_links(&m);
- assert_eq!(vec![2,3,4], m.into_iter().collect::<Vec<int>>());
- }
-
#[test]
fn test_mut_rev_iter() {
let mut m = generate_test();
#[test]
fn test_send() {
let n = list_from(&[1i,2,3]);
- spawn(move || {
+ Thread::spawn(move || {
check_links(&n);
let a: &[_] = &[&1,&2,&3];
assert_eq!(a, n.iter().collect::<Vec<&int>>());
- });
+ }).join().ok().unwrap();
}
#[test]
assert_eq!(i, v.len());
}
+ #[allow(deprecated)]
+ fn test_append() {
+ {
+ let mut m = DList::new();
+ let mut n = DList::new();
+ n.push_back(2i);
+ m.append(n);
+ assert_eq!(m.len(), 1);
+ assert_eq!(m.pop_back(), Some(2));
+ check_links(&m);
+ }
+ {
+ let mut m = DList::new();
+ let n = DList::new();
+ m.push_back(2i);
+ m.append(n);
+ assert_eq!(m.len(), 1);
+ assert_eq!(m.pop_back(), Some(2));
+ check_links(&m);
+ }
+
+ let v = vec![1i,2,3,4,5];
+ let u = vec![9i,8,1,2,3,4,5];
+ let mut m = list_from(v.as_slice());
+ m.append(list_from(u.as_slice()));
+ check_links(&m);
+ let mut sum = v;
+ sum.push_all(u.as_slice());
+ assert_eq!(sum.len(), m.len());
+ for elt in sum.into_iter() {
+ assert_eq!(m.pop_front(), Some(elt))
+ }
+ }
+
#[bench]
fn bench_collect_into(b: &mut test::Bencher) {
let v = &[0i; 64];
})
}
- #[bench]
- fn bench_rotate_forward(b: &mut test::Bencher) {
- let mut m: DList<int> = DList::new();
- m.push_front(0i);
- m.push_front(1);
- b.iter(|| {
- m.rotate_forward();
- })
- }
-
- #[bench]
- fn bench_rotate_backward(b: &mut test::Bencher) {
- let mut m: DList<int> = DList::new();
- m.push_front(0i);
- m.push_front(1);
- b.iter(|| {
- m.rotate_backward();
- })
- }
-
#[bench]
fn bench_iter(b: &mut test::Bencher) {
let v = &[0i; 128];
// FIXME(contentions): implement union family of methods? (general design may be wrong here)
-#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A specialized set implementation to use enum types.
pub struct EnumSet<E> {
// We must maintain the invariant that no bits are set
}
impl<E:CLike> EnumSet<E> {
- /// Deprecated: Renamed to `new`.
- #[deprecated = "Renamed to `new`"]
- pub fn empty() -> EnumSet<E> {
- EnumSet::new()
- }
-
/// Returns an empty `EnumSet`.
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn new() -> EnumSet<E> {
self.bits = 0;
}
- /// Returns `true` if the `EnumSet` contains any enum of the given `EnumSet`.
- /// Deprecated: Use `is_disjoint`.
- #[deprecated = "Use `is_disjoint`"]
- pub fn intersects(&self, e: EnumSet<E>) -> bool {
- !self.is_disjoint(&e)
- }
-
/// Returns `false` if the `EnumSet` contains any enum of the given `EnumSet`.
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn is_disjoint(&self, other: &EnumSet<E>) -> bool {
EnumSet {bits: self.bits & e.bits}
}
- /// Deprecated: Use `insert`.
- #[deprecated = "Use `insert`"]
- pub fn add(&mut self, e: E) {
- self.insert(e);
- }
-
/// Adds an enum to the `EnumSet`, and returns `true` if it wasn't there before
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn insert(&mut self, e: E) -> bool {
result
}
- /// Deprecated: use `contains`.
- #[deprecated = "use `contains"]
- pub fn contains_elem(&self, e: E) -> bool {
- self.contains(&e)
- }
-
/// Returns `true` if an `EnumSet` contains a given enum.
#[unstable = "matches collection reform specification, waiting for dust to settle"]
pub fn contains(&self, e: &E) -> bool {
bits: uint,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<E> Clone for Iter<E> {
fn clone(&self) -> Iter<E> {
Iter {
use super::{EnumSet, CLike};
- #[deriving(Copy, PartialEq, Show)]
+ #[derive(Copy, PartialEq, Show)]
#[repr(uint)]
enum Foo {
A, B, C
#[should_fail]
fn test_overflow() {
#[allow(dead_code)]
- #[deriving(Copy)]
+ #[derive(Copy)]
#[repr(uint)]
enum Bar {
V00, V01, V02, V03, V04, V05, V06, V07, V08, V09,
pub mod vec_map;
pub mod bitv {
- pub use bit::{Bitv, Iter, from_fn, from_bytes};
+ pub use bit::{Bitv, Iter};
}
pub mod bitv_set {
pub use core::borrow::IntoCow;
pub use core::char::Char;
pub use core::clone::Clone;
- pub use core::cmp::{PartialEq, Eq, Equiv, PartialOrd, Ord};
+ pub use core::cmp::{PartialEq, Eq, PartialOrd, Ord};
pub use core::cmp::Ordering::{Less, Equal, Greater};
pub use core::iter::range;
pub use core::iter::{FromIterator, Extend, IteratorExt};
// in core and collections (may differ).
pub use slice::{AsSlice, SliceExt};
- pub use str::{from_str, Str, StrExt};
+ pub use str::{Str, StrExt};
// from other crates.
pub use alloc::boxed::Box;
// from collections.
pub use slice::SliceConcatExt;
- pub use str::IntoMaybeOwned;
pub use string::{String, ToString};
pub use vec::Vec;
}
use core::cmp::Ordering;
use core::default::Default;
use core::fmt;
-use core::iter::{mod, FromIterator, RandomAccessIterator};
+use core::iter::{self, FromIterator, RandomAccessIterator};
use core::kinds::marker;
use core::mem;
use core::num::{Int, UnsignedInt};
unsafe { self.buffer_write(tail, t); }
}
- /// Deprecated: Renamed to `push_back`.
- #[deprecated = "Renamed to `push_back`"]
- pub fn push(&mut self, t: T) {
- self.push_back(t)
- }
-
/// Appends an element to the back of a buffer
///
/// # Examples
unsafe { self.buffer_write(head, t) }
}
- /// Deprecated: Renamed to `pop_back`.
- #[deprecated = "Renamed to `pop_back`"]
- pub fn pop(&mut self) -> Option<T> {
- self.pop_back()
- }
-
/// Removes the last element from a buffer and returns it, or `None` if
/// it is empty.
///
head: uint
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, T> Clone for Iter<'a, T> {
fn clone(&self) -> Iter<'a, T> {
Iter {
use self::Taggy::*;
use self::Taggypar::*;
use prelude::*;
- use core::cmp;
use core::iter;
use std::fmt::Show;
use std::hash;
})
}
- #[deriving(Clone, PartialEq, Show)]
+ #[derive(Clone, PartialEq, Show)]
enum Taggy {
One(int),
Two(int, int),
Three(int, int, int),
}
- #[deriving(Clone, PartialEq, Show)]
+ #[derive(Clone, PartialEq, Show)]
enum Taggypar<T> {
Onepar(int),
Twopar(int, int),
Threepar(int, int, int),
}
- #[deriving(Clone, PartialEq, Show)]
+ #[derive(Clone, PartialEq, Show)]
struct RecCy {
x: int,
y: int,
use alloc::boxed::Box;
use core::borrow::{BorrowFrom, BorrowFromMut, ToOwned};
use core::clone::Clone;
-use core::cmp::Ordering::{mod, Greater, Less};
-use core::cmp::{mod, Ord, PartialEq};
-use core::iter::{Iterator, IteratorExt, IteratorCloneExt};
+use core::cmp::Ordering::{self, Greater, Less};
+use core::cmp::{self, Ord, PartialEq};
+use core::iter::{Iterator, IteratorExt};
use core::iter::{range, range_step, MultiplicativeIterator};
use core::kinds::Sized;
use core::mem::size_of;
use core::mem;
use core::ops::{FnMut, SliceMut};
-use core::option::Option::{mod, Some, None};
+use core::option::Option::{self, Some, None};
use core::ptr::PtrExt;
use core::ptr;
use core::result::Result;
pub use core::slice::{bytes, mut_ref_slice, ref_slice};
pub use core::slice::{from_raw_buf, from_raw_mut_buf};
-#[deprecated = "use Iter instead"]
-pub type Items<'a, T:'a> = Iter<'a, T>;
-
-#[deprecated = "use IterMut instead"]
-pub type MutItems<'a, T:'a> = IterMut<'a, T>;
-
////////////////////////////////////////////////////////////////////////////////
// Basic slice extension methods
////////////////////////////////////////////////////////////////////////////////
#[stable]
fn first(&self) -> Option<&Self::Item>;
- /// Deprecated: renamed to `first`.
- #[deprecated = "renamed to `first`"]
- fn head(&self) -> Option<&Self::Item> { self.first() }
-
/// Returns all but the first element of a slice.
#[experimental = "likely to be renamed"]
fn tail(&self) -> &[Self::Item];
#[stable]
unsafe fn get_unchecked(&self, index: uint) -> &Self::Item;
- /// Deprecated: renamed to `get_unchecked`.
- #[deprecated = "renamed to get_unchecked"]
- unsafe fn unsafe_get(&self, index: uint) -> &Self::Item {
- self.get_unchecked(index)
- }
-
/// Returns an unsafe pointer to the slice's buffer
///
/// The caller must ensure that the slice outlives the pointer this
#[stable]
fn first_mut(&mut self) -> Option<&mut Self::Item>;
- /// Depreated: renamed to `first_mut`.
- #[deprecated = "renamed to first_mut"]
- fn head_mut(&mut self) -> Option<&mut Self::Item> {
- self.first_mut()
- }
-
/// Returns all but the first element of a mutable slice
#[experimental = "likely to be renamed or removed"]
fn tail_mut(&mut self) -> &mut [Self::Item];
#[stable]
unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut Self::Item;
- /// Deprecated: renamed to `get_unchecked_mut`.
- #[deprecated = "renamed to get_unchecked_mut"]
- unsafe fn unchecked_mut(&mut self, index: uint) -> &mut Self::Item {
- self.get_unchecked_mut(index)
- }
-
/// Return an unsafe mutable pointer to the slice's buffer.
///
/// The caller must ensure that the slice outlives the pointer this
#[stable]
fn to_vec(&self) -> Vec<Self::Item> where Self::Item: Clone;
- /// Deprecated: use `iter().cloned().partition(f)` instead.
- #[deprecated = "use iter().cloned().partition(f) instead"]
- fn partitioned<F>(&self, f: F) -> (Vec<Self::Item>, Vec<Self::Item>) where
- Self::Item: Clone,
- F: FnMut(&Self::Item) -> bool;
-
/// Creates an iterator that yields every possible permutation of the
/// vector in succession.
///
vector
}
-
- #[inline]
- fn partitioned<F>(&self, f: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool, T: Clone {
- self.iter().cloned().partition(f)
- }
-
/// Returns an iterator over all permutations of a vector.
fn permutations(&self) -> Permutations<T> where T: Clone {
Permutations{
#[stable]
fn concat(&self) -> U;
- #[deprecated = "renamed to concat"]
- fn concat_vec(&self) -> U {
- self.concat()
- }
-
/// Flattens a slice of `T` into a single value `U`, placing a
/// given seperator between each.
#[stable]
fn connect(&self, sep: &T) -> U;
-
- #[deprecated = "renamed to connect"]
- fn connect_vec(&self, sep: &T) -> U {
- self.connect(sep)
- }
}
impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] {
/// The last generated swap is always (0, 1), and it returns the
/// sequence to its initial order.
#[experimental]
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct ElementSwaps {
sdir: Vec<SizeDirection>,
/// If `true`, emit the last swap that returns the sequence to initial
// Iterators
////////////////////////////////////////////////////////////////////////////////
-#[deriving(Copy, Clone)]
+#[derive(Copy, Clone)]
enum Direction { Pos, Neg }
/// An `Index` and `Direction` together.
-#[deriving(Copy, Clone)]
+#[derive(Copy, Clone)]
struct SizeDirection {
size: uint,
dir: Direction,
}
}
-/// Deprecated, unsafe operations
-#[deprecated]
-pub mod raw {
- pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
- pub use core::slice::raw::{shift_ptr, pop_ptr};
-}
-
#[cfg(test)]
mod tests {
- use std::boxed::Box;
use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal};
use prelude::{SliceExt, Iterator, IteratorExt};
use prelude::AsSlice;
use prelude::{RandomAccessIterator, Ord, SliceConcatExt};
- use core::cell::Cell;
use core::default::Default;
use core::mem;
use std::rand::{Rng, thread_rng};
#[test]
fn test_from_fn() {
// Test on-stack from_fn.
- let mut v = Vec::from_fn(3u, square);
+ let mut v = range(0, 3).map(square).collect::<Vec<_>>();
{
let v = v.as_slice();
assert_eq!(v.len(), 3u);
}
// Test on-heap from_fn.
- v = Vec::from_fn(5u, square);
+ v = range(0, 5).map(square).collect::<Vec<_>>();
{
let v = v.as_slice();
assert_eq!(v.len(), 5u);
#[test]
fn test_from_elem() {
// Test on-stack from_elem.
- let mut v = Vec::from_elem(2u, 10u);
+ let mut v = vec![10u, 10u];
{
let v = v.as_slice();
assert_eq!(v.len(), 2u);
}
// Test on-heap from_elem.
- v = Vec::from_elem(6u, 20u);
+ v = vec![20u, 20u, 20u, 20u, 20u, 20u];
{
let v = v.as_slice();
assert_eq!(v[0], 20u);
}
#[test]
- fn test_head() {
+ fn test_first() {
let mut a = vec![];
- assert_eq!(a.as_slice().head(), None);
+ assert_eq!(a.as_slice().first(), None);
a = vec![11i];
- assert_eq!(a.as_slice().head().unwrap(), &11);
+ assert_eq!(a.as_slice().first().unwrap(), &11);
a = vec![11i, 12];
- assert_eq!(a.as_slice().head().unwrap(), &11);
+ assert_eq!(a.as_slice().first().unwrap(), &11);
}
#[test]
- fn test_head_mut() {
+ fn test_first_mut() {
let mut a = vec![];
- assert_eq!(a.head_mut(), None);
+ assert_eq!(a.first_mut(), None);
a = vec![11i];
- assert_eq!(*a.head_mut().unwrap(), 11);
+ assert_eq!(*a.first_mut().unwrap(), 11);
a = vec![11i, 12];
- assert_eq!(*a.head_mut().unwrap(), 11);
+ assert_eq!(*a.first_mut().unwrap(), 11);
}
#[test]
assert_eq!(v.as_slice()[1], 2);
}
- #[test]
- fn test_grow() {
- // Test on-stack grow().
- let mut v = vec![];
- v.grow(2u, 1i);
- {
- let v = v.as_slice();
- assert_eq!(v.len(), 2u);
- assert_eq!(v[0], 1);
- assert_eq!(v[1], 1);
- }
-
- // Test on-heap grow().
- v.grow(3u, 2i);
- {
- let v = v.as_slice();
- assert_eq!(v.len(), 5u);
- assert_eq!(v[0], 1);
- assert_eq!(v[1], 1);
- assert_eq!(v[2], 2);
- assert_eq!(v[3], 2);
- assert_eq!(v[4], 2);
- }
- }
-
- #[test]
- fn test_grow_fn() {
- let mut v = vec![];
- v.grow_fn(3u, square);
- let v = v.as_slice();
- assert_eq!(v.len(), 3u);
- assert_eq!(v[0], 0u);
- assert_eq!(v[1], 1u);
- assert_eq!(v[2], 4u);
- }
-
#[test]
fn test_truncate() {
let mut v = vec![box 6i,box 5,box 4];
}
}
- #[test]
- fn test_partition() {
- assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
- assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
- assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
- assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
- }
-
- #[test]
- fn test_partitioned() {
- assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
- assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
- assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
- assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
- }
-
#[test]
fn test_concat() {
let v: [Vec<int>; 0] = [];
#[test]
fn test_connect() {
let v: [Vec<int>; 0] = [];
- assert_eq!(v.connect_vec(&0), vec![]);
- assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
- assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
+ assert_eq!(v.connect(&0), vec![]);
+ assert_eq!([vec![1i], vec![2i, 3]].connect(&0), vec![1, 0, 2, 3]);
+ assert_eq!([vec![1i], vec![2i], vec![3i]].connect(&0), vec![1, 0, 2, 0, 3]);
let v: [&[int]; 2] = [&[1], &[2, 3]];
- assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]);
+ assert_eq!(v.connect(&0), vec![1, 0, 2, 3]);
let v: [&[int]; 3] = [&[1], &[2], &[3]];
- assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]);
+ assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]);
}
#[test]
assert_eq!(v[1], 3);
}
-
- #[test]
- #[should_fail]
- fn test_from_fn_fail() {
- Vec::from_fn(100, |v| {
- if v == 50 { panic!() }
- box 0i
- });
- }
-
- #[test]
- #[should_fail]
- fn test_from_elem_fail() {
-
- struct S {
- f: Cell<int>,
- boxes: (Box<int>, Rc<int>)
- }
-
- impl Clone for S {
- fn clone(&self) -> S {
- self.f.set(self.f.get() + 1);
- if self.f.get() == 10 { panic!() }
- S {
- f: self.f.clone(),
- boxes: self.boxes.clone(),
- }
- }
- }
-
- let s = S {
- f: Cell::new(0),
- boxes: (box 0, Rc::new(0)),
- };
- let _ = Vec::from_elem(100, s);
- }
-
- #[test]
- #[should_fail]
- fn test_grow_fn_fail() {
- let mut v = vec![];
- v.grow_fn(100, |i| {
- if i == 50 {
- panic!()
- }
- (box 0i, Rc::new(0i))
- })
- }
-
#[test]
#[should_fail]
fn test_permute_fail() {
assert!(values == [2, 3, 5, 6, 7]);
}
- #[deriving(Clone, PartialEq)]
+ #[derive(Clone, PartialEq)]
struct Foo;
#[test]
use prelude::*;
use core::mem;
use core::ptr;
+ use core::iter::repeat;
use std::rand::{weak_rng, Rng};
use test::{Bencher, black_box};
fn iterator(b: &mut Bencher) {
// peculiar numbers to stop LLVM from optimising the summation
// out.
- let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
+ let v = range(0u, 100).map(|i| i ^ (i << 1) ^ (i >> 1)).collect::<Vec<_>>();
b.iter(|| {
let mut sum = 0;
#[bench]
fn mut_iterator(b: &mut Bencher) {
- let mut v = Vec::from_elem(100, 0i);
+ let mut v = repeat(0i).take(100).collect::<Vec<_>>();
b.iter(|| {
let mut i = 0i;
#[bench]
fn concat(b: &mut Bencher) {
let xss: Vec<Vec<uint>> =
- Vec::from_fn(100, |i| range(0u, i).collect());
+ range(0, 100u).map(|i| range(0, i).collect()).collect();
b.iter(|| {
xss.as_slice().concat();
});
#[bench]
fn connect(b: &mut Bencher) {
let xss: Vec<Vec<uint>> =
- Vec::from_fn(100, |i| range(0u, i).collect());
+ range(0, 100u).map(|i| range(0, i).collect()).collect();
b.iter(|| {
- xss.as_slice().connect_vec(&0)
+ xss.as_slice().connect(&0)
});
}
#[bench]
fn starts_with_same_vector(b: &mut Bencher) {
- let vec: Vec<uint> = Vec::from_fn(100, |i| i);
+ let vec: Vec<uint> = range(0, 100).collect();
b.iter(|| {
vec.as_slice().starts_with(vec.as_slice())
})
#[bench]
fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
- let vec: Vec<uint> = Vec::from_fn(100, |i| i);
- let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
+ let vec: Vec<uint> = range(0, 100).collect();
+ let mut match_vec: Vec<uint> = range(0, 99).collect();
match_vec.push(0);
b.iter(|| {
vec.as_slice().starts_with(match_vec.as_slice())
#[bench]
fn ends_with_same_vector(b: &mut Bencher) {
- let vec: Vec<uint> = Vec::from_fn(100, |i| i);
+ let vec: Vec<uint> = range(0, 100).collect();
b.iter(|| {
vec.as_slice().ends_with(vec.as_slice())
})
#[bench]
fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
- let vec: Vec<uint> = Vec::from_fn(100, |i| i);
- let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
+ let vec: Vec<uint> = range(0, 100).collect();
+ let mut match_vec: Vec<uint> = range(0, 100).collect();
match_vec.as_mut_slice()[0] = 200;
b.iter(|| {
vec.as_slice().starts_with(match_vec.as_slice())
#[bench]
fn contains_last_element(b: &mut Bencher) {
- let vec: Vec<uint> = Vec::from_fn(100, |i| i);
+ let vec: Vec<uint> = range(0, 100).collect();
b.iter(|| {
vec.contains(&99u)
})
#[bench]
fn zero_1kb_from_elem(b: &mut Bencher) {
b.iter(|| {
- Vec::from_elem(1024, 0u8)
+ repeat(0u8).take(1024).collect::<Vec<_>>()
});
}
fn random_inserts(b: &mut Bencher) {
let mut rng = weak_rng();
b.iter(|| {
- let mut v = Vec::from_elem(30, (0u, 0u));
- for _ in range(0u, 100) {
- let l = v.len();
- v.insert(rng.gen::<uint>() % (l + 1),
- (1, 1));
- }
- })
+ let mut v = repeat((0u, 0u)).take(30).collect::<Vec<_>>();
+ for _ in range(0u, 100) {
+ let l = v.len();
+ v.insert(rng.gen::<uint>() % (l + 1),
+ (1, 1));
+ }
+ })
}
#[bench]
fn random_removes(b: &mut Bencher) {
let mut rng = weak_rng();
b.iter(|| {
- let mut v = Vec::from_elem(130, (0u, 0u));
- for _ in range(0u, 100) {
- let l = v.len();
- v.remove(rng.gen::<uint>() % l);
- }
- })
+ let mut v = repeat((0u, 0u)).take(130).collect::<Vec<_>>();
+ for _ in range(0u, 100) {
+ let l = v.len();
+ v.remove(rng.gen::<uint>() % l);
+ }
+ })
}
#[bench]
#[bench]
fn sort_sorted(b: &mut Bencher) {
- let mut v = Vec::from_fn(10000, |i| i);
+ let mut v = range(0u, 10000).collect::<Vec<_>>();
b.iter(|| {
v.sort();
});
#[bench]
fn sort_big_sorted(b: &mut Bencher) {
- let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
+ let mut v = range(0, 10000u).map(|i| (i, i, i, i)).collect::<Vec<_>>();
b.iter(|| {
v.sort();
});
#![doc(primitive = "str")]
-use self::MaybeOwned::*;
use self::RecompositionState::*;
use self::DecompositionType::*;
-use core::borrow::{BorrowFrom, Cow, ToOwned};
+use core::borrow::{BorrowFrom, ToOwned};
use core::char::Char;
use core::clone::Clone;
-use core::cmp::{Equiv, PartialEq, Eq, PartialOrd, Ord, Ordering};
-use core::cmp;
-use core::default::Default;
-use core::fmt;
-use core::hash;
use core::iter::AdditiveIterator;
-use core::iter::{mod, range, Iterator, IteratorExt};
+use core::iter::{range, Iterator, IteratorExt};
use core::kinds::Sized;
use core::ops;
-use core::option::Option::{mod, Some, None};
+use core::option::Option::{self, Some, None};
use core::slice::AsSlice;
use core::str as core_str;
use unicode::str::{UnicodeStr, Utf16Encoder};
use vec::Vec;
use slice::SliceConcatExt;
-pub use core::str::{from_utf8, CharEq, Chars, CharIndices};
-pub use core::str::{Bytes, CharSplits, is_utf8};
-pub use core::str::{CharSplitsN, Lines, LinesAny, MatchIndices, StrSplits, SplitStr};
-pub use core::str::{CharRange};
-pub use core::str::{FromStr, from_str, Utf8Error};
-pub use core::str::Str;
-pub use core::str::{from_utf8_unchecked, from_c_str};
-pub use unicode::str::{Words, Graphemes, GraphemeIndices};
+pub use core::str::{FromStr, Utf8Error, Str};
+pub use core::str::{Lines, LinesAny, MatchIndices, SplitStr, CharRange};
pub use core::str::{Split, SplitTerminator};
pub use core::str::{SplitN, RSplitN};
+pub use core::str::{from_utf8, CharEq, Chars, CharIndices, Bytes};
+pub use core::str::{from_utf8_unchecked, from_c_str};
+pub use unicode::str::{Words, Graphemes, GraphemeIndices};
/*
Section: Creating a string
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
enum DecompositionType {
Canonical,
Compatible
/// External iterator for a string's decomposition's characters.
/// Use with the `std::iter` module.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Decompositions<'a> {
kind: DecompositionType,
iter: Chars<'a>,
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
enum RecompositionState {
Composing,
Purging,
/// External iterator for a string's recomposition's characters.
/// Use with the `std::iter` module.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Recompositions<'a> {
iter: Decompositions<'a>,
state: RecompositionState,
/// External iterator for a string's UTF16 codeunits.
/// Use with the `std::iter` module.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Utf16Units<'a> {
encoder: Utf16Encoder<Chars<'a>>
}
fn size_hint(&self) -> (uint, Option<uint>) { self.encoder.size_hint() }
}
-/// Replaces all occurrences of one string with another.
-///
-/// # Arguments
-///
-/// * s - The string containing substrings to replace
-/// * from - The string to replace
-/// * to - The replacement string
-///
-/// # Return value
-///
-/// The original string with all occurrences of `from` replaced with `to`.
-///
-/// # Examples
-///
-/// ```rust
-/// # #![allow(deprecated)]
-/// use std::str;
-/// let string = "orange";
-/// let new_string = str::replace(string, "or", "str");
-/// assert_eq!(new_string.as_slice(), "strange");
-/// ```
-#[deprecated = "call the inherent method instead"]
-pub fn replace(s: &str, from: &str, to: &str) -> String {
- s.replace(from, to)
-}
-
/*
Section: Misc
*/
($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63u8) as u32)
}
-/*
-Section: MaybeOwned
-*/
-
-/// A string type that can hold either a `String` or a `&str`.
-/// This can be useful as an optimization when an allocation is sometimes
-/// needed but not always.
-#[deprecated = "use std::string::CowString"]
-pub enum MaybeOwned<'a> {
- /// A borrowed string.
- Slice(&'a str),
- /// An owned string.
- Owned(String)
-}
-
-/// A specialization of `CowString` to be sendable.
-#[deprecated = "use std::string::CowString<'static>"]
-pub type SendStr = CowString<'static>;
-
-#[deprecated = "use std::string::CowString"]
-impl<'a> MaybeOwned<'a> {
- /// Returns `true` if this `MaybeOwned` wraps an owned string.
- ///
- /// # Examples
- ///
- /// ``` ignore
- /// let string = String::from_str("orange");
- /// let maybe_owned_string = string.into_maybe_owned();
- /// assert_eq!(true, maybe_owned_string.is_owned());
- /// ```
- #[inline]
- pub fn is_owned(&self) -> bool {
- match *self {
- Slice(_) => false,
- Owned(_) => true
- }
- }
-
- /// Returns `true` if this `MaybeOwned` wraps a borrowed string.
- ///
- /// # Examples
- ///
- /// ``` ignore
- /// let string = "orange";
- /// let maybe_owned_string = string.as_slice().into_maybe_owned();
- /// assert_eq!(true, maybe_owned_string.is_slice());
- /// ```
- #[inline]
- pub fn is_slice(&self) -> bool {
- match *self {
- Slice(_) => true,
- Owned(_) => false
- }
- }
-
- /// Return the number of bytes in this string.
- #[inline]
- #[allow(deprecated)]
- pub fn len(&self) -> uint { self.as_slice().len() }
-
- /// Returns true if the string contains no bytes
- #[allow(deprecated)]
- #[inline]
- pub fn is_empty(&self) -> bool { self.len() == 0 }
-}
-
-#[deprecated = "use std::borrow::IntoCow"]
-/// Trait for moving into a `MaybeOwned`.
-pub trait IntoMaybeOwned<'a> {
- /// Moves `self` into a `MaybeOwned`.
- fn into_maybe_owned(self) -> MaybeOwned<'a>;
-}
-
-#[deprecated = "use std::borrow::IntoCow"]
-#[allow(deprecated)]
-impl<'a> IntoMaybeOwned<'a> for String {
- /// # Examples
- ///
- /// ``` ignore
- /// let owned_string = String::from_str("orange");
- /// let maybe_owned_string = owned_string.into_maybe_owned();
- /// assert_eq!(true, maybe_owned_string.is_owned());
- /// ```
- #[allow(deprecated)]
- #[inline]
- fn into_maybe_owned(self) -> MaybeOwned<'a> {
- Owned(self)
- }
-}
-
-#[deprecated = "use std::borrow::IntoCow"]
-#[allow(deprecated)]
-impl<'a> IntoMaybeOwned<'a> for &'a str {
- /// # Examples
- ///
- /// ``` ignore
- /// let string = "orange";
- /// let maybe_owned_str = string.as_slice().into_maybe_owned();
- /// assert_eq!(false, maybe_owned_str.is_owned());
- /// ```
- #[allow(deprecated)]
- #[inline]
- fn into_maybe_owned(self) -> MaybeOwned<'a> { Slice(self) }
-}
-
-#[allow(deprecated)]
-#[deprecated = "use std::borrow::IntoCow"]
-impl<'a> IntoMaybeOwned<'a> for MaybeOwned<'a> {
- /// # Examples
- ///
- /// ``` ignore
- /// let str = "orange";
- /// let maybe_owned_str = str.as_slice().into_maybe_owned();
- /// let maybe_maybe_owned_str = maybe_owned_str.into_maybe_owned();
- /// assert_eq!(false, maybe_maybe_owned_str.is_owned());
- /// ```
- #[inline]
- fn into_maybe_owned(self) -> MaybeOwned<'a> { self }
-}
-
-#[deprecated = "use std::string::CowString"]
-#[allow(deprecated)]
-impl<'a> PartialEq for MaybeOwned<'a> {
- #[inline]
- fn eq(&self, other: &MaybeOwned) -> bool {
- self.as_slice() == other.as_slice()
- }
-}
-
-#[deprecated = "use std::string::CowString"]
-impl<'a> Eq for MaybeOwned<'a> {}
-
-#[deprecated = "use std::string::CowString"]
-impl<'a> PartialOrd for MaybeOwned<'a> {
- #[inline]
- fn partial_cmp(&self, other: &MaybeOwned) -> Option<Ordering> {
- Some(self.cmp(other))
- }
-}
-
-#[deprecated = "use std::string::CowString"]
-impl<'a> Ord for MaybeOwned<'a> {
- #[inline]
- #[allow(deprecated)]
- fn cmp(&self, other: &MaybeOwned) -> Ordering {
- self.as_slice().cmp(other.as_slice())
- }
-}
-
-#[allow(deprecated)]
-#[deprecated = "use std::string::CowString"]
-impl<'a, S: Str> Equiv<S> for MaybeOwned<'a> {
- #[inline]
- fn equiv(&self, other: &S) -> bool {
- self.as_slice() == other.as_slice()
- }
-}
-
-#[deprecated = "use std::string::CowString"]
-#[allow(deprecated)]
-impl<'a> Str for MaybeOwned<'a> {
- #[inline]
- fn as_slice<'b>(&'b self) -> &'b str {
- match *self {
- Slice(s) => s,
- Owned(ref s) => s.as_slice()
- }
- }
-}
-
-#[deprecated = "use std::string::CowString"]
-impl<'a> Clone for MaybeOwned<'a> {
- #[allow(deprecated)]
- #[inline]
- fn clone(&self) -> MaybeOwned<'a> {
- match *self {
- Slice(s) => Slice(s),
- Owned(ref s) => Owned(String::from_str(s.as_slice()))
- }
- }
-}
-
-#[deprecated = "use std::string::CowString"]
-impl<'a> Default for MaybeOwned<'a> {
- #[allow(deprecated)]
- #[inline]
- fn default() -> MaybeOwned<'a> { Slice("") }
-}
-
-#[deprecated = "use std::string::CowString"]
-#[allow(deprecated)]
-impl<'a, H: hash::Writer> hash::Hash<H> for MaybeOwned<'a> {
- #[inline]
- fn hash(&self, hasher: &mut H) {
- self.as_slice().hash(hasher)
- }
-}
-
-#[deprecated = "use std::string::CowString"]
-impl<'a> fmt::Show for MaybeOwned<'a> {
- #[inline]
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- Slice(ref s) => s.fmt(f),
- Owned(ref s) => s.fmt(f)
- }
- }
-}
-
#[unstable = "trait is unstable"]
impl BorrowFrom<String> for str {
fn borrow_from(owned: &String) -> &str { owned[] }
}
}
-/// Unsafe string operations.
-#[deprecated]
-pub mod raw {
- pub use core::str::raw::{from_utf8, c_str_to_static_slice, slice_bytes};
- pub use core::str::raw::{slice_unchecked};
-}
-
/*
Section: CowString
*/
-/// A clone-on-write string
-#[deprecated = "use std::string::CowString instead"]
-pub type CowString<'a> = Cow<'a, String, str>;
-
/*
Section: Trait implementations
*/
result
}
- /// Given a string, makes a new string with repeated copies of it.
- #[deprecated = "use repeat(self).take(n).collect() instead"]
- fn repeat(&self, nn: uint) -> String {
- iter::repeat(self[]).take(nn).collect()
- }
-
- /// Returns the Levenshtein Distance between two strings.
- #[deprecated = "this function will be removed"]
- fn lev_distance(&self, t: &str) -> uint {
- let me = self[];
- if me.is_empty() { return t.chars().count(); }
- if t.is_empty() { return me.chars().count(); }
-
- let mut dcol: Vec<_> = range(0, t.len() + 1).collect();
- let mut t_last = 0;
-
- for (i, sc) in me.chars().enumerate() {
-
- let mut current = i;
- dcol[0] = current + 1;
-
- for (j, tc) in t.chars().enumerate() {
-
- let next = dcol[j + 1];
-
- if sc == tc {
- dcol[j + 1] = current;
- } else {
- dcol[j + 1] = cmp::min(current, next);
- dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1;
- }
-
- current = next;
- t_last = j;
- }
- }
-
- dcol[t_last + 1]
- }
-
/// Returns an iterator over the string in Unicode Normalization Form D
/// (canonical decomposition).
#[inline]
/// assert_eq!(v, vec!["1", "", "2"]);
/// ```
#[unstable = "might get removed in the future in favor of a more generic split()"]
- fn split_str<'a>(&'a self, pat: &'a str) -> StrSplits<'a> {
+ fn split_str<'a>(&'a self, pat: &'a str) -> SplitStr<'a> {
core_str::StrExt::split_str(self[], pat)
}
core_str::StrExt::lines_any(self[])
}
- /// Returns the number of Unicode code points (`char`) that a
- /// string holds.
- ///
- /// This does not perform any normalization, and is `O(n)`, since
- /// UTF-8 is a variable width encoding of code points.
- ///
- /// *Warning*: The number of code points in a string does not directly
- /// correspond to the number of visible characters or width of the
- /// visible text due to composing characters, and double- and
- /// zero-width ones.
- ///
- /// See also `.len()` for the byte length.
- ///
- /// # Example
- ///
- /// ```rust
- /// # #![allow(deprecated)]
- /// // composed forms of `ö` and `é`
- /// let c = "Löwe 老虎 Léopard"; // German, Simplified Chinese, French
- /// // decomposed forms of `ö` and `é`
- /// let d = "Lo\u{0308}we 老虎 Le\u{0301}opard";
- ///
- /// assert_eq!(c.char_len(), 15);
- /// assert_eq!(d.char_len(), 17);
- ///
- /// assert_eq!(c.len(), 21);
- /// assert_eq!(d.len(), 23);
- ///
- /// // the two strings *look* the same
- /// println!("{}", c);
- /// println!("{}", d);
- /// ```
- #[deprecated = "call .chars().count() instead"]
- fn char_len(&self) -> uint {
- core_str::StrExt::char_len(self[])
- }
-
/// Returns a slice of the given string from the byte range
/// [`begin`..`end`).
///
core_str::StrExt::trim_matches(self[], pat)
}
- /// Deprecated
- #[deprecated = "Replaced by `trim_matches`"]
- fn trim_chars<'a, C: CharEq>(&'a self, to_trim: C) -> &'a str {
- self.trim_matches(to_trim)
- }
-
/// Returns a string with all prefixes that match
/// the pattern `pat` repeatedly removed.
///
core_str::StrExt::trim_left_matches(self[], pat)
}
- /// Deprecated
- #[deprecated = "Replaced by `trim_left_matches`"]
- fn trim_left_chars<'a, C: CharEq>(&'a self, to_trim: C) -> &'a str {
- self.trim_left_matches(to_trim)
- }
-
/// Returns a string with all suffixes that match
/// the pattern `pat` repeatedly removed.
///
core_str::StrExt::trim_right_matches(self[], pat)
}
- /// Deprecated
- #[deprecated = "Replaced by `trim_right_matches`"]
- fn trim_right_chars<'a, C: CharEq>(&'a self, to_trim: C) -> &'a str {
- self.trim_right_matches(to_trim)
- }
-
/// Check that `index`-th byte lies at the start and/or end of a
/// UTF-8 code point sequence.
///
#[inline]
#[unstable = "this method was just created"]
fn parse<F: FromStr>(&self) -> Option<F> {
- FromStr::from_str(self[])
+ core_str::StrExt::parse(self[])
}
/// Returns an iterator over the
UnicodeStr::words(self[])
}
- /// Returns true if the string contains only whitespace.
- ///
- /// Whitespace characters are determined by `char::is_whitespace`.
- ///
- /// # Example
- ///
- /// ```rust
- /// # #![allow(deprecated)]
- /// assert!(" \t\n".is_whitespace());
- /// assert!("".is_whitespace());
- ///
- /// assert!( !"abc".is_whitespace());
- /// ```
- #[deprecated = "use .chars().all(|c| c.is_whitespace())"]
- fn is_whitespace(&self) -> bool {
- UnicodeStr::is_whitespace(self[])
- }
-
- /// Returns true if the string contains only alphanumeric code
- /// points.
- ///
- /// Alphanumeric characters are determined by `char::is_alphanumeric`.
- ///
- /// # Example
- ///
- /// ```rust
- /// # #![allow(deprecated)]
- /// assert!("Löwe老虎Léopard123".is_alphanumeric());
- /// assert!("".is_alphanumeric());
- ///
- /// assert!( !" &*~".is_alphanumeric());
- /// ```
- #[deprecated = "use .chars().all(|c| c.is_alphanumeric())"]
- fn is_alphanumeric(&self) -> bool {
- UnicodeStr::is_alphanumeric(self[])
- }
-
/// Returns a string's displayed width in columns, treating control
/// characters as zero-width.
///
fn trim_right(&self) -> &str {
UnicodeStr::trim_right(self[])
}
-
- /// Deprecated, call `.to_owned()` instead from the `std::borrow::ToOwned`
- /// trait.
- #[deprecated = "call `.to_owned()` on `std::borrow::ToOwned` instead"]
- fn into_string(&self) -> String {
- self[].to_owned()
- }
}
impl StrExt for str {}
mod tests {
use prelude::*;
- use core::default::Default;
use core::iter::AdditiveIterator;
- use super::{from_utf8, is_utf8, raw};
- use super::MaybeOwned::{Owned, Slice};
+ use super::from_utf8;
use super::Utf8Error;
#[test]
assert_eq!("\u{2620}".len(), 3u);
assert_eq!("\u{1d11e}".len(), 4u);
- assert_eq!("".char_len(), 0u);
- assert_eq!("hello world".char_len(), 11u);
- assert_eq!("\x63".char_len(), 1u);
- assert_eq!("\u{a2}".char_len(), 1u);
- assert_eq!("\u{3c0}".char_len(), 1u);
- assert_eq!("\u{2620}".char_len(), 1u);
- assert_eq!("\u{1d11e}".char_len(), 1u);
- assert_eq!("ประเทศไทย中华Việt Nam".char_len(), 19u);
+ assert_eq!("".chars().count(), 0u);
+ assert_eq!("hello world".chars().count(), 11u);
+ assert_eq!("\x63".chars().count(), 1u);
+ assert_eq!("\u{a2}".chars().count(), 1u);
+ assert_eq!("\u{3c0}".chars().count(), 1u);
+ assert_eq!("\u{2620}".chars().count(), 1u);
+ assert_eq!("\u{1d11e}".chars().count(), 1u);
+ assert_eq!("ประเทศไทย中华Việt Nam".chars().count(), 19u);
assert_eq!("hello".width(false), 10u);
assert_eq!("hello".width(true), 10u);
#[test]
fn test_slice_chars() {
fn t(a: &str, b: &str, start: uint) {
- assert_eq!(a.slice_chars(start, start + b.char_len()), b);
+ assert_eq!(a.slice_chars(start, start + b.chars().count()), b);
}
t("", "", 0);
t("hello", "llo", 2);
assert_eq!("ะเทศไท", "ประเทศไทย中华Việt Nam".slice_chars(2, 8));
}
- fn s(x: &str) -> String { x.into_string() }
+ fn s(x: &str) -> String { x.to_string() }
macro_rules! test_concat {
($expected: expr, $string: expr) => {
#[test]
fn test_connect_for_different_types() {
test_connect!("a-b", ["a", "b"], "-");
- let hyphen = "-".into_string();
+ let hyphen = "-".to_string();
test_connect!("a-b", [s("a"), s("b")], hyphen.as_slice());
test_connect!("a-b", vec!["a", "b"], hyphen.as_slice());
test_connect!("a-b", vec!["a", "b"].as_slice(), "-");
test_connect!("-a-bc", ["", "a", "bc"], "-");
}
- #[test]
- fn test_repeat() {
- assert_eq!("x".repeat(4), String::from_str("xxxx"));
- assert_eq!("hi".repeat(4), String::from_str("hihihihi"));
- assert_eq!("ไท华".repeat(3), String::from_str("ไท华ไท华ไท华"));
- assert_eq!("".repeat(4), String::from_str(""));
- assert_eq!("hi".repeat(0), String::from_str(""));
- }
-
#[test]
fn test_unsafe_slice() {
- assert_eq!("ab", unsafe {raw::slice_bytes("abc", 0, 2)});
- assert_eq!("bc", unsafe {raw::slice_bytes("abc", 1, 3)});
- assert_eq!("", unsafe {raw::slice_bytes("abc", 1, 1)});
+ assert_eq!("ab", unsafe {"abc".slice_unchecked(0, 2)});
+ assert_eq!("bc", unsafe {"abc".slice_unchecked(1, 3)});
+ assert_eq!("", unsafe {"abc".slice_unchecked(1, 1)});
fn a_million_letter_a() -> String {
let mut i = 0u;
let mut rs = String::new();
}
let letters = a_million_letter_a();
assert!(half_a_million_letter_a() ==
- unsafe {String::from_str(raw::slice_bytes(letters.as_slice(),
+ unsafe {String::from_str(letters.slice_unchecked(
0u,
500000))});
}
}
#[test]
- fn test_trim_left_chars() {
+ fn test_trim_left_matches() {
let v: &[char] = &[];
- assert_eq!(" *** foo *** ".trim_left_chars(v), " *** foo *** ");
+ assert_eq!(" *** foo *** ".trim_left_matches(v), " *** foo *** ");
let chars: &[char] = &['*', ' '];
- assert_eq!(" *** foo *** ".trim_left_chars(chars), "foo *** ");
- assert_eq!(" *** *** ".trim_left_chars(chars), "");
- assert_eq!("foo *** ".trim_left_chars(chars), "foo *** ");
+ assert_eq!(" *** foo *** ".trim_left_matches(chars), "foo *** ");
+ assert_eq!(" *** *** ".trim_left_matches(chars), "");
+ assert_eq!("foo *** ".trim_left_matches(chars), "foo *** ");
- assert_eq!("11foo1bar11".trim_left_chars('1'), "foo1bar11");
+ assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
let chars: &[char] = &['1', '2'];
- assert_eq!("12foo1bar12".trim_left_chars(chars), "foo1bar12");
- assert_eq!("123foo1bar123".trim_left_chars(|&: c: char| c.is_numeric()), "foo1bar123");
+ assert_eq!("12foo1bar12".trim_left_matches(chars), "foo1bar12");
+ assert_eq!("123foo1bar123".trim_left_matches(|&: c: char| c.is_numeric()), "foo1bar123");
}
#[test]
- fn test_trim_right_chars() {
+ fn test_trim_right_matches() {
let v: &[char] = &[];
- assert_eq!(" *** foo *** ".trim_right_chars(v), " *** foo *** ");
+ assert_eq!(" *** foo *** ".trim_right_matches(v), " *** foo *** ");
let chars: &[char] = &['*', ' '];
- assert_eq!(" *** foo *** ".trim_right_chars(chars), " *** foo");
- assert_eq!(" *** *** ".trim_right_chars(chars), "");
- assert_eq!(" *** foo".trim_right_chars(chars), " *** foo");
+ assert_eq!(" *** foo *** ".trim_right_matches(chars), " *** foo");
+ assert_eq!(" *** *** ".trim_right_matches(chars), "");
+ assert_eq!(" *** foo".trim_right_matches(chars), " *** foo");
- assert_eq!("11foo1bar11".trim_right_chars('1'), "11foo1bar");
+ assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
let chars: &[char] = &['1', '2'];
- assert_eq!("12foo1bar12".trim_right_chars(chars), "12foo1bar");
- assert_eq!("123foo1bar123".trim_right_chars(|&: c: char| c.is_numeric()), "123foo1bar");
+ assert_eq!("12foo1bar12".trim_right_matches(chars), "12foo1bar");
+ assert_eq!("123foo1bar123".trim_right_matches(|&: c: char| c.is_numeric()), "123foo1bar");
}
#[test]
- fn test_trim_chars() {
+ fn test_trim_matches() {
let v: &[char] = &[];
- assert_eq!(" *** foo *** ".trim_chars(v), " *** foo *** ");
+ assert_eq!(" *** foo *** ".trim_matches(v), " *** foo *** ");
let chars: &[char] = &['*', ' '];
- assert_eq!(" *** foo *** ".trim_chars(chars), "foo");
- assert_eq!(" *** *** ".trim_chars(chars), "");
- assert_eq!("foo".trim_chars(chars), "foo");
+ assert_eq!(" *** foo *** ".trim_matches(chars), "foo");
+ assert_eq!(" *** *** ".trim_matches(chars), "");
+ assert_eq!("foo".trim_matches(chars), "foo");
- assert_eq!("11foo1bar11".trim_chars('1'), "foo1bar");
+ assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
let chars: &[char] = &['1', '2'];
- assert_eq!("12foo1bar12".trim_chars(chars), "foo1bar");
- assert_eq!("123foo1bar123".trim_chars(|&: c: char| c.is_numeric()), "foo1bar");
+ assert_eq!("12foo1bar12".trim_matches(chars), "foo1bar");
+ assert_eq!("123foo1bar123".trim_matches(|&: c: char| c.is_numeric()), "foo1bar");
}
#[test]
#[test]
fn test_is_whitespace() {
- assert!("".is_whitespace());
- assert!(" ".is_whitespace());
- assert!("\u{2009}".is_whitespace()); // Thin space
- assert!(" \n\t ".is_whitespace());
- assert!(!" _ ".is_whitespace());
+ assert!("".chars().all(|c| c.is_whitespace()));
+ assert!(" ".chars().all(|c| c.is_whitespace()));
+ assert!("\u{2009}".chars().all(|c| c.is_whitespace())); // Thin space
+ assert!(" \n\t ".chars().all(|c| c.is_whitespace()));
+ assert!(!" _ ".chars().all(|c| c.is_whitespace()));
}
#[test]
#[test]
fn test_is_utf8() {
// deny overlong encodings
- assert!(!is_utf8(&[0xc0, 0x80]));
- assert!(!is_utf8(&[0xc0, 0xae]));
- assert!(!is_utf8(&[0xe0, 0x80, 0x80]));
- assert!(!is_utf8(&[0xe0, 0x80, 0xaf]));
- assert!(!is_utf8(&[0xe0, 0x81, 0x81]));
- assert!(!is_utf8(&[0xf0, 0x82, 0x82, 0xac]));
- assert!(!is_utf8(&[0xf4, 0x90, 0x80, 0x80]));
+ assert!(from_utf8(&[0xc0, 0x80]).is_err());
+ assert!(from_utf8(&[0xc0, 0xae]).is_err());
+ assert!(from_utf8(&[0xe0, 0x80, 0x80]).is_err());
+ assert!(from_utf8(&[0xe0, 0x80, 0xaf]).is_err());
+ assert!(from_utf8(&[0xe0, 0x81, 0x81]).is_err());
+ assert!(from_utf8(&[0xf0, 0x82, 0x82, 0xac]).is_err());
+ assert!(from_utf8(&[0xf4, 0x90, 0x80, 0x80]).is_err());
// deny surrogates
- assert!(!is_utf8(&[0xED, 0xA0, 0x80]));
- assert!(!is_utf8(&[0xED, 0xBF, 0xBF]));
+ assert!(from_utf8(&[0xED, 0xA0, 0x80]).is_err());
+ assert!(from_utf8(&[0xED, 0xBF, 0xBF]).is_err());
- assert!(is_utf8(&[0xC2, 0x80]));
- assert!(is_utf8(&[0xDF, 0xBF]));
- assert!(is_utf8(&[0xE0, 0xA0, 0x80]));
- assert!(is_utf8(&[0xED, 0x9F, 0xBF]));
- assert!(is_utf8(&[0xEE, 0x80, 0x80]));
- assert!(is_utf8(&[0xEF, 0xBF, 0xBF]));
- assert!(is_utf8(&[0xF0, 0x90, 0x80, 0x80]));
- assert!(is_utf8(&[0xF4, 0x8F, 0xBF, 0xBF]));
+ assert!(from_utf8(&[0xC2, 0x80]).is_ok());
+ assert!(from_utf8(&[0xDF, 0xBF]).is_ok());
+ assert!(from_utf8(&[0xE0, 0xA0, 0x80]).is_ok());
+ assert!(from_utf8(&[0xED, 0x9F, 0xBF]).is_ok());
+ assert!(from_utf8(&[0xEE, 0x80, 0x80]).is_ok());
+ assert!(from_utf8(&[0xEF, 0xBF, 0xBF]).is_ok());
+ assert!(from_utf8(&[0xF0, 0x90, 0x80, 0x80]).is_ok());
+ assert!(from_utf8(&[0xF4, 0x8F, 0xBF, 0xBF]).is_ok());
}
#[test]
let mut pos = 0;
for ch in v.iter() {
assert!(s.char_at(pos) == *ch);
- pos += String::from_char(1, *ch).len();
+ pos += ch.to_string().len();
}
}
let mut pos = s.len();
for ch in v.iter().rev() {
assert!(s.char_at_reverse(pos) == *ch);
- pos -= String::from_char(1, *ch).len();
+ pos -= ch.to_string().len();
}
}
let xs = b"hello\xFF";
assert_eq!(from_utf8(xs), Err(Utf8Error::TooShort));
}
-
- #[test]
- fn test_maybe_owned_traits() {
- let s = Slice("abcde");
- assert_eq!(s.len(), 5);
- assert_eq!(s.as_slice(), "abcde");
- assert_eq!(String::from_str(s.as_slice()).as_slice(), "abcde");
- assert_eq!(format!("{}", s).as_slice(), "abcde");
- assert!(s.lt(&Owned(String::from_str("bcdef"))));
- assert_eq!(Slice(""), Default::default());
-
- let o = Owned(String::from_str("abcde"));
- assert_eq!(o.len(), 5);
- assert_eq!(o.as_slice(), "abcde");
- assert_eq!(String::from_str(o.as_slice()).as_slice(), "abcde");
- assert_eq!(format!("{}", o).as_slice(), "abcde");
- assert!(o.lt(&Slice("bcdef")));
- assert_eq!(Owned(String::from_str("")), Default::default());
-
- assert!(s.cmp(&o) == Equal);
- assert!(s.equiv(&o));
-
- assert!(o.cmp(&s) == Equal);
- assert!(o.equiv(&s));
- }
-
- #[test]
- fn test_maybe_owned_methods() {
- let s = Slice("abcde");
- assert!(s.is_slice());
- assert!(!s.is_owned());
-
- let o = Owned(String::from_str("abcde"));
- assert!(!o.is_slice());
- assert!(o.is_owned());
- }
-
- #[test]
- fn test_maybe_owned_clone() {
- assert_eq!(Owned(String::from_str("abcde")), Slice("abcde").clone());
- assert_eq!(Owned(String::from_str("abcde")), Owned(String::from_str("abcde")).clone());
- assert_eq!(Slice("abcde"), Slice("abcde").clone());
- assert_eq!(Slice("abcde"), Owned(String::from_str("abcde")).clone());
- }
-
- #[test]
- fn test_maybe_owned_into_string() {
- assert_eq!(Slice("abcde").to_string(), String::from_str("abcde"));
- assert_eq!(Owned(String::from_str("abcde")).to_string(),
- String::from_str("abcde"));
- }
-
- #[test]
- fn test_into_maybe_owned() {
- assert_eq!("abcde".into_maybe_owned(), Slice("abcde"));
- assert_eq!((String::from_str("abcde")).into_maybe_owned(), Slice("abcde"));
- assert_eq!("abcde".into_maybe_owned(), Owned(String::from_str("abcde")));
- assert_eq!((String::from_str("abcde")).into_maybe_owned(),
- Owned(String::from_str("abcde")));
- }
}
#[cfg(test)]
#[bench]
fn char_indicesator(b: &mut Bencher) {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
- let len = s.char_len();
+ let len = s.chars().count();
b.iter(|| assert_eq!(s.char_indices().count(), len));
}
#[bench]
fn char_indicesator_rev(b: &mut Bencher) {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
- let len = s.char_len();
+ let len = s.chars().count();
b.iter(|| assert_eq!(s.char_indices().rev().count(), len));
}
b.iter(|| assert_eq!(s.split(c).count(), len));
}
- #[bench]
- fn is_utf8_100_ascii(b: &mut Bencher) {
-
- let s = b"Hello there, the quick brown fox jumped over the lazy dog! \
- Lorem ipsum dolor sit amet, consectetur. ";
-
- assert_eq!(100, s.len());
- b.iter(|| {
- is_utf8(s)
- });
- }
-
- #[bench]
- fn is_utf8_100_multibyte(b: &mut Bencher) {
- let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes();
- assert_eq!(100, s.len());
- b.iter(|| {
- is_utf8(s)
- });
- }
-
#[bench]
fn bench_connect(b: &mut Bencher) {
let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
use core::prelude::*;
use core::borrow::{Cow, IntoCow};
-use core::cmp::Equiv;
use core::default::Default;
use core::fmt;
use core::hash;
use core::iter::FromIterator;
use core::mem;
-use core::ops::{mod, Deref, Add};
+use core::ops::{self, Deref, Add};
use core::ptr;
use core::raw::Slice as RawSlice;
use unicode::str as unicode_str;
use unicode::str::Utf16Item;
-use str::{mod, CharRange, FromStr, Utf8Error};
+use str::{self, CharRange, FromStr, Utf8Error};
use vec::{DerefVec, Vec, as_vec};
/// A growable string stored as a UTF-8 encoded buffer.
-#[deriving(Clone, PartialOrd, Eq, Ord)]
+#[derive(Clone, PartialOrd, Eq, Ord)]
#[stable]
pub struct String {
vec: Vec<u8>,
/// # Examples
///
/// ```rust
- /// # #![allow(deprecated)]
/// use std::str::Utf8Error;
///
/// let hello_vec = vec![104, 101, 108, 108, 111];
unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
}
- /// Convert a vector of `char`s to a `String`.
- ///
- /// # Examples
- ///
- /// ```rust
- /// # #![allow(deprecated)]
- /// let chars = &['h', 'e', 'l', 'l', 'o'];
- /// let s = String::from_chars(chars);
- /// assert_eq!(s.as_slice(), "hello");
- /// ```
- #[inline]
- #[deprecated = "use .collect() instead"]
- pub fn from_chars(chs: &[char]) -> String {
- chs.iter().map(|c| *c).collect()
- }
-
/// Creates a new `String` from a length, capacity, and pointer.
///
/// This is unsafe because:
self.vec
}
- /// Creates a string buffer by repeating a character `length` times.
- ///
- /// # Examples
- ///
- /// ```
- /// # #![allow(deprecated)]
- /// let s = String::from_char(5, 'a');
- /// assert_eq!(s.as_slice(), "aaaaa");
- /// ```
- #[inline]
- #[deprecated = "use repeat(ch).take(length).collect() instead"]
- pub fn from_char(length: uint, ch: char) -> String {
- if length == 0 {
- return String::new()
- }
-
- let mut buf = String::new();
- buf.push(ch);
- let size = buf.len() * (length - 1);
- buf.reserve_exact(size);
- for _ in range(1, length) {
- buf.push(ch)
- }
- buf
- }
-
/// Pushes the given string onto this string buffer.
///
/// # Examples
self.vec.push_all(string.as_bytes())
}
- /// Pushes `ch` onto the given string `count` times.
- ///
- /// # Examples
- ///
- /// ```
- /// # #![allow(deprecated)]
- /// let mut s = String::from_str("foo");
- /// s.grow(5, 'Z');
- /// assert_eq!(s.as_slice(), "fooZZZZZ");
- /// ```
- #[inline]
- #[deprecated = "deprecated in favor of .extend(repeat(ch).take(count))"]
- pub fn grow(&mut self, count: uint, ch: char) {
- for _ in range(0, count) {
- self.push(ch)
- }
- }
-
/// Returns the number of bytes that this string buffer can hold without
/// reallocating.
///
self.vec.capacity()
}
- /// Deprecated: Renamed to `reserve`.
- #[deprecated = "Renamed to `reserve`"]
- pub fn reserve_additional(&mut self, extra: uint) {
- self.vec.reserve(extra)
- }
-
/// Reserves capacity for at least `additional` more bytes to be inserted
/// in the given `String`. The collection may reserve more space to avoid
/// frequent reallocations.
}
#[experimental = "waiting on Str stabilization"]
-#[allow(deprecated)]
impl Str for String {
#[inline]
#[stable]
}
}
-#[allow(deprecated)]
-#[deprecated = "Use overloaded `core::cmp::PartialEq`"]
-impl<'a, S: Str> Equiv<S> for String {
- #[inline]
- fn equiv(&self, other: &S) -> bool {
- self.as_slice() == other.as_slice()
- }
-}
-
#[experimental = "waiting on Add stabilization"]
impl<'a> Add<&'a str> for String {
type Output = String;
}
}
-/// Trait for converting a type to a string, consuming it in the process.
-#[deprecated = "trait will be removed"]
-pub trait IntoString {
- /// Consume and convert to a string.
- fn into_string(self) -> String;
-}
-
/// A generic trait for converting a value to a string
pub trait ToString {
/// Converts the value of `self` to an owned string
}
}
-/// Unsafe operations
-#[deprecated]
-pub mod raw {
- use super::String;
- use vec::Vec;
-
- /// Creates a new `String` from a length, capacity, and pointer.
- ///
- /// This is unsafe because:
- /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
- /// * We assume that the `Vec` contains valid UTF-8.
- #[inline]
- #[deprecated = "renamed to String::from_raw_parts"]
- pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
- String::from_raw_parts(buf, length, capacity)
- }
-
- /// Creates a `String` from a `*const u8` buffer of the given length.
- ///
- /// This function is unsafe because of two reasons:
- ///
- /// * A raw pointer is dereferenced and transmuted to `&[u8]`;
- /// * The slice is not checked to see whether it contains valid UTF-8.
- #[deprecated = "renamed to String::from_raw_buf_len"]
- pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
- String::from_raw_buf_len(buf, len)
- }
-
- /// Creates a `String` from a null-terminated `*const u8` buffer.
- ///
- /// This function is unsafe because we dereference memory until we find the NUL character,
- /// which is not guaranteed to be present. Additionally, the slice is not checked to see
- /// whether it contains valid UTF-8
- #[deprecated = "renamed to String::from_raw_buf"]
- pub unsafe fn from_buf(buf: *const u8) -> String {
- String::from_raw_buf(buf)
- }
-
- /// Converts a vector of bytes to a new `String` without checking if
- /// it contains valid UTF-8. This is unsafe because it assumes that
- /// the UTF-8-ness of the vector has already been validated.
- #[inline]
- #[deprecated = "renamed to String::from_utf8_unchecked"]
- pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
- String::from_utf8_unchecked(bytes)
- }
-}
-
/// A clone-on-write string
#[stable]
pub type CowString<'a> = Cow<'a, String, str>;
-#[allow(deprecated)]
impl<'a> Str for CowString<'a> {
#[inline]
fn as_slice<'b>(&'b self) -> &'b str {
use test::Bencher;
use str::Utf8Error;
- use str;
- use super::as_string;
+ use core::iter::repeat;
+ use super::{as_string, CowString};
#[test]
fn test_as_string() {
#[test]
fn test_from_str() {
- let owned: Option<::std::string::String> = from_str("string");
+ let owned: Option<::std::string::String> = "string".parse();
assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
}
#[test]
fn test_from_utf8_lossy() {
let xs = b"hello";
- let ys: str::CowString = "hello".into_cow();
+ let ys: CowString = "hello".into_cow();
assert_eq!(String::from_utf8_lossy(xs), ys);
let xs = "ศไทย中华Việt Nam".as_bytes();
- let ys: str::CowString = "ศไทย中华Việt Nam".into_cow();
+ let ys: CowString = "ศไทย中华Việt Nam".into_cow();
assert_eq!(String::from_utf8_lossy(xs), ys);
let xs = b"Hello\xC2 There\xFF Goodbye";
fn test_from_buf_len() {
unsafe {
let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0];
- assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
+ assert_eq!(String::from_raw_buf_len(a.as_ptr(), 3), String::from_str("AAA"));
}
}
unsafe {
let a = vec![65, 65, 65, 65, 65, 65, 65, 0];
let b = a.as_ptr();
- let c = super::raw::from_buf(b);
+ let c = String::from_raw_buf(b);
assert_eq!(c, String::from_str("AAAAAAA"));
}
}
#[bench]
fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
- let s = Vec::from_elem(100, 0xF5u8);
+ let s = repeat(0xf5u8).take(100).collect::<Vec<_>>();
b.iter(|| {
let _ = String::from_utf8_lossy(s.as_slice());
});
use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
use core::borrow::{Cow, IntoCow};
use core::cmp::max;
-use core::cmp::{Equiv, Ordering};
+use core::cmp::{Ordering};
use core::default::Default;
use core::fmt;
-use core::hash::{mod, Hash};
+use core::hash::{self, Hash};
use core::iter::{repeat, FromIterator};
use core::kinds::marker::{ContravariantLifetime, InvariantType};
use core::mem;
}
}
- /// Deprecated: use `iter::range(0, length).map(op).collect()` instead
- #[inline]
- #[deprecated = "use iter::range(0, length).map(op).collect() instead"]
- pub fn from_fn<F>(length: uint, op: F) -> Vec<T> where F: FnMut(uint) -> T {
- range(0, length).map(op).collect()
- }
-
/// Creates a `Vec<T>` directly from the raw components of another vector.
///
/// This is highly unsafe, due to the number of invariants that aren't checked.
dst
}
- /// Deprecated: use `into_iter().partition(f)` instead.
- #[inline]
- #[deprecated = "use into_iter().partition(f) instead"]
- pub fn partition<F>(self, f: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool {
- self.into_iter().partition(f)
- }
-
/// Returns the number of elements the vector can hold without
/// reallocating.
///
self.cap
}
- /// Deprecated: Renamed to `reserve`.
- #[deprecated = "Renamed to `reserve`"]
- pub fn reserve_additional(&mut self, extra: uint) {
- self.reserve(extra)
- }
-
/// Reserves capacity for at least `additional` more elements to be inserted in the given
/// `Vec<T>`. The collection may reserve more space to avoid frequent reallocations.
///
}
}
- /// Deprecated: use `extend(range(0, n).map(f))` instead.
- #[deprecated = "use extend(range(0, n).map(f)) instead"]
- pub fn grow_fn<F>(&mut self, n: uint, f: F) where F: FnMut(uint) -> T {
- self.extend(range(0, n).map(f));
- }
-
/// Appends an element to the back of a collection.
///
/// # Panics
/// let w = v.map_in_place(|i| i + 3);
/// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
///
- /// #[deriving(PartialEq, Show)]
+ /// #[derive(PartialEq, Show)]
/// struct Newtype(u8);
/// let bytes = vec![0x11, 0x22];
/// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
}
impl<T: Clone> Vec<T> {
- /// Deprecated: use `repeat(value).take(length).collect()` instead.
- #[inline]
- #[deprecated = "use repeat(value).take(length).collect() instead"]
- pub fn from_elem(length: uint, value: T) -> Vec<T> {
- repeat(value).take(length).collect()
- }
-
/// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
///
/// Calls either `extend()` or `truncate()` depending on whether `new_len`
}
}
}
-
- /// Deprecated: use `extend(repeat(value).take(n))` instead
- #[deprecated = "use extend(repeat(value).take(n)) instead"]
- pub fn grow(&mut self, n: uint, value: T) {
- self.extend(repeat(value).take(n))
- }
-
- /// Deprecated: use `iter().cloned().partition(f)` instead.
- #[deprecated = "use iter().cloned().partition(f) instead"]
- pub fn partitioned<F>(&self, f: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool {
- self.iter().cloned().partition(f)
- }
}
impl<T: PartialEq> Vec<T> {
}
}
-////////////////////////////////////////////////////////////////////////////////
-// Public free fns
-////////////////////////////////////////////////////////////////////////////////
-
-/// Deprecated: use `unzip` directly on the iterator instead.
-#[deprecated = "use unzip directly on the iterator instead"]
-pub fn unzip<T, U, V: Iterator<Item=(T, U)>>(iter: V) -> (Vec<T>, Vec<U>) {
- iter.unzip()
-}
-
////////////////////////////////////////////////////////////////////////////////
// Internal methods and functions
////////////////////////////////////////////////////////////////////////////////
#[unstable = "waiting on Eq stability"]
impl<T: Eq> Eq for Vec<T> {}
-#[allow(deprecated)]
-#[deprecated = "Use overloaded `core::cmp::PartialEq`"]
-impl<T: PartialEq, Sized? V: AsSlice<T>> Equiv<V> for Vec<T> {
- #[inline]
- fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
-}
-
#[unstable = "waiting on Ord stability"]
impl<T: Ord> Ord for Vec<T> {
#[inline]
end: *const T
}
-#[deprecated = "use IntoIter instead"]
-pub type MoveItems<T> = IntoIter<T>;
-
impl<T> IntoIter<T> {
#[inline]
/// Drops all items that have not yet been moved and returns the empty vector.
Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
}
}
-
- /// Deprecated, use .into_inner() instead
- #[deprecated = "use .into_inner() instead"]
- pub fn unwrap(self) -> Vec<T> { self.into_inner() }
}
impl<T> Iterator for IntoIter<T> {
}
}
-////////////////////////////////////////////////////////////////////////////////
-// Raw module (deprecated)
-////////////////////////////////////////////////////////////////////////////////
-
-/// Unsafe vector operations.
-#[deprecated]
-pub mod raw {
- use super::Vec;
-
- /// Constructs a vector from an unsafe pointer to a buffer.
- ///
- /// The elements of the buffer are copied into the vector without cloning,
- /// as if `ptr::read()` were called on them.
- #[inline]
- #[deprecated = "renamed to Vec::from_raw_buf"]
- pub unsafe fn from_buf<T>(ptr: *const T, elts: uint) -> Vec<T> {
- Vec::from_raw_buf(ptr, elts)
- }
-}
-
////////////////////////////////////////////////////////////////////////////////
// Partial vec, used for map_in_place
////////////////////////////////////////////////////////////////////////////////
mod tests {
use prelude::*;
use core::mem::size_of;
+ use core::iter::repeat;
use test::Bencher;
- use super::{as_vec, unzip, raw};
+ use super::as_vec;
struct DropCounter<'a> {
count: &'a mut int
assert_eq!(v, three)
}
- #[test]
- fn test_grow_fn() {
- let mut v = vec![0u, 1];
- v.grow_fn(3, |i| i);
- assert!(v == vec![0u, 1, 0, 1, 2]);
- }
-
#[test]
fn test_retain() {
let mut vec = vec![1u, 2, 3, 4];
#[test]
fn test_partition() {
- assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
- assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
- assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
- assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
- }
-
- #[test]
- fn test_partitioned() {
- assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]));
- assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
- assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
- assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
+ assert_eq!(vec![].into_iter().partition(|x: &int| *x < 3), (vec![], vec![]));
+ assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
+ assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
+ assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
}
#[test]
fn test_zip_unzip() {
let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
- let (left, right) = unzip(z1.iter().map(|&x| x));
+ let (left, right): (Vec<_>, Vec<_>) = z1.iter().map(|&x| x).unzip();
assert_eq!((1, 4), (left[0], right[0]));
assert_eq!((2, 5), (left[1], right[1]));
// Test on-stack copy-from-buf.
let a = [1i, 2, 3];
let ptr = a.as_ptr();
- let b = raw::from_buf(ptr, 3u);
+ let b = Vec::from_raw_buf(ptr, 3u);
assert_eq!(b, vec![1, 2, 3]);
// Test on-heap copy-from-buf.
let c = vec![1i, 2, 3, 4, 5];
let ptr = c.as_ptr();
- let d = raw::from_buf(ptr, 5u);
+ let d = Vec::from_raw_buf(ptr, 5u);
assert_eq!(d, vec![1, 2, 3, 4, 5]);
}
}
vec.push(1);
vec.push(2);
let ptr = vec.as_ptr();
- vec = vec.into_iter().unwrap();
+ vec = vec.into_iter().into_inner();
assert_eq!(vec.as_ptr(), ptr);
assert_eq!(vec.capacity(), 7);
assert_eq!(vec.len(), 0);
#[test]
fn test_map_in_place_zero_sized() {
let v = vec![(), ()];
- #[deriving(PartialEq, Show)]
+ #[derive(PartialEq, Show)]
struct ZeroSized;
assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]);
}
#[test]
fn test_map_in_place_zero_drop_count() {
- use std::sync::atomic;
- use std::sync::atomic::AtomicUint;
+ use std::sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};
- #[deriving(Clone, PartialEq, Show)]
+ #[derive(Clone, PartialEq, Show)]
struct Nothing;
impl Drop for Nothing { fn drop(&mut self) { } }
- #[deriving(Clone, PartialEq, Show)]
+ #[derive(Clone, PartialEq, Show)]
struct ZeroSized;
impl Drop for ZeroSized {
fn drop(&mut self) {
- DROP_COUNTER.fetch_add(1, atomic::Relaxed);
+ DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
}
}
const NUM_ELEMENTS: uint = 2;
- static DROP_COUNTER: AtomicUint = atomic::ATOMIC_UINT_INIT;
+ static DROP_COUNTER: AtomicUint = ATOMIC_UINT_INIT;
- let v = Vec::from_elem(NUM_ELEMENTS, Nothing);
+ let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>();
- DROP_COUNTER.store(0, atomic::Relaxed);
+ DROP_COUNTER.store(0, Ordering::Relaxed);
let v = v.map_in_place(|_| ZeroSized);
- assert_eq!(DROP_COUNTER.load(atomic::Relaxed), 0);
+ assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), 0);
drop(v);
- assert_eq!(DROP_COUNTER.load(atomic::Relaxed), NUM_ELEMENTS);
+ assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), NUM_ELEMENTS);
}
#[test]
b.bytes = src_len as u64;
b.iter(|| {
- let dst = Vec::from_fn(src_len, |i| i);
+ let dst = range(0, src_len).collect::<Vec<_>>();
assert_eq!(dst.len(), src_len);
assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
})
b.bytes = src_len as u64;
b.iter(|| {
- let dst: Vec<uint> = Vec::from_elem(src_len, 5);
+ let dst: Vec<uint> = repeat(5).take(src_len).collect();
assert_eq!(dst.len(), src_len);
assert!(dst.iter().all(|x| *x == 5));
})
#[stable]
pub fn clear(&mut self) { self.v.clear() }
- /// Deprecated: Renamed to `get`.
- #[deprecated = "Renamed to `get`"]
- pub fn find(&self, key: &uint) -> Option<&V> {
- self.get(key)
- }
-
/// Returns a reference to the value corresponding to the key.
///
/// # Examples
self.get(key).is_some()
}
- /// Deprecated: Renamed to `get_mut`.
- #[deprecated = "Renamed to `get_mut`"]
- pub fn find_mut(&mut self, key: &uint) -> Option<&mut V> {
- self.get_mut(key)
- }
-
/// Returns a mutable reference to the value corresponding to the key.
///
/// # Examples
}
}
- /// Deprecated: Renamed to `insert`.
- #[deprecated = "Renamed to `insert`"]
- pub fn swap(&mut self, key: uint, value: V) -> Option<V> {
- self.insert(key, value)
- }
-
/// Inserts a key-value pair from the map. If the key already had a value
/// present in the map, that value is returned. Otherwise, `None` is returned.
///
replace(&mut self.v[key], Some(value))
}
- /// Deprecated: Renamed to `remove`.
- #[deprecated = "Renamed to `remove`"]
- pub fn pop(&mut self, key: &uint) -> Option<V> {
- self.remove(key)
- }
-
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
///
}
}
-impl<V:Clone> VecMap<V> {
- /// Deprecated: Use the entry API when available; shouldn't matter anyway, access is cheap.
- #[deprecated = "Use the entry API when available; shouldn't matter anyway, access is cheap"]
- #[allow(deprecated)]
- pub fn update<F>(&mut self, key: uint, newval: V, ff: F) -> bool where F: FnOnce(V, V) -> V {
- self.update_with_key(key, newval, move |_k, v, v1| ff(v,v1))
- }
-
- /// Deprecated: Use the entry API when available; shouldn't matter anyway, access is cheap.
- #[deprecated = "Use the entry API when available; shouldn't matter anyway, access is cheap"]
- pub fn update_with_key<F>(&mut self, key: uint, val: V, ff: F) -> bool where
- F: FnOnce(uint, V, V) -> V
- {
- let new_val = match self.get(&key) {
- None => val,
- Some(orig) => ff(key, (*orig).clone(), val)
- };
- self.insert(key, new_val).is_none()
- }
-}
-
#[stable]
impl<V: PartialEq> PartialEq for VecMap<V> {
fn eq(&self, other: &VecMap<V>) -> bool {
iter: slice::Iter<'a, Option<V>>
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, V> Clone for Iter<'a, V> {
fn clone(&self) -> Iter<'a, V> {
Iter {
iter: Map<(uint, &'a V), uint, Iter<'a, V>, fn((uint, &'a V)) -> uint>
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, V> Clone for Keys<'a, V> {
fn clone(&self) -> Keys<'a, V> {
Keys {
iter: Map<(uint, &'a V), &'a V, Iter<'a, V>, fn((uint, &'a V)) -> &'a V>
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, V> Clone for Values<'a, V> {
fn clone(&self) -> Values<'a, V> {
Values {
assert!(map.get(&14).is_none());
}
- #[test]
- fn test_insert_with_key() {
- let mut map = VecMap::new();
-
- // given a new key, initialize it with this new count,
- // given an existing key, add more to its count
- fn add_more_to_count(_k: uint, v0: uint, v1: uint) -> uint {
- v0 + v1
- }
-
- fn add_more_to_count_simple(v0: uint, v1: uint) -> uint {
- v0 + v1
- }
-
- // count integers
- map.update(3, 1, add_more_to_count_simple);
- map.update_with_key(9, 1, add_more_to_count);
- map.update(3, 7, add_more_to_count_simple);
- map.update_with_key(5, 3, add_more_to_count);
- map.update_with_key(3, 2, add_more_to_count);
-
- // check the total counts
- assert_eq!(map.get(&3).unwrap(), &10);
- assert_eq!(map.get(&5).unwrap(), &3);
- assert_eq!(map.get(&9).unwrap(), &1);
-
- // sadly, no sevens were counted
- assert!(map.get(&7).is_none());
- }
-
#[test]
fn test_insert() {
let mut m = VecMap::new();
//!
//! ```rust
//! use std::fmt::Show;
-//! use std::any::{Any, AnyRefExt};
+//! use std::any::Any;
//!
//! // Logger function for any type that implements Show.
//! fn log<T: Any+Show>(value: &T) {
// Implemented as three extension traits so that the methods can be generic.
///////////////////////////////////////////////////////////////////////////////
-/// Extension methods for a referenced `Any` trait object
-#[unstable = "this trait will not be necessary once DST lands, it will be a \
- part of `impl Any`"]
-pub trait AnyRefExt<'a> {
+impl Any {
/// Returns true if the boxed type is the same as `T`
#[stable]
- fn is<T: 'static>(self) -> bool;
-
- /// Returns some reference to the boxed value if it is of type `T`, or
- /// `None` if it isn't.
- #[unstable = "naming conventions around acquiring references may change"]
- fn downcast_ref<T: 'static>(self) -> Option<&'a T>;
-}
-
-#[stable]
-impl<'a> AnyRefExt<'a> for &'a Any {
#[inline]
- fn is<T: 'static>(self) -> bool {
+ pub fn is<T: 'static>(&self) -> bool {
// Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>();
t == boxed
}
+ /// Returns some reference to the boxed value if it is of type `T`, or
+ /// `None` if it isn't.
+ #[unstable = "naming conventions around acquiring references may change"]
#[inline]
- fn downcast_ref<T: 'static>(self) -> Option<&'a T> {
+ pub fn downcast_ref<'a, T: 'static>(&'a self) -> Option<&'a T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
None
}
}
-}
-/// Extension methods for a mutable referenced `Any` trait object
-#[unstable = "this trait will not be necessary once DST lands, it will be a \
- part of `impl Any`"]
-pub trait AnyMutRefExt<'a> {
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[unstable = "naming conventions around acquiring references may change"]
- fn downcast_mut<T: 'static>(self) -> Option<&'a mut T>;
-}
-
-#[stable]
-impl<'a> AnyMutRefExt<'a> for &'a mut Any {
#[inline]
- fn downcast_mut<T: 'static>(self) -> Option<&'a mut T> {
+ pub fn downcast_mut<'a, T: 'static>(&'a mut self) -> Option<&'a mut T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Core atomic primitives
+//! Atomic types
+//!
+//! Atomic types provide primitive shared-memory communication between
+//! threads, and are the building blocks of other concurrent
+//! types.
+//!
+//! This module defines atomic versions of a select number of primitive
+//! types, including `AtomicBool`, `AtomicInt`, `AtomicUint`, and `AtomicOption`.
+//! Atomic types present operations that, when used correctly, synchronize
+//! updates between threads.
+//!
+//! Each method takes an `Ordering` which represents the strength of
+//! the memory barrier for that operation. These orderings are the
+//! same as [C++11 atomic orderings][1].
+//!
+//! [1]: http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync
+//!
+//! Atomic variables are safe to share between threads (they implement `Sync`)
+//! but they do not themselves provide the mechanism for sharing. The most
+//! common way to share an atomic variable is to put it into an `Arc` (an
+//! atomically-reference-counted shared pointer).
+//!
+//! Most atomic types may be stored in static variables, initialized using
+//! the provided static initializers like `INIT_ATOMIC_BOOL`. Atomic statics
+//! are often used for lazy global initialization.
+//!
+//!
+//! # Examples
+//!
+//! A simple spinlock:
+//!
+//! ```
+//! use std::sync::Arc;
+//! use std::sync::atomic::{AtomicUint, Ordering};
+//! use std::thread::Thread;
+//!
+//! fn main() {
+//! let spinlock = Arc::new(AtomicUint::new(1));
+//!
+//! let spinlock_clone = spinlock.clone();
+//! Thread::spawn(move|| {
+//! spinlock_clone.store(0, Ordering::SeqCst);
+//! }).detach();
+//!
+//! // Wait for the other task to release the lock
+//! while spinlock.load(Ordering::SeqCst) != 0 {}
+//! }
+//! ```
+//!
+//! Keep a global count of live tasks:
+//!
+//! ```
+//! use std::sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};
+//!
+//! static GLOBAL_TASK_COUNT: AtomicUint = ATOMIC_UINT_INIT;
+//!
+//! let old_task_count = GLOBAL_TASK_COUNT.fetch_add(1, Ordering::SeqCst);
+//! println!("live tasks: {}", old_task_count + 1);
+//! ```
#![stable]
/// Rust's memory orderings are [the same as
/// C++'s](http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync).
#[stable]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Ordering {
/// No ordering constraints, only atomic operations.
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicBool, SeqCst};
+ /// use std::sync::atomic::{AtomicBool, Ordering};
///
/// let foo = AtomicBool::new(true);
- /// assert_eq!(true, foo.fetch_and(false, SeqCst));
- /// assert_eq!(false, foo.load(SeqCst));
+ /// assert_eq!(true, foo.fetch_and(false, Ordering::SeqCst));
+ /// assert_eq!(false, foo.load(Ordering::SeqCst));
///
/// let foo = AtomicBool::new(true);
- /// assert_eq!(true, foo.fetch_and(true, SeqCst));
- /// assert_eq!(true, foo.load(SeqCst));
+ /// assert_eq!(true, foo.fetch_and(true, Ordering::SeqCst));
+ /// assert_eq!(true, foo.load(Ordering::SeqCst));
///
/// let foo = AtomicBool::new(false);
- /// assert_eq!(false, foo.fetch_and(false, SeqCst));
- /// assert_eq!(false, foo.load(SeqCst));
+ /// assert_eq!(false, foo.fetch_and(false, Ordering::SeqCst));
+ /// assert_eq!(false, foo.load(Ordering::SeqCst));
/// ```
#[inline]
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicBool, SeqCst};
+ /// use std::sync::atomic::{AtomicBool, Ordering};
///
/// let foo = AtomicBool::new(true);
- /// assert_eq!(true, foo.fetch_nand(false, SeqCst));
- /// assert_eq!(true, foo.load(SeqCst));
+ /// assert_eq!(true, foo.fetch_nand(false, Ordering::SeqCst));
+ /// assert_eq!(true, foo.load(Ordering::SeqCst));
///
/// let foo = AtomicBool::new(true);
- /// assert_eq!(true, foo.fetch_nand(true, SeqCst));
- /// assert_eq!(0, foo.load(SeqCst) as int);
- /// assert_eq!(false, foo.load(SeqCst));
+ /// assert_eq!(true, foo.fetch_nand(true, Ordering::SeqCst));
+ /// assert_eq!(0, foo.load(Ordering::SeqCst) as int);
+ /// assert_eq!(false, foo.load(Ordering::SeqCst));
///
/// let foo = AtomicBool::new(false);
- /// assert_eq!(false, foo.fetch_nand(false, SeqCst));
- /// assert_eq!(true, foo.load(SeqCst));
+ /// assert_eq!(false, foo.fetch_nand(false, Ordering::SeqCst));
+ /// assert_eq!(true, foo.load(Ordering::SeqCst));
/// ```
#[inline]
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicBool, SeqCst};
+ /// use std::sync::atomic::{AtomicBool, Ordering};
///
/// let foo = AtomicBool::new(true);
- /// assert_eq!(true, foo.fetch_or(false, SeqCst));
- /// assert_eq!(true, foo.load(SeqCst));
+ /// assert_eq!(true, foo.fetch_or(false, Ordering::SeqCst));
+ /// assert_eq!(true, foo.load(Ordering::SeqCst));
///
/// let foo = AtomicBool::new(true);
- /// assert_eq!(true, foo.fetch_or(true, SeqCst));
- /// assert_eq!(true, foo.load(SeqCst));
+ /// assert_eq!(true, foo.fetch_or(true, Ordering::SeqCst));
+ /// assert_eq!(true, foo.load(Ordering::SeqCst));
///
/// let foo = AtomicBool::new(false);
- /// assert_eq!(false, foo.fetch_or(false, SeqCst));
- /// assert_eq!(false, foo.load(SeqCst));
+ /// assert_eq!(false, foo.fetch_or(false, Ordering::SeqCst));
+ /// assert_eq!(false, foo.load(Ordering::SeqCst));
/// ```
#[inline]
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicBool, SeqCst};
+ /// use std::sync::atomic::{AtomicBool, Ordering};
///
/// let foo = AtomicBool::new(true);
- /// assert_eq!(true, foo.fetch_xor(false, SeqCst));
- /// assert_eq!(true, foo.load(SeqCst));
+ /// assert_eq!(true, foo.fetch_xor(false, Ordering::SeqCst));
+ /// assert_eq!(true, foo.load(Ordering::SeqCst));
///
/// let foo = AtomicBool::new(true);
- /// assert_eq!(true, foo.fetch_xor(true, SeqCst));
- /// assert_eq!(false, foo.load(SeqCst));
+ /// assert_eq!(true, foo.fetch_xor(true, Ordering::SeqCst));
+ /// assert_eq!(false, foo.load(Ordering::SeqCst));
///
/// let foo = AtomicBool::new(false);
- /// assert_eq!(false, foo.fetch_xor(false, SeqCst));
- /// assert_eq!(false, foo.load(SeqCst));
+ /// assert_eq!(false, foo.fetch_xor(false, Ordering::SeqCst));
+ /// assert_eq!(false, foo.load(Ordering::SeqCst));
/// ```
#[inline]
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicInt, SeqCst};
+ /// use std::sync::atomic::{AtomicInt, Ordering};
///
/// let foo = AtomicInt::new(0);
- /// assert_eq!(0, foo.fetch_add(10, SeqCst));
- /// assert_eq!(10, foo.load(SeqCst));
+ /// assert_eq!(0, foo.fetch_add(10, Ordering::SeqCst));
+ /// assert_eq!(10, foo.load(Ordering::SeqCst));
/// ```
#[inline]
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicInt, SeqCst};
+ /// use std::sync::atomic::{AtomicInt, Ordering};
///
/// let foo = AtomicInt::new(0);
- /// assert_eq!(0, foo.fetch_sub(10, SeqCst));
- /// assert_eq!(-10, foo.load(SeqCst));
+ /// assert_eq!(0, foo.fetch_sub(10, Ordering::SeqCst));
+ /// assert_eq!(-10, foo.load(Ordering::SeqCst));
/// ```
#[inline]
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicInt, SeqCst};
+ /// use std::sync::atomic::{AtomicInt, Ordering};
///
/// let foo = AtomicInt::new(0b101101);
- /// assert_eq!(0b101101, foo.fetch_and(0b110011, SeqCst));
- /// assert_eq!(0b100001, foo.load(SeqCst));
+ /// assert_eq!(0b101101, foo.fetch_and(0b110011, Ordering::SeqCst));
+ /// assert_eq!(0b100001, foo.load(Ordering::SeqCst));
#[inline]
#[stable]
pub fn fetch_and(&self, val: int, order: Ordering) -> int {
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicInt, SeqCst};
+ /// use std::sync::atomic::{AtomicInt, Ordering};
///
/// let foo = AtomicInt::new(0b101101);
- /// assert_eq!(0b101101, foo.fetch_or(0b110011, SeqCst));
- /// assert_eq!(0b111111, foo.load(SeqCst));
+ /// assert_eq!(0b101101, foo.fetch_or(0b110011, Ordering::SeqCst));
+ /// assert_eq!(0b111111, foo.load(Ordering::SeqCst));
#[inline]
#[stable]
pub fn fetch_or(&self, val: int, order: Ordering) -> int {
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicInt, SeqCst};
+ /// use std::sync::atomic::{AtomicInt, Ordering};
///
/// let foo = AtomicInt::new(0b101101);
- /// assert_eq!(0b101101, foo.fetch_xor(0b110011, SeqCst));
- /// assert_eq!(0b011110, foo.load(SeqCst));
+ /// assert_eq!(0b101101, foo.fetch_xor(0b110011, Ordering::SeqCst));
+ /// assert_eq!(0b011110, foo.load(Ordering::SeqCst));
#[inline]
#[stable]
pub fn fetch_xor(&self, val: int, order: Ordering) -> int {
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicUint, SeqCst};
+ /// use std::sync::atomic::{AtomicUint, Ordering};
///
/// let foo = AtomicUint::new(0);
- /// assert_eq!(0, foo.fetch_add(10, SeqCst));
- /// assert_eq!(10, foo.load(SeqCst));
+ /// assert_eq!(0, foo.fetch_add(10, Ordering::SeqCst));
+ /// assert_eq!(10, foo.load(Ordering::SeqCst));
/// ```
#[inline]
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicUint, SeqCst};
+ /// use std::sync::atomic::{AtomicUint, Ordering};
///
/// let foo = AtomicUint::new(10);
- /// assert_eq!(10, foo.fetch_sub(10, SeqCst));
- /// assert_eq!(0, foo.load(SeqCst));
+ /// assert_eq!(10, foo.fetch_sub(10, Ordering::SeqCst));
+ /// assert_eq!(0, foo.load(Ordering::SeqCst));
/// ```
#[inline]
#[stable]
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicUint, SeqCst};
+ /// use std::sync::atomic::{AtomicUint, Ordering};
///
/// let foo = AtomicUint::new(0b101101);
- /// assert_eq!(0b101101, foo.fetch_and(0b110011, SeqCst));
- /// assert_eq!(0b100001, foo.load(SeqCst));
+ /// assert_eq!(0b101101, foo.fetch_and(0b110011, Ordering::SeqCst));
+ /// assert_eq!(0b100001, foo.load(Ordering::SeqCst));
#[inline]
#[stable]
pub fn fetch_and(&self, val: uint, order: Ordering) -> uint {
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicUint, SeqCst};
+ /// use std::sync::atomic::{AtomicUint, Ordering};
///
/// let foo = AtomicUint::new(0b101101);
- /// assert_eq!(0b101101, foo.fetch_or(0b110011, SeqCst));
- /// assert_eq!(0b111111, foo.load(SeqCst));
+ /// assert_eq!(0b101101, foo.fetch_or(0b110011, Ordering::SeqCst));
+ /// assert_eq!(0b111111, foo.load(Ordering::SeqCst));
#[inline]
#[stable]
pub fn fetch_or(&self, val: uint, order: Ordering) -> uint {
/// # Examples
///
/// ```
- /// use std::sync::atomic::{AtomicUint, SeqCst};
+ /// use std::sync::atomic::{AtomicUint, Ordering};
///
/// let foo = AtomicUint::new(0b101101);
- /// assert_eq!(0b101101, foo.fetch_xor(0b110011, SeqCst));
- /// assert_eq!(0b011110, foo.load(SeqCst));
+ /// assert_eq!(0b101101, foo.fetch_xor(0b110011, Ordering::SeqCst));
+ /// assert_eq!(0b011110, foo.load(Ordering::SeqCst));
#[inline]
#[stable]
pub fn fetch_xor(&self, val: uint, order: Ordering) -> uint {
unsafe { self.value.into_inner() }
}
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> T { self.into_inner() }
-
/// Attempts to immutably borrow the wrapped value.
///
/// The borrow lasts until the returned `Ref` exits scope. Multiple
#[inline]
#[stable]
pub unsafe fn into_inner(self) -> T { self.value }
-
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub unsafe fn unwrap(self) -> T { self.into_inner() }
}
use iter::Iterator;
use mem::transmute;
-use ops::FnMut;
use option::Option::{None, Some};
use option::Option;
use slice::SliceExt;
}
}
-///
-/// Checks if a `char` parses as a numeric digit in the given radix
-///
-/// Compared to `is_numeric()`, this function only recognizes the
-/// characters `0-9`, `a-z` and `A-Z`.
-///
-/// # Return value
-///
-/// Returns `true` if `c` is a valid digit under `radix`, and `false`
-/// otherwise.
-///
-/// # Panics
-///
-/// Panics if given a `radix` > 36.
-///
-/// # Note
-///
-/// This just wraps `to_digit()`.
-///
-#[inline]
-#[deprecated = "use the Char::is_digit method"]
-pub fn is_digit_radix(c: char, radix: uint) -> bool {
- c.is_digit(radix)
-}
-
-///
-/// Converts a `char` to the corresponding digit
-///
-/// # Return value
-///
-/// If `c` is between '0' and '9', the corresponding value
-/// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
-/// 'b' or 'B', 11, etc. Returns none if the `char` does not
-/// refer to a digit in the given radix.
-///
-/// # Panics
-///
-/// Panics if given a `radix` outside the range `[0..36]`.
-///
-#[inline]
-#[deprecated = "use the Char::to_digit method"]
-pub fn to_digit(c: char, radix: uint) -> Option<uint> {
- c.to_digit(radix)
-}
-
///
/// Converts a number to the character representing it
///
}
}
-/// Deprecated, call the escape_unicode method instead.
-#[deprecated = "use the Char::escape_unicode method"]
-pub fn escape_unicode<F>(c: char, mut f: F) where F: FnMut(char) {
- for char in c.escape_unicode() {
- f(char);
- }
-}
-
-/// Deprecated, call the escape_default method instead.
-#[deprecated = "use the Char::escape_default method"]
-pub fn escape_default<F>(c: char, mut f: F) where F: FnMut(char) {
- for c in c.escape_default() {
- f(c);
- }
-}
-
-/// Returns the amount of bytes this `char` would need if encoded in UTF-8
-#[inline]
-#[deprecated = "use the Char::len_utf8 method"]
-pub fn len_utf8_bytes(c: char) -> uint {
- c.len_utf8()
-}
-
/// Basic `char` manipulations.
#[experimental = "trait organization may change"]
pub trait Char {
- /// Checks if a `char` parses as a numeric digit in the given radix.
- ///
- /// Compared to `is_numeric()`, this function only recognizes the characters
- /// `0-9`, `a-z` and `A-Z`.
- ///
- /// # Return value
- ///
- /// Returns `true` if `c` is a valid digit under `radix`, and `false`
- /// otherwise.
- ///
- /// # Panics
- ///
- /// Panics if given a radix > 36.
- #[deprecated = "use is_digit"]
- fn is_digit_radix(self, radix: uint) -> bool;
-
/// Checks if a `char` parses as a numeric digit in the given radix.
///
/// Compared to `is_numeric()`, this function only recognizes the characters
#[unstable = "pending error conventions, trait organization"]
fn to_digit(self, radix: uint) -> Option<uint>;
- /// Converts a number to the character representing it.
- ///
- /// # Return value
- ///
- /// Returns `Some(char)` if `num` represents one digit under `radix`,
- /// using one character of `0-9` or `a-z`, or `None` if it doesn't.
- ///
- /// # Panics
- ///
- /// Panics if given a radix > 36.
- #[deprecated = "use the char::from_digit free function"]
- fn from_digit(num: uint, radix: uint) -> Option<Self>;
-
- /// Converts from `u32` to a `char`
- #[deprecated = "use the char::from_u32 free function"]
- fn from_u32(i: u32) -> Option<char>;
-
/// Returns an iterator that yields the hexadecimal Unicode escape
/// of a character, as `char`s.
///
#[unstable = "pending error conventions, trait organization"]
fn escape_default(self) -> EscapeDefault;
- /// Returns the amount of bytes this character would need if encoded in
- /// UTF-8.
- #[deprecated = "use len_utf8"]
- fn len_utf8_bytes(self) -> uint;
-
/// Returns the amount of bytes this character would need if encoded in
/// UTF-8.
#[unstable = "pending trait organization"]
#[experimental = "trait is experimental"]
impl Char for char {
- #[deprecated = "use is_digit"]
- fn is_digit_radix(self, radix: uint) -> bool { self.is_digit(radix) }
-
#[unstable = "pending trait organization"]
fn is_digit(self, radix: uint) -> bool {
match self.to_digit(radix) {
else { None }
}
- #[deprecated = "use the char::from_digit free function"]
- fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
-
- #[inline]
- #[deprecated = "use the char::from_u32 free function"]
- fn from_u32(i: u32) -> Option<char> { from_u32(i) }
-
#[unstable = "pending error conventions, trait organization"]
fn escape_unicode(self) -> EscapeUnicode {
EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
EscapeDefault { state: init_state }
}
- #[inline]
- #[deprecated = "use len_utf8"]
- fn len_utf8_bytes(self) -> uint { self.len_utf8() }
-
#[inline]
#[unstable = "pending trait organization"]
fn len_utf8(self) -> uint {
/// An iterator over the characters that represent a `char`, as escaped by
/// Rust's unicode escaping rules.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct EscapeUnicode {
c: char,
state: EscapeUnicodeState
}
-#[deriving(Clone)]
+#[derive(Clone)]
enum EscapeUnicodeState {
Backslash,
Type,
/// An iterator over the characters that represent a `char`, escaped
/// for maximum portability.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct EscapeDefault {
state: EscapeDefaultState
}
-#[deriving(Clone)]
+#[derive(Clone)]
enum EscapeDefaultState {
Backslash(char),
Char(char),
use self::Ordering::*;
use kinds::Sized;
-use option::Option::{mod, Some, None};
+use option::Option::{self, Some, None};
/// Trait for equality comparisons which are [partial equivalence relations](
/// http://en.wikipedia.org/wiki/Partial_equivalence_relation).
}
/// An ordering is, e.g, a result of a comparison between two values.
-#[deriving(Clone, Copy, PartialEq, Show)]
+#[derive(Clone, Copy, PartialEq, Show)]
#[stable]
pub enum Ordering {
/// An ordering where a compared value is less [than another].
}
}
-/// The equivalence relation. Two values may be equivalent even if they are
-/// of different types. The most common use case for this relation is
-/// container types; e.g. it is often desirable to be able to use `&str`
-/// values to look up entries in a container with `String` keys.
-#[deprecated = "Use overloaded core::cmp::PartialEq"]
-pub trait Equiv<Sized? T> for Sized? {
- /// Implement this function to decide equivalent values.
- fn equiv(&self, other: &T) -> bool;
-}
-
/// Compare and return the minimum of two values.
#[inline]
#[stable]
//! ```
//! use std::default::Default;
//!
-//! #[deriving(Default)]
+//! #[derive(Default)]
//! struct SomeOptions {
//! foo: int,
//! bar: f32,
//! fn default() -> Kind { Kind::A }
//! }
//!
-//! #[deriving(Default)]
+//! #[derive(Default)]
//! struct SomeOptions {
//! foo: int,
//! bar: f32,
//!
//! ```
//! # use std::default::Default;
-//! # #[deriving(Default)]
+//! # #[derive(Default)]
//! # struct SomeOptions {
//! # foo: int,
//! # bar: f32,
/// A trait that types which have a useful default value should implement.
///
/// A struct can derive default implementations of `Default` for basic types using
-/// `#[deriving(Default)]`.
+/// `#[derive(Default)]`.
///
/// # Examples
///
/// ```
-/// #[deriving(Default)]
+/// #[derive(Default)]
/// struct SomeOptions {
/// foo: int,
/// bar: f32,
use num::FpCategory as Fp;
use ops::FnOnce;
use result::Result::Ok;
-use slice::{mod, SliceExt};
-use str::{mod, StrExt};
+use slice::{self, SliceExt};
+use str::{self, StrExt};
/// A flag that specifies whether to use exponential (scientific) notation.
pub enum ExponentFormat {
use result;
use slice::SliceExt;
use slice;
-use str::{mod, StrExt, Utf8Error};
+use str::{self, StrExt, Utf8Error};
pub use self::num::radix;
pub use self::num::Radix;
/// occurred. Any extra information must be arranged to be transmitted through
/// some other means.
#[experimental = "core and I/O reconciliation may alter this definition"]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Error;
/// A collection of methods that are required to format a message into a stream.
/// compile time it is ensured that the function and the value have the correct
/// types, and then this struct is used to canonicalize arguments to one type.
#[experimental = "implementation detail of the `format_args!` macro"]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Argument<'a> {
value: &'a Void,
formatter: fn(&Void, &mut Formatter) -> Result,
/// macro validates the format string at compile-time so usage of the `write`
/// and `format` functions can be safely performed.
#[stable]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Arguments<'a> {
// Format string pieces to print.
pieces: &'a [&'a str],
}
/// A binary (base 2) radix
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
struct Binary;
/// An octal (base 8) radix
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
struct Octal;
/// A decimal (base 10) radix
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
struct Decimal;
/// A hexadecimal (base 16) radix, formatted with lower-case characters
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
struct LowerHex;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
pub struct UpperHex;
macro_rules! radix {
x @ 10 ... 15 => b'A' + (x - 10) }
/// A radix with in the range of `2..36`.
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
#[unstable = "may be renamed or move to a different module"]
pub struct Radix {
base: u8,
/// A helper type for formatting radixes.
#[unstable = "may be renamed or move to a different module"]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct RadixFmt<T, R>(T, R);
/// Constructs a radix formatter in the range of `2..36`.
pub use self::Flag::*;
#[doc(hidden)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Argument<'a> {
pub position: Position,
pub format: FormatSpec,
}
#[doc(hidden)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct FormatSpec {
pub fill: char,
pub align: Alignment,
}
/// Possible alignments that can be requested as part of a formatting directive.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Alignment {
/// Indication that contents should be left-aligned.
AlignLeft,
}
#[doc(hidden)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Count {
CountIs(uint), CountIsParam(uint), CountIsNextParam, CountImplied,
}
#[doc(hidden)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Position {
ArgumentNext, ArgumentIs(uint)
}
/// These flags are discovered through the `flags` field of the `Formatter`
/// structure. The flag in that structure is a union of these flags into a
/// `uint` where each flag's discriminant is the corresponding bit.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Flag {
/// A flag which enables number formatting to always print the sign of a
/// number.
//! Generic hashing support.
//!
//! This module provides a generic way to compute the hash of a value. The
-//! simplest way to make a type hashable is to use `#[deriving(Hash)]`:
+//! simplest way to make a type hashable is to use `#[derive(Hash)]`:
//!
//! # Examples
//!
//! use std::hash;
//! use std::hash::Hash;
//!
-//! #[deriving(Hash)]
+//! #[derive(Hash)]
//! struct Person {
//! id: uint,
//! name: String,
use super::{Hash, Hasher, Writer};
/// `SipState` computes a SipHash 2-4 hash over a stream of bytes.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct SipState {
k0: u64,
k1: u64,
}
/// `SipHasher` computes the SipHash algorithm from a stream of bytes.
-#[deriving(Clone)]
+#[derive(Clone)]
#[allow(missing_copy_implementations)]
pub struct SipHasher {
k0: u64,
pub type GlueFn = extern "Rust" fn(*const i8);
#[lang="ty_desc"]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct TyDesc {
// sizeof(T)
pub size: uint,
/// `TypeId` represents a globally unique identifier for a type
#[lang="type_id"] // This needs to be kept in lockstep with the code in trans/intrinsic.rs and
// middle/lang_items.rs
-#[deriving(Clone, Copy, PartialEq, Eq, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Show)]
pub struct TypeId {
t: u64,
}
use std::kinds::Sized;
use uint;
-#[deprecated = "renamed to Extend"] pub use self::Extend as Extendable;
-
/// An interface for dealing with "external iterators". These types of iterators
/// can be resumed at any time as all state is stored internally as opposed to
/// being located on the call stack.
impl<A, B> ExactSizeIterator for Zip<A, B> where A: ExactSizeIterator, B: ExactSizeIterator {}
/// An double-ended iterator with the direction inverted
-#[deriving(Clone)]
+#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
pub struct Rev<T> {
}
/// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail.
-#[deriving(Clone, PartialEq, Show)]
+#[derive(Clone, PartialEq, Show)]
#[unstable = "waiting on namespaced enum conventions"]
pub enum MinMaxResult<T> {
/// Empty iterator
/// # Example
///
/// ```rust
- /// use std::iter::MinMaxResult::{mod, NoElements, OneElement, MinMax};
+ /// use std::iter::MinMaxResult::{self, NoElements, OneElement, MinMax};
///
/// let r: MinMaxResult<int> = NoElements;
/// assert_eq!(r.into_option(), None);
}
/// An iterator that repeats endlessly
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
pub struct Cycle<I> {
}
/// An iterator that strings two iterators together
-#[deriving(Clone)]
+#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
pub struct Chain<A, B> {
}
/// An iterator that iterates two other iterators simultaneously
-#[deriving(Clone)]
+#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
pub struct Zip<A, B> {
f: F,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, B, I, F> Clone for Map<A, B, I, F> where
I: Clone + Iterator<Item=A>,
predicate: P,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, I, P> Clone for Filter<A, I, P> where
I: Clone + Iterator<Item=A>,
f: F,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, B, I, F> Clone for FilterMap<A, B, I, F> where
I: Clone + Iterator<Item=A>,
}
/// An iterator that yields the current count and the element during iteration
-#[deriving(Clone)]
+#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
pub struct Enumerate<I> {
/// An iterator with a `peek()` that returns an optional reference to the next element.
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Peekable<T, I> where I: Iterator<Item=T> {
iter: I,
peeked: Option<T>,
predicate: P,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, I, P> Clone for SkipWhile<A, I, P> where
I: Clone + Iterator<Item=A>,
predicate: P,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, I, P> Clone for TakeWhile<A, I, P> where
I: Clone + Iterator<Item=A>,
}
/// An iterator that skips over `n` elements of `iter`.
-#[deriving(Clone)]
+#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
pub struct Skip<I> {
}
/// An iterator that only iterates over the first `n` iterations of `iter`.
-#[deriving(Clone)]
+#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
pub struct Take<I> {
pub state: St,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, B, I, St, F> Clone for Scan<A, B, I, St, F> where
I: Clone + Iterator<Item=A>,
backiter: Option<U>,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, B, I, U, F> Clone for FlatMap<A, B, I, U, F> where
I: Clone + Iterator<Item=A>,
/// An iterator that yields `None` forever after the underlying iterator
/// yields `None` once.
-#[deriving(Clone)]
+#[derive(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
#[stable]
pub struct Fuse<I> {
f: F,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, I, F> Clone for Inspect<A, I, F> where
I: Clone + Iterator<Item=A>,
pub state: St,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<A, St, F> Clone for Unfold<A, St, F> where
F: Clone + FnMut(&mut St) -> Option<A>,
/// An infinite iterator starting at `start` and advancing by `step` with each
/// iteration
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
#[unstable = "may be renamed"]
pub struct Counter<A> {
/// The current state the counter is at (next value to be yielded)
}
/// An iterator over the range [start, stop)
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
#[unstable = "may be refactored due to numerics reform or ops reform"]
pub struct Range<A> {
state: A,
}
/// An iterator over the range [start, stop]
-#[deriving(Clone)]
+#[derive(Clone)]
#[unstable = "may be refactored due to numerics reform or ops reform"]
pub struct RangeInclusive<A> {
range: Range<A>,
}
/// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
-#[deriving(Clone)]
+#[derive(Clone)]
#[unstable = "may be refactored due to numerics reform or ops reform"]
pub struct RangeStep<A> {
state: A,
}
/// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
-#[deriving(Clone)]
+#[derive(Clone)]
#[unstable = "may be refactored due to numerics reform or ops reform"]
pub struct RangeStepInclusive<A> {
state: A,
/// Change self to the previous object.
fn step_back(&mut self);
/// The steps_between two step objects.
- /// a should always be less than b, so the result should never be negative.
+ /// start should always be less than end, so the result should never be negative.
/// Return None if it is not possible to calculate steps_between without
/// overflow.
- fn steps_between(a: &Self, b: &Self) -> Option<uint>;
+ fn steps_between(start: &Self, end: &Self) -> Option<uint>;
}
macro_rules! step_impl {
#[inline]
fn step_back(&mut self) { *self -= 1; }
#[inline]
- fn steps_between(a: &$t, b: &$t) -> Option<uint> {
- debug_assert!(a < b);
- Some((*a - *b) as uint)
+ fn steps_between(start: &$t, end: &$t) -> Option<uint> {
+ debug_assert!(end >= start);
+ Some((*end - *start) as uint)
}
}
)*)
#[inline]
fn step_back(&mut self) { *self -= 1; }
#[inline]
- fn steps_between(_a: &$t, _b: &$t) -> Option<uint> {
+ fn steps_between(_start: &$t, _end: &$t) -> Option<uint> {
None
}
}
/// An iterator that repeats an element endlessly
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct Repeat<A> {
element: A
}
-impl<A: Clone> Repeat<A> {
- /// Create a new `Repeat` that endlessly repeats the element `elt`.
- #[inline]
- #[deprecated = "use iter::repeat instead"]
- pub fn new(elt: A) -> Repeat<A> {
- Repeat{element: elt}
- }
-}
-
#[unstable = "trait is unstable"]
impl<A: Clone> Iterator for Repeat<A> {
type Item = A;
/// (for example, `S<&'static int>` is a subtype of `S<&'a int>`
/// for some lifetime `'a`, but not the other way around).
#[lang="covariant_type"]
- #[deriving(PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct CovariantType<Sized? T>;
impl<Sized? T> Copy for CovariantType<T> {}
/// function requires arguments of type `T`, it must also accept
/// arguments of type `U`, hence such a conversion is safe.
#[lang="contravariant_type"]
- #[deriving(PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct ContravariantType<Sized? T>;
impl<Sized? T> Copy for ContravariantType<T> {}
/// never written, but in fact `Cell` uses unsafe code to achieve
/// interior mutability.
#[lang="invariant_type"]
- #[deriving(PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct InvariantType<Sized? T>;
impl<Sized? T> Copy for InvariantType<T> {}
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
#[lang="covariant_lifetime"]
- #[deriving(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct CovariantLifetime<'a>;
/// As `ContravariantType`, but for lifetime parameters. Using
/// For more information about variance, refer to this Wikipedia
/// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
#[lang="contravariant_lifetime"]
- #[deriving(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ContravariantLifetime<'a>;
/// As `InvariantType`, but for lifetime parameters. Using
/// and this pointer is itself stored in an inherently mutable
/// location (such as a `Cell`).
#[lang="invariant_lifetime"]
- #[deriving(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct InvariantLifetime<'a>;
/// A type which is considered "not sendable", meaning that it cannot
/// typically embedded in other types, such as `Gc`, to ensure that
/// their instances remain thread-local.
#[lang="no_send_bound"]
- #[deriving(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct NoSend;
/// A type which is considered "not POD", meaning that it is not
/// implicitly copyable. This is typically embedded in other types to
/// ensure that they are never copied, even if they lack a destructor.
#[lang="no_copy_bound"]
- #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(missing_copy_implementations)]
pub struct NoCopy;
/// its contents are not threadsafe, hence they cannot be
/// shared between tasks.
#[lang="no_sync_bound"]
- #[deriving(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct NoSync;
/// A type which is considered managed by the GC. This is typically
/// embedded in other types.
#[lang="managed_bound"]
- #[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
+ #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(missing_copy_implementations)]
pub struct Managed;
}
/// A wrapper type for raw pointers and integers that will never be
/// NULL or 0 that might allow certain optimizations.
#[lang="non_zero"]
-#[deriving(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Show)]
+#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Show)]
#[experimental]
pub struct NonZero<T: Zeroable>(T);
use mem;
use num::Float;
use num::FpCategory as Fp;
-use num::from_str_radix;
use option::Option;
#[stable]
unsafe { intrinsics::powf32(self, n) }
}
- /// sqrt(2.0)
- #[inline]
- fn sqrt2() -> f32 { consts::SQRT2 }
-
- /// 1.0 / sqrt(2.0)
- #[inline]
- fn frac_1_sqrt2() -> f32 { consts::FRAC_1_SQRT2 }
-
#[inline]
fn sqrt(self) -> f32 {
if self < 0.0 {
#[inline]
fn rsqrt(self) -> f32 { self.sqrt().recip() }
- /// Archimedes' constant
- #[inline]
- fn pi() -> f32 { consts::PI }
-
- /// 2.0 * pi
- #[inline]
- fn two_pi() -> f32 { consts::PI_2 }
-
- /// pi / 2.0
- #[inline]
- fn frac_pi_2() -> f32 { consts::FRAC_PI_2 }
-
- /// pi / 3.0
- #[inline]
- fn frac_pi_3() -> f32 { consts::FRAC_PI_3 }
-
- /// pi / 4.0
- #[inline]
- fn frac_pi_4() -> f32 { consts::FRAC_PI_4 }
-
- /// pi / 6.0
- #[inline]
- fn frac_pi_6() -> f32 { consts::FRAC_PI_6 }
-
- /// pi / 8.0
- #[inline]
- fn frac_pi_8() -> f32 { consts::FRAC_PI_8 }
-
- /// 1.0 / pi
- #[inline]
- fn frac_1_pi() -> f32 { consts::FRAC_1_PI }
-
- /// 2.0 / pi
- #[inline]
- fn frac_2_pi() -> f32 { consts::FRAC_2_PI }
-
- /// 2.0 / sqrt(pi)
- #[inline]
- fn frac_2_sqrtpi() -> f32 { consts::FRAC_2_SQRTPI }
-
- /// Euler's number
- #[inline]
- fn e() -> f32 { consts::E }
-
- /// log2(e)
- #[inline]
- fn log2_e() -> f32 { consts::LOG2_E }
-
- /// log10(e)
- #[inline]
- fn log10_e() -> f32 { consts::LOG10_E }
-
- /// ln(2.0)
- #[inline]
- fn ln_2() -> f32 { consts::LN_2 }
-
- /// ln(10.0)
- #[inline]
- fn ln_10() -> f32 { consts::LN_10 }
-
/// Returns the exponential of the number.
#[inline]
fn exp(self) -> f32 {
self * (value / 180.0f32)
}
}
-
-#[inline]
-#[allow(missing_docs)]
-#[deprecated="Use `FromStrRadix::from_str_radix(src, 16)`"]
-pub fn from_str_hex(src: &str) -> Option<f32> {
- from_str_radix(src, 16)
-}
use mem;
use num::Float;
use num::FpCategory as Fp;
-use num::from_str_radix;
use option::Option;
// FIXME(#5527): These constants should be deprecated once associated
unsafe { intrinsics::powif64(self, n) }
}
- /// sqrt(2.0)
- #[inline]
- fn sqrt2() -> f64 { consts::SQRT2 }
-
- /// 1.0 / sqrt(2.0)
- #[inline]
- fn frac_1_sqrt2() -> f64 { consts::FRAC_1_SQRT2 }
-
#[inline]
fn sqrt(self) -> f64 {
if self < 0.0 {
#[inline]
fn rsqrt(self) -> f64 { self.sqrt().recip() }
- /// Archimedes' constant
- #[inline]
- fn pi() -> f64 { consts::PI }
-
- /// 2.0 * pi
- #[inline]
- fn two_pi() -> f64 { consts::PI_2 }
-
- /// pi / 2.0
- #[inline]
- fn frac_pi_2() -> f64 { consts::FRAC_PI_2 }
-
- /// pi / 3.0
- #[inline]
- fn frac_pi_3() -> f64 { consts::FRAC_PI_3 }
-
- /// pi / 4.0
- #[inline]
- fn frac_pi_4() -> f64 { consts::FRAC_PI_4 }
-
- /// pi / 6.0
- #[inline]
- fn frac_pi_6() -> f64 { consts::FRAC_PI_6 }
-
- /// pi / 8.0
- #[inline]
- fn frac_pi_8() -> f64 { consts::FRAC_PI_8 }
-
- /// 1.0 / pi
- #[inline]
- fn frac_1_pi() -> f64 { consts::FRAC_1_PI }
-
- /// 2.0 / pi
- #[inline]
- fn frac_2_pi() -> f64 { consts::FRAC_2_PI }
-
- /// 2.0 / sqrt(pi)
- #[inline]
- fn frac_2_sqrtpi() -> f64 { consts::FRAC_2_SQRTPI }
-
- /// Euler's number
- #[inline]
- fn e() -> f64 { consts::E }
-
- /// log2(e)
- #[inline]
- fn log2_e() -> f64 { consts::LOG2_E }
-
- /// log10(e)
- #[inline]
- fn log10_e() -> f64 { consts::LOG10_E }
-
- /// ln(2.0)
- #[inline]
- fn ln_2() -> f64 { consts::LN_2 }
-
- /// ln(10.0)
- #[inline]
- fn ln_10() -> f64 { consts::LN_10 }
-
/// Returns the exponential of the number.
#[inline]
fn exp(self) -> f64 {
self * (value / 180.0)
}
}
-
-#[inline]
-#[allow(missing_docs)]
-#[deprecated="Use `FromStrRadix::from_str_radix(src, 16)`"]
-pub fn from_str_hex(src: &str) -> Option<f64> {
- from_str_radix(src, 16)
-}
#![stable]
#![allow(missing_docs)]
-use {int, i8, i16, i32, i64};
-use {uint, u8, u16, u32, u64};
-use {f32, f64};
use char::Char;
use clone::Clone;
use cmp::{PartialEq, Eq};
use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
use option::Option;
use option::Option::{Some, None};
-use str::{FromStr, from_str, StrExt};
-
-/// Simultaneous division and remainder
-#[inline]
-#[deprecated = "use division and remainder directly"]
-pub fn div_rem<T: Clone + Div<Output=T> + Rem<Output=T>>(x: T, y: T) -> (T, T) {
- (x.clone() / y.clone(), x % y)
-}
-
-/// Raises a `base` to the power of `exp`, using exponentiation by squaring.
-#[inline]
-#[deprecated = "Use Int::pow() instead, as in 2i.pow(4)"]
-pub fn pow<T: Int>(base: T, exp: uint) -> T {
- base.pow(exp)
-}
+use str::{FromStr, StrExt};
/// A built-in signed or unsigned integer.
#[unstable = "recently settled as part of numerics reform"]
impl_num_cast! { f64, to_f64 }
/// Used for representing the classification of floating point numbers
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
#[unstable = "may be renamed"]
pub enum FpCategory {
/// "Not a Number", often obtained by dividing by zero
/// Raise a number to a floating point power.
fn powf(self, n: Self) -> Self;
- /// sqrt(2.0).
- fn sqrt2() -> Self;
- /// 1.0 / sqrt(2.0).
- fn frac_1_sqrt2() -> Self;
-
/// Take the square root of a number.
///
/// Returns NaN if `self` is a negative number.
/// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
fn rsqrt(self) -> Self;
- /// Archimedes' constant.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn pi() -> Self;
- /// 2.0 * pi.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn two_pi() -> Self;
- /// pi / 2.0.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn frac_pi_2() -> Self;
- /// pi / 3.0.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn frac_pi_3() -> Self;
- /// pi / 4.0.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn frac_pi_4() -> Self;
- /// pi / 6.0.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn frac_pi_6() -> Self;
- /// pi / 8.0.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn frac_pi_8() -> Self;
- /// 1.0 / pi.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn frac_1_pi() -> Self;
- /// 2.0 / pi.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn frac_2_pi() -> Self;
- /// 2.0 / sqrt(pi).
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn frac_2_sqrtpi() -> Self;
-
- /// Euler's number.
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn e() -> Self;
- /// log2(e).
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn log2_e() -> Self;
- /// log10(e).
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn log10_e() -> Self;
- /// ln(2.0).
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn ln_2() -> Self;
- /// ln(10.0).
- #[deprecated = "use f32::consts or f64::consts instead"]
- fn ln_10() -> Self;
-
/// Returns `e^(self)`, (the exponential function).
fn exp(self) -> Self;
/// Returns 2 raised to the power of the number, `2^(self)`.
// Parse the exponent as decimal integer
let src = src[offset..];
let (is_positive, exp) = match src.slice_shift_char() {
- Some(('-', src)) => (false, from_str::<uint>(src)),
- Some(('+', src)) => (true, from_str::<uint>(src)),
- Some((_, _)) => (true, from_str::<uint>(src)),
+ Some(('-', src)) => (false, src.parse::<uint>()),
+ Some(('+', src)) => (true, src.parse::<uint>()),
+ Some((_, _)) => (true, src.parse::<uint>()),
None => return None,
};
from_str_radix_int_impl! { u16 }
from_str_radix_int_impl! { u32 }
from_str_radix_int_impl! { u64 }
-
-// DEPRECATED
-
-macro_rules! trait_impl {
- ($name:ident for $($t:ty)*) => {
- $(#[allow(deprecated)] impl $name for $t {})*
- };
-}
-
-#[deprecated = "Generalised numbers are no longer supported"]
-#[allow(deprecated)]
-pub trait Num: PartialEq + Zero + One
- + Neg<Output=Self>
- + Add<Output=Self>
- + Sub<Output=Self>
- + Mul<Output=Self>
- + Div<Output=Self>
- + Rem<Output=Self> {}
-trait_impl! { Num for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
-
-#[deprecated = "Generalised unsigned numbers are no longer supported"]
-#[allow(deprecated)]
-pub trait Unsigned: Num {}
-trait_impl! { Unsigned for uint u8 u16 u32 u64 }
-
-#[deprecated = "Use `Float` or `Int`"]
-#[allow(deprecated)]
-pub trait Primitive: Copy + Clone + Num + NumCast + PartialOrd {}
-trait_impl! { Primitive for uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64 }
-
-#[deprecated = "The generic `Zero` trait will be removed soon."]
-pub trait Zero: Add<Output=Self> {
- #[deprecated = "Use `Int::zero()` or `Float::zero()`."]
- fn zero() -> Self;
- #[deprecated = "Use `x == Int::zero()` or `x == Float::zero()`."]
- fn is_zero(&self) -> bool;
-}
-#[deprecated = "Use `Int::zero()` or `Float::zero()`."]
-#[allow(deprecated)]
-pub fn zero<T: Zero>() -> T { Zero::zero() }
-macro_rules! zero_impl {
- ($t:ty, $v:expr) => {
- impl Zero for $t {
- fn zero() -> $t { $v }
- fn is_zero(&self) -> bool { *self == $v }
- }
- }
-}
-zero_impl! { uint, 0u }
-zero_impl! { u8, 0u8 }
-zero_impl! { u16, 0u16 }
-zero_impl! { u32, 0u32 }
-zero_impl! { u64, 0u64 }
-zero_impl! { int, 0i }
-zero_impl! { i8, 0i8 }
-zero_impl! { i16, 0i16 }
-zero_impl! { i32, 0i32 }
-zero_impl! { i64, 0i64 }
-zero_impl! { f32, 0.0f32 }
-zero_impl! { f64, 0.0f64 }
-
-#[deprecated = "The generic `One` trait will be removed soon."]
-pub trait One: Mul<Output=Self> {
- #[deprecated = "Use `Int::one()` or `Float::one()`."]
- fn one() -> Self;
-}
-#[deprecated = "Use `Int::one()` or `Float::one()`."]
-#[allow(deprecated)]
-pub fn one<T: One>() -> T { One::one() }
-macro_rules! one_impl {
- ($t:ty, $v:expr) => {
- impl One for $t {
- fn one() -> $t { $v }
- }
- }
-}
-one_impl! { uint, 1u }
-one_impl! { u8, 1u8 }
-one_impl! { u16, 1u16 }
-one_impl! { u32, 1u32 }
-one_impl! { u64, 1u64 }
-one_impl! { int, 1i }
-one_impl! { i8, 1i8 }
-one_impl! { i16, 1i16 }
-one_impl! { i32, 1i32 }
-one_impl! { i64, 1i64 }
-one_impl! { f32, 1.0f32 }
-one_impl! { f64, 1.0f64 }
-
-#[deprecated = "Use `UnsignedInt::next_power_of_two`"]
-pub fn next_power_of_two<T: UnsignedInt>(n: T) -> T {
- n.next_power_of_two()
-}
-#[deprecated = "Use `UnsignedInt::is_power_of_two`"]
-pub fn is_power_of_two<T: UnsignedInt>(n: T) -> bool {
- n.is_power_of_two()
-}
-#[deprecated = "Use `UnsignedInt::checked_next_power_of_two`"]
-pub fn checked_next_power_of_two<T: UnsignedInt>(n: T) -> Option<T> {
- n.checked_next_power_of_two()
-}
-
-#[deprecated = "Generalised bounded values are no longer supported"]
-pub trait Bounded {
- #[deprecated = "Use `Int::min_value` or `Float::min_value`"]
- fn min_value() -> Self;
- #[deprecated = "Use `Int::max_value` or `Float::max_value`"]
- fn max_value() -> Self;
-}
-macro_rules! bounded_impl {
- ($T:ty, $min:expr, $max:expr) => {
- impl Bounded for $T {
- #[inline]
- fn min_value() -> $T { $min }
-
- #[inline]
- fn max_value() -> $T { $max }
- }
- };
-}
-bounded_impl! { uint, uint::MIN, uint::MAX }
-bounded_impl! { u8, u8::MIN, u8::MAX }
-bounded_impl! { u16, u16::MIN, u16::MAX }
-bounded_impl! { u32, u32::MIN, u32::MAX }
-bounded_impl! { u64, u64::MIN, u64::MAX }
-bounded_impl! { int, int::MIN, int::MAX }
-bounded_impl! { i8, i8::MIN, i8::MAX }
-bounded_impl! { i16, i16::MIN, i16::MAX }
-bounded_impl! { i32, i32::MIN, i32::MAX }
-bounded_impl! { i64, i64::MIN, i64::MAX }
-bounded_impl! { f32, f32::MIN_VALUE, f32::MAX_VALUE }
-bounded_impl! { f64, f64::MIN_VALUE, f64::MAX_VALUE }
//!
//! use std::ops::{Add, Sub};
//!
-//! #[deriving(Show)]
+//! #[derive(Show)]
//! struct Point {
//! x: int,
//! y: int
use clone::Clone;
use iter::{Step, Iterator,DoubleEndedIterator,ExactSizeIterator};
use kinds::Sized;
-use option::Option::{mod, Some, None};
+use option::Option::{self, Some, None};
/// The `Drop` trait is used to run some code when a value goes out of scope. This
/// is sometimes called a 'destructor'.
///
/// use std::ops::Add;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Add for Foo {
///
/// use std::ops::Sub;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Sub for Foo {
///
/// use std::ops::Mul;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Mul for Foo {
///
/// use std::ops::Div;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Div for Foo {
///
/// use std::ops::Rem;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Rem for Foo {
///
/// use std::ops::BitAnd;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl BitAnd for Foo {
///
/// use std::ops::BitOr;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl BitOr for Foo {
///
/// use std::ops::BitXor;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl BitXor for Foo {
///
/// use std::ops::Shl;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Shl<Foo> for Foo {
///
/// use std::ops::Shr;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Shr<Foo> for Foo {
///
/// use std::ops::Index;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Index<Foo> for Foo {
///
/// use std::ops::IndexMut;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl IndexMut<Foo> for Foo {
/// ```ignore
/// use std::ops::Slice;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl Slice<Foo, Foo> for Foo {
/// ```ignore
/// use std::ops::SliceMut;
///
-/// #[deriving(Copy)]
+/// #[derive(Copy)]
/// struct Foo;
///
/// impl SliceMut<Foo, Foo> for Foo {
/// An unbounded range.
-#[deriving(Copy)]
+#[derive(Copy)]
#[lang="full_range"]
pub struct FullRange;
/// A (half-open) range which is bounded at both ends.
-#[deriving(Copy)]
+#[derive(Copy)]
#[lang="range"]
pub struct Range<Idx> {
/// The lower bound of the range (inclusive).
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
- if let Some(hint) = Step::steps_between(&self.end, &self.start) {
+ if let Some(hint) = Step::steps_between(&self.start, &self.end) {
(hint, Some(hint))
} else {
(0, None)
impl<Idx: Clone + Step> ExactSizeIterator for Range<Idx> {}
/// A range which is only bounded below.
-#[deriving(Copy)]
+#[derive(Copy)]
#[lang="range_from"]
pub struct RangeFrom<Idx> {
/// The lower bound of the range (inclusive).
}
/// A range which is only bounded above.
-#[deriving(Copy)]
+#[derive(Copy)]
#[lang="range_to"]
pub struct RangeTo<Idx> {
/// The upper bound of the range (exclusive).
// which basically means it must be `Option`.
/// The `Option` type.
-#[deriving(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show, Hash)]
+#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show, Hash)]
#[stable]
pub enum Option<T> {
/// No value
// The Option Iterators
/////////////////////////////////////////////////////////////////////////////
-#[deriving(Clone)]
+#[derive(Clone)]
struct Item<A> {
opt: Option<A>
}
pub use iter::{Iterator, DoubleEndedIterator};
pub use iter::{IteratorCloneExt, CloneIteratorExt};
pub use iter::{IteratorOrdExt, ExactSizeIterator};
-pub use option::Option::{mod, Some, None};
+pub use option::Option::{self, Some, None};
pub use ptr::{PtrExt, MutPtrExt};
-pub use result::Result::{mod, Ok, Err};
+pub use result::Result::{self, Ok, Err};
pub use slice::{AsSlice, SliceExt};
pub use str::{Str, StrExt};
use mem;
use clone::Clone;
use intrinsics;
-use option::Option::{mod, Some, None};
+use option::Option::{self, Some, None};
use kinds::{Send, Sized, Sync};
-use cmp::{PartialEq, Eq, Ord, PartialOrd, Equiv};
-use cmp::Ordering::{mod, Less, Equal, Greater};
+use cmp::{PartialEq, Eq, Ord, PartialOrd};
+use cmp::Ordering::{self, Less, Equal, Greater};
// FIXME #19649: instrinsic docs don't render, so these have no docs :(
pub trait PtrExt: Sized {
type Target;
- /// Returns the null pointer.
- #[deprecated = "call ptr::null instead"]
- fn null() -> Self;
-
/// Returns true if the pointer is null.
#[stable]
fn is_null(self) -> bool;
- /// Returns true if the pointer is not equal to the null pointer.
- #[deprecated = "use !p.is_null() instead"]
- fn is_not_null(self) -> bool { !self.is_null() }
-
- /// Returns true if the pointer is not null.
- #[deprecated = "use `as uint` instead"]
- fn to_uint(self) -> uint;
-
/// Returns `None` if the pointer is null, or else returns a reference to
/// the value wrapped in `Some`.
///
impl<T> PtrExt for *const T {
type Target = T;
- #[inline]
- #[deprecated = "call ptr::null instead"]
- fn null() -> *const T { null() }
-
#[inline]
#[stable]
fn is_null(self) -> bool { self as uint == 0 }
- #[inline]
- #[deprecated = "use `as uint` instead"]
- fn to_uint(self) -> uint { self as uint }
-
#[inline]
#[stable]
unsafe fn offset(self, count: int) -> *const T {
impl<T> PtrExt for *mut T {
type Target = T;
- #[inline]
- #[deprecated = "call ptr::null instead"]
- fn null() -> *mut T { null_mut() }
-
#[inline]
#[stable]
fn is_null(self) -> bool { self as uint == 0 }
- #[inline]
- #[deprecated = "use `as uint` instead"]
- fn to_uint(self) -> uint { self as uint }
-
#[inline]
#[stable]
unsafe fn offset(self, count: int) -> *mut T {
#[stable]
impl<T> Eq for *mut T {}
-// Equivalence for pointers
-#[allow(deprecated)]
-#[deprecated = "Use overloaded `core::cmp::PartialEq`"]
-impl<T> Equiv<*mut T> for *const T {
- fn equiv(&self, other: &*mut T) -> bool {
- self.to_uint() == other.to_uint()
- }
-}
-
-#[allow(deprecated)]
-#[deprecated = "Use overloaded `core::cmp::PartialEq`"]
-impl<T> Equiv<*const T> for *mut T {
- fn equiv(&self, other: &*const T) -> bool {
- self.to_uint() == other.to_uint()
- }
-}
-
#[stable]
impl<T> Clone for *const T {
#[inline]
/// The representation of a Rust closure
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Closure {
pub code: *mut (),
pub env: *mut (),
/// This struct does not have a `Repr` implementation
/// because there is no way to refer to all trait objects generically.
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct TraitObject {
pub data: *mut (),
pub vtable: *mut (),
//! defined and used like so:
//!
//! ```
-//! #[deriving(Show)]
+//! #[derive(Show)]
//! enum Version { Version1, Version2 }
//!
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
use fmt::Show;
use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator};
use ops::{FnMut, FnOnce};
-use option::Option::{mod, None, Some};
+use option::Option::{self, None, Some};
use slice::AsSlice;
use slice;
/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
///
/// See the [`std::result`](index.html) module documentation for details.
-#[deriving(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show, Hash)]
+#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show, Hash)]
#[must_use]
#[stable]
pub enum Result<T, E> {
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct i8x16(pub i8, pub i8, pub i8, pub i8,
pub i8, pub i8, pub i8, pub i8,
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct i16x8(pub i16, pub i16, pub i16, pub i16,
pub i16, pub i16, pub i16, pub i16);
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct i32x4(pub i32, pub i32, pub i32, pub i32);
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct i64x2(pub i64, pub i64);
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct u8x16(pub u8, pub u8, pub u8, pub u8,
pub u8, pub u8, pub u8, pub u8,
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct u16x8(pub u16, pub u16, pub u16, pub u16,
pub u16, pub u16, pub u16, pub u16);
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct u32x4(pub u32, pub u32, pub u32, pub u32);
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct u64x2(pub u64, pub u64);
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct f32x4(pub f32, pub f32, pub f32, pub f32);
#[experimental]
#[simd]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
#[repr(C)]
pub struct f64x2(pub f64, pub f64);
use mem::transmute;
use clone::Clone;
-use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord, Equiv};
+use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord};
use cmp::Ordering::{Less, Equal, Greater};
use cmp;
use default::Default;
use iter::*;
use kinds::Copy;
use num::Int;
-use ops::{FnMut, mod};
+use ops::{FnMut, self};
use option::Option;
use option::Option::{None, Some};
use result::Result;
finished: bool
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
#[stable]
impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
fn clone(&self) -> Split<'a, T, P> {
forward_iterator! { RSplitNMut: T, &'a mut [T] }
/// An iterator over overlapping subslices of length `size`.
-#[deriving(Clone)]
+#[derive(Clone)]
#[experimental = "needs review"]
pub struct Windows<'a, T:'a> {
v: &'a [T],
///
/// When the slice len is not evenly divided by the chunk size, the last slice
/// of the iteration will be the remainder.
-#[deriving(Clone)]
+#[derive(Clone)]
#[experimental = "needs review"]
pub struct Chunks<'a, T:'a> {
v: &'a [T],
// Submodules
//
-/// Unsafe operations
-#[deprecated]
-pub mod raw {
- use mem::transmute;
- use ptr::PtrExt;
- use raw::Slice;
- use ops::FnOnce;
- use option::Option;
- use option::Option::{None, Some};
-
- /// Form a slice from a pointer and length (as a number of units,
- /// not bytes).
- #[inline]
- #[deprecated = "renamed to slice::from_raw_buf"]
- pub unsafe fn buf_as_slice<T, U, F>(p: *const T, len: uint, f: F) -> U where
- F: FnOnce(&[T]) -> U,
- {
- f(transmute(Slice {
- data: p,
- len: len
- }))
- }
-
- /// Form a slice from a pointer and length (as a number of units,
- /// not bytes).
- #[inline]
- #[deprecated = "renamed to slice::from_raw_mut_buf"]
- pub unsafe fn mut_buf_as_slice<T, U, F>(p: *mut T, len: uint, f: F) -> U where
- F: FnOnce(&mut [T]) -> U,
- {
- f(transmute(Slice {
- data: p as *const T,
- len: len
- }))
- }
-
- /// Returns a pointer to first element in slice and adjusts
- /// slice so it no longer contains that element. Returns None
- /// if the slice is empty. O(1).
- #[inline]
- #[deprecated = "inspect `Slice::{data, len}` manually (increment data by 1)"]
- pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
- if slice.len == 0 { return None; }
- let head: *const T = slice.data;
- slice.data = slice.data.offset(1);
- slice.len -= 1;
- Some(head)
- }
-
- /// Returns a pointer to last element in slice and adjusts
- /// slice so it no longer contains that element. Returns None
- /// if the slice is empty. O(1).
- #[inline]
- #[deprecated = "inspect `Slice::{data, len}` manually (decrement len by 1)"]
- pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
- if slice.len == 0 { return None; }
- let tail: *const T = slice.data.offset((slice.len - 1) as int);
- slice.len -= 1;
- Some(tail)
- }
-}
-
/// Operations on `[u8]`.
#[experimental = "needs review"]
pub mod bytes {
#[stable]
impl<T: Eq> Eq for [T] {}
-#[allow(deprecated)]
-#[deprecated = "Use overloaded `core::cmp::PartialEq`"]
-impl<T: PartialEq, Sized? V: AsSlice<T>> Equiv<V> for [T] {
- #[inline]
- fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
-}
-
-#[allow(deprecated)]
-#[deprecated = "Use overloaded `core::cmp::PartialEq`"]
-impl<'a,T:PartialEq, Sized? V: AsSlice<T>> Equiv<V> for &'a mut [T] {
- #[inline]
- fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
-}
-
#[stable]
impl<T: Ord> Ord for [T] {
fn cmp(&self, other: &[T]) -> Ordering {
use self::Searcher::{Naive, TwoWay, TwoWayLong};
-use cmp::{mod, Eq};
+use cmp::{self, Eq};
use default::Default;
use iter::range;
use iter::ExactSizeIterator;
use mem;
use num::Int;
use ops::{Fn, FnMut};
-use option::Option::{mod, None, Some};
+use option::Option::{self, None, Some};
use ptr::PtrExt;
use raw::{Repr, Slice};
-use result::Result::{mod, Ok, Err};
-use slice::{mod, SliceExt};
+use result::Result::{self, Ok, Err};
+use slice::{self, SliceExt};
use uint;
macro_rules! delegate_iter {
fn from_str(s: &str) -> Option<Self>;
}
-/// A utility function that just calls FromStr::from_str
-#[deprecated = "call the .parse() method on the string instead"]
-pub fn from_str<A: FromStr>(s: &str) -> Option<A> {
- FromStr::from_str(s)
-}
-
impl FromStr for bool {
/// Parse a `bool` from a string.
///
*/
/// Errors which can occur when attempting to interpret a byte slice as a `str`.
-#[deriving(Copy, Eq, PartialEq, Clone)]
+#[derive(Copy, Eq, PartialEq, Clone)]
pub enum Utf8Error {
/// An invalid byte was detected at the byte offset given.
///
/// Iterator for the char (representing *Unicode Scalar Values*) of a string
///
/// Created with the method `.chars()`.
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct Chars<'a> {
iter: slice::Iter<'a, u8>
}
/// External iterator for a string's characters and their byte offsets.
/// Use with the `std::iter` module.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct CharIndices<'a> {
front_offset: uint,
iter: Chars<'a>,
///
/// Created with `StrExt::bytes`
#[stable]
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Bytes<'a>(Map<&'a u8, u8, slice::Iter<'a, u8>, BytesDeref>);
delegate_iter!{exact u8 in Bytes<'a>}
/// A temporary fn new type that ensures that the `Bytes` iterator
/// is cloneable.
-#[deriving(Copy, Clone)]
+#[derive(Copy, Clone)]
struct BytesDeref;
impl<'a> Fn(&'a u8) -> u8 for BytesDeref {
}
/// An iterator over the substrings of a string, separated by `sep`.
-#[deriving(Clone)]
-#[deprecated = "Type is now named `Split` or `SplitTerminator`"]
-pub struct CharSplits<'a, Sep> {
+#[derive(Clone)]
+struct CharSplits<'a, Sep> {
/// The slice remaining to be iterated
string: &'a str,
sep: Sep,
/// An iterator over the substrings of a string, separated by `sep`,
/// splitting at most `count` times.
-#[deriving(Clone)]
-#[deprecated = "Type is now named `SplitN` or `RSplitN`"]
-pub struct CharSplitsN<'a, Sep> {
+#[derive(Clone)]
+struct CharSplitsN<'a, Sep> {
iter: CharSplits<'a, Sep>,
/// The number of splits remaining
count: uint,
/// The internal state of an iterator that searches for matches of a substring
/// within a larger string using naive search
-#[deriving(Clone)]
+#[derive(Clone)]
struct NaiveSearcher {
position: uint
}
/// The internal state of an iterator that searches for matches of a substring
/// within a larger string using two-way search
-#[deriving(Clone)]
+#[derive(Clone)]
struct TwoWaySearcher {
// constants
crit_pos: uint,
/// The internal state of an iterator that searches for matches of a substring
/// within a larger string using a dynamically chosen search algorithm
-#[deriving(Clone)]
+#[derive(Clone)]
enum Searcher {
Naive(NaiveSearcher),
TwoWay(TwoWaySearcher),
/// An iterator over the start and end indices of the matches of a
/// substring within a larger string
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct MatchIndices<'a> {
// constants
haystack: &'a str,
/// An iterator over the substrings of a string separated by a given
/// search string
-#[deriving(Clone)]
+#[derive(Clone)]
#[unstable = "Type might get removed"]
pub struct SplitStr<'a> {
it: MatchIndices<'a>,
finished: bool
}
-/// Deprecated
-#[deprecated = "Type is now named `SplitStr`"]
-pub type StrSplits<'a> = SplitStr<'a>;
-
impl<'a> Iterator for MatchIndices<'a> {
type Item = (uint, uint);
}
}
-/// Determines if a vector of bytes contains valid UTF-8.
-#[deprecated = "call from_utf8 instead"]
-pub fn is_utf8(v: &[u8]) -> bool {
- run_utf8_validation_iterator(&mut v.iter()).is_ok()
-}
-
-/// Deprecated function
-#[deprecated = "this function will be removed"]
-pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
- match v.iter().position(|c| *c == 0) {
- // don't include the 0
- Some(i) => v[..i],
- None => v
- }
-}
-
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
];
-/// Given a first byte, determine how many bytes are in this UTF-8 character
-#[inline]
-#[deprecated = "this function has moved to libunicode"]
-pub fn utf8_char_width(b: u8) -> uint {
- return UTF8_CHAR_WIDTH[b as uint] as uint;
-}
-
/// Struct that contains a `char` and the index of the first byte of
/// the next `char` in a string. This can be used as a data structure
/// for iterating over the UTF-8 bytes of a string.
-#[deriving(Copy)]
+#[derive(Copy)]
#[unstable = "naming is uncertain with container conventions"]
pub struct CharRange {
/// Current `char`
/// Value of the tag bits (tag mask is !CONT_MASK) of a continuation byte
const TAG_CONT_U8: u8 = 0b1000_0000u8;
-/// Unsafe operations
-#[deprecated]
-pub mod raw {
- use ptr::PtrExt;
- use raw::Slice;
- use slice::SliceExt;
- use str::StrExt;
-
- /// Converts a slice of bytes to a string slice without checking
- /// that the string contains valid UTF-8.
- #[deprecated = "renamed to str::from_utf8_unchecked"]
- pub unsafe fn from_utf8<'a>(v: &'a [u8]) -> &'a str {
- super::from_utf8_unchecked(v)
- }
-
- /// Form a slice from a C string. Unsafe because the caller must ensure the
- /// C string has the static lifetime, or else the return value may be
- /// invalidated later.
- #[deprecated = "renamed to str::from_c_str"]
- pub unsafe fn c_str_to_static_slice(s: *const i8) -> &'static str {
- let s = s as *const u8;
- let mut curr = s;
- let mut len = 0u;
- while *curr != 0u8 {
- len += 1u;
- curr = s.offset(len as int);
- }
- let v = Slice { data: s, len: len };
- super::from_utf8(::mem::transmute(v)).unwrap()
- }
-
- /// Takes a bytewise (not UTF-8) slice from a string.
- ///
- /// Returns the substring from [`begin`..`end`).
- ///
- /// # Panics
- ///
- /// If begin is greater than end.
- /// If end is greater than the length of the string.
- #[inline]
- #[deprecated = "call the slice_unchecked method instead"]
- pub unsafe fn slice_bytes<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
- assert!(begin <= end);
- assert!(end <= s.len());
- s.slice_unchecked(begin, end)
- }
-
- /// Takes a bytewise (not UTF-8) slice from a string.
- ///
- /// Returns the substring from [`begin`..`end`).
- ///
- /// Caller must check slice boundaries!
- #[inline]
- #[deprecated = "this has moved to a method on `str` directly"]
- pub unsafe fn slice_unchecked<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
- s.slice_unchecked(begin, end)
- }
-}
-
/*
Section: Trait implementations
*/
#[allow(missing_docs)]
pub mod traits {
- use cmp::{Ordering, Ord, PartialEq, PartialOrd, Equiv, Eq};
+ use cmp::{Ordering, Ord, PartialEq, PartialOrd, Eq};
use cmp::Ordering::{Less, Equal, Greater};
use iter::IteratorExt;
use option::Option;
use option::Option::Some;
use ops;
- use str::{Str, StrExt, eq_slice};
+ use str::{StrExt, eq_slice};
#[stable]
impl Ord for str {
}
}
- #[allow(deprecated)]
- #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
- impl<S: Str> Equiv<S> for str {
- #[inline]
- fn equiv(&self, other: &S) -> bool { eq_slice(self, other.as_slice()) }
- }
-
impl ops::Slice<uint, str> for str {
#[inline]
fn as_slice_<'a>(&'a self) -> &'a str {
fn as_slice<'a>(&'a self) -> &'a str;
}
-#[allow(deprecated)]
impl Str for str {
#[inline]
fn as_slice<'a>(&'a self) -> &'a str { self }
}
-#[allow(deprecated)]
impl<'a, Sized? S> Str for &'a S where S: Str {
#[inline]
fn as_slice(&self) -> &str { Str::as_slice(*self) }
}
/// Return type of `StrExt::split`
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct Split<'a, P>(CharSplits<'a, P>);
delegate_iter!{pattern &'a str in Split<'a, P>}
/// Return type of `StrExt::split_terminator`
-#[deriving(Clone)]
+#[derive(Clone)]
#[unstable = "might get removed in favour of a constructor method on Split"]
pub struct SplitTerminator<'a, P>(CharSplits<'a, P>);
delegate_iter!{pattern &'a str in SplitTerminator<'a, P>}
/// Return type of `StrExt::splitn`
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct SplitN<'a, P>(CharSplitsN<'a, P>);
delegate_iter!{pattern forward &'a str in SplitN<'a, P>}
/// Return type of `StrExt::rsplitn`
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct RSplitN<'a, P>(CharSplitsN<'a, P>);
delegate_iter!{pattern forward &'a str in RSplitN<'a, P>}
fn as_ptr(&self) -> *const u8;
fn len(&self) -> uint;
fn is_empty(&self) -> bool;
+ fn parse<T: FromStr>(&self) -> Option<T>;
}
#[inline(never)]
}
#[inline]
- #[allow(deprecated)] // For using CharSplits
fn split<P: CharEq>(&self, pat: P) -> Split<P> {
Split(CharSplits {
string: self,
}
#[inline]
- #[allow(deprecated)] // For using CharSplitsN
fn splitn<P: CharEq>(&self, count: uint, pat: P) -> SplitN<P> {
SplitN(CharSplitsN {
iter: self.split(pat).0,
}
#[inline]
- #[allow(deprecated)] // For using CharSplits
fn split_terminator<P: CharEq>(&self, pat: P) -> SplitTerminator<P> {
SplitTerminator(CharSplits {
allow_trailing_empty: false,
}
#[inline]
- #[allow(deprecated)] // For using CharSplitsN
fn rsplitn<P: CharEq>(&self, count: uint, pat: P) -> RSplitN<P> {
RSplitN(CharSplitsN {
iter: self.split(pat).0,
#[inline]
fn is_empty(&self) -> bool { self.len() == 0 }
+
+ #[inline]
+ fn parse<T: FromStr>(&self) -> Option<T> { FromStr::from_str(self) }
}
#[stable]
}
)+) => {
$(
- #[allow(missing_docs)]
- #[deprecated]
- pub trait $Tuple<$($T),+> {
- $(
- #[deprecated = "use tuple indexing: `tuple.N`"]
- fn $valN(self) -> $T;
- #[deprecated = "use tuple indexing: `&tuple.N`"]
- fn $refN<'a>(&'a self) -> &'a $T;
- #[deprecated = "use tuple indexing: `&mut tuple.N`"]
- fn $mutN<'a>(&'a mut self) -> &'a mut $T;
- )+
- }
-
- impl<$($T),+> $Tuple<$($T),+> for ($($T,)+) {
- $(
- #[inline]
- #[allow(unused_variables)]
- #[deprecated = "use tuple indexing: `tuple.N`"]
- fn $valN(self) -> $T {
- e!(self.$idx)
- }
-
- #[inline]
- #[allow(unused_variables)]
- #[deprecated = "use tuple indexing: `&tuple.N`"]
- fn $refN<'a>(&'a self) -> &'a $T {
- e!(&self.$idx)
- }
-
- #[inline]
- #[allow(unused_variables)]
- #[deprecated = "use tuple indexing: &mut tuple.N"]
- fn $mutN<'a>(&'a mut self) -> &'a mut $T {
- e!(&mut self.$idx)
- }
- )+
- }
-
#[stable]
impl<$($T:Clone),+> Clone for ($($T,)+) {
fn clone(&self) -> ($($T,)+) {
use test::Bencher;
use test;
-#[deriving(PartialEq, Show)]
+#[derive(PartialEq, Show)]
struct Test;
static TEST: &'static str = "Test";
//
// ignore-lexer-test FIXME #15679
-use core::char::{escape_unicode, escape_default};
-
#[test]
fn test_is_lowercase() {
assert!('a'.is_lowercase());
#[test]
fn test_is_whitespace() {
assert!(' '.is_whitespace());
- assert!('\u2007'.is_whitespace());
+ assert!('\u{2007}'.is_whitespace());
assert!('\t'.is_whitespace());
assert!('\n'.is_whitespace());
assert!(!'a'.is_whitespace());
assert!(!'_'.is_whitespace());
- assert!(!'\u0000'.is_whitespace());
+ assert!(!'\u{0}'.is_whitespace());
}
#[test]
#[test]
fn test_is_control() {
- assert!('\u0000'.is_control());
- assert!('\u0003'.is_control());
- assert!('\u0006'.is_control());
- assert!('\u0009'.is_control());
- assert!('\u007f'.is_control());
- assert!('\u0092'.is_control());
- assert!(!'\u0020'.is_control());
- assert!(!'\u0055'.is_control());
- assert!(!'\u0068'.is_control());
+ assert!('\u{0}'.is_control());
+ assert!('\u{3}'.is_control());
+ assert!('\u{6}'.is_control());
+ assert!('\u{9}'.is_control());
+ assert!('\u{7f}'.is_control());
+ assert!('\u{92}'.is_control());
+ assert!(!'\u{20}'.is_control());
+ assert!(!'\u{55}'.is_control());
+ assert!(!'\u{68}'.is_control());
}
#[test]
#[test]
fn test_escape_default() {
fn string(c: char) -> String {
- let mut result = String::new();
- escape_default(c, |c| { result.push(c); });
- return result;
+ c.escape_default().collect()
}
let s = string('\n');
assert_eq!(s, "\\n");
}
check('x', &[0x78]);
- check('\u00e9', &[0xc3, 0xa9]);
- check('\ua66e', &[0xea, 0x99, 0xae]);
- check('\U0001f4a9', &[0xf0, 0x9f, 0x92, 0xa9]);
+ check('\u{e9}', &[0xc3, 0xa9]);
+ check('\u{a66e}', &[0xea, 0x99, 0xae]);
+ check('\u{1f4a9}', &[0xf0, 0x9f, 0x92, 0xa9]);
}
#[test]
}
check('x', &[0x0078]);
- check('\u00e9', &[0x00e9]);
- check('\ua66e', &[0xa66e]);
- check('\U0001f4a9', &[0xd83d, 0xdca9]);
+ check('\u{e9}', &[0x00e9]);
+ check('\u{a66e}', &[0xa66e]);
+ check('\u{1f4a9}', &[0xd83d, 0xdca9]);
}
#[test]
fn test_len_utf16() {
assert!('x'.len_utf16() == 1);
- assert!('\u00e9'.len_utf16() == 1);
- assert!('\ua66e'.len_utf16() == 1);
- assert!('\U0001f4a9'.len_utf16() == 2);
+ assert!('\u{e9}'.len_utf16() == 1);
+ assert!('\u{a66e}'.len_utf16() == 1);
+ assert!('\u{1f4a9}'.len_utf16() == 2);
}
#[test]
assert_eq!('h'.width(false),Some(2));
assert_eq!('h'.width(true),Some(2));
- assert_eq!('\u00AD'.width(false),Some(1));
- assert_eq!('\u00AD'.width(true),Some(1));
+ assert_eq!('\u{AD}'.width(false),Some(1));
+ assert_eq!('\u{AD}'.width(true),Some(1));
- assert_eq!('\u1160'.width(false),Some(0));
- assert_eq!('\u1160'.width(true),Some(0));
+ assert_eq!('\u{1160}'.width(false),Some(0));
+ assert_eq!('\u{1160}'.width(true),Some(0));
- assert_eq!('\u00a1'.width(false),Some(1));
- assert_eq!('\u00a1'.width(true),Some(2));
+ assert_eq!('\u{a1}'.width(false),Some(1));
+ assert_eq!('\u{a1}'.width(true),Some(2));
- assert_eq!('\u0300'.width(false),Some(0));
- assert_eq!('\u0300'.width(true),Some(0));
+ assert_eq!('\u{300}'.width(false),Some(0));
+ assert_eq!('\u{300}'.width(true),Some(0));
}
#[test]
fn test_filter_map() {
- let mut it = count(0u, 1u).take(10)
+ let it = count(0u, 1u).take(10)
.filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None });
assert!(it.collect::<Vec<uint>>() == vec![0*0, 2*2, 4*4, 6*6, 8*8]);
}
#[test]
fn test_match_option_string() {
- let five = "Five".into_string();
+ let five = "Five".to_string();
match Some(five) {
Some(s) => assert_eq!(s, "Five"),
None => panic!("unexpected None while matching on Some(String { ... })")
use core::$T_i::*;
use core::int;
use core::num::{FromStrRadix, Int, SignedInt};
- use core::str::from_str;
use core::ops::{Shl, Shr, Not, BitXor, BitAnd, BitOr};
use num;
#[test]
fn test_from_str() {
+ fn from_str<T: ::std::str::FromStr>(t: &str) -> Option<T> {
+ ::std::str::FromStr::from_str(t)
+ }
assert_eq!(from_str::<$T>("0"), Some(0 as $T));
assert_eq!(from_str::<$T>("3"), Some(3 as $T));
assert_eq!(from_str::<$T>("10"), Some(10 as $T));
use core::num::{NumCast, cast};
use core::ops::{Add, Sub, Mul, Div, Rem};
use core::kinds::Copy;
-use std::str::from_str;
mod int_macros;
mod i8;
use core::option::Option::{Some, None};
use core::num::Float;
use core::num::from_str_radix;
- use core::str::from_str;
#[test]
fn from_str_issue7588() {
#[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127_i8;
- assert_eq!(from_str::<i8>("127"), Some(i8_val));
- assert_eq!(from_str::<i8>("128"), None);
+ assert_eq!("127".parse::<i8>(), Some(i8_val));
+ assert_eq!("128".parse::<i8>(), None);
i8_val += 1 as i8;
- assert_eq!(from_str::<i8>("-128"), Some(i8_val));
- assert_eq!(from_str::<i8>("-129"), None);
+ assert_eq!("-128".parse::<i8>(), Some(i8_val));
+ assert_eq!("-129".parse::<i8>(), None);
let mut i16_val: i16 = 32_767_i16;
- assert_eq!(from_str::<i16>("32767"), Some(i16_val));
- assert_eq!(from_str::<i16>("32768"), None);
+ assert_eq!("32767".parse::<i16>(), Some(i16_val));
+ assert_eq!("32768".parse::<i16>(), None);
i16_val += 1 as i16;
- assert_eq!(from_str::<i16>("-32768"), Some(i16_val));
- assert_eq!(from_str::<i16>("-32769"), None);
+ assert_eq!("-32768".parse::<i16>(), Some(i16_val));
+ assert_eq!("-32769".parse::<i16>(), None);
let mut i32_val: i32 = 2_147_483_647_i32;
- assert_eq!(from_str::<i32>("2147483647"), Some(i32_val));
- assert_eq!(from_str::<i32>("2147483648"), None);
+ assert_eq!("2147483647".parse::<i32>(), Some(i32_val));
+ assert_eq!("2147483648".parse::<i32>(), None);
i32_val += 1 as i32;
- assert_eq!(from_str::<i32>("-2147483648"), Some(i32_val));
- assert_eq!(from_str::<i32>("-2147483649"), None);
+ assert_eq!("-2147483648".parse::<i32>(), Some(i32_val));
+ assert_eq!("-2147483649".parse::<i32>(), None);
let mut i64_val: i64 = 9_223_372_036_854_775_807_i64;
- assert_eq!(from_str::<i64>("9223372036854775807"), Some(i64_val));
- assert_eq!(from_str::<i64>("9223372036854775808"), None);
+ assert_eq!("9223372036854775807".parse::<i64>(), Some(i64_val));
+ assert_eq!("9223372036854775808".parse::<i64>(), None);
i64_val += 1 as i64;
- assert_eq!(from_str::<i64>("-9223372036854775808"), Some(i64_val));
- assert_eq!(from_str::<i64>("-9223372036854775809"), None);
+ assert_eq!("-9223372036854775808".parse::<i64>(), Some(i64_val));
+ assert_eq!("-9223372036854775809".parse::<i64>(), None);
}
}
use core::ptr::*;
use core::mem;
+use std::iter::repeat;
#[test]
fn test() {
fn test_is_null() {
let p: *const int = null();
assert!(p.is_null());
- assert!(!p.is_not_null());
let q = unsafe { p.offset(1) };
assert!(!q.is_null());
- assert!(q.is_not_null());
let mp: *mut int = null_mut();
assert!(mp.is_null());
- assert!(!mp.is_not_null());
let mq = unsafe { mp.offset(1) };
assert!(!mq.is_null());
- assert!(mq.is_not_null());
}
#[test]
#[test]
fn test_ptr_addition() {
unsafe {
- let xs = Vec::from_elem(16, 5i);
+ let xs = repeat(5i).take(16).collect::<Vec<_>>();
let mut ptr = xs.as_ptr();
let end = ptr.offset(16);
m_ptr = m_ptr.offset(1);
}
- assert!(xs_mut == Vec::from_elem(16, 10i));
+ assert!(xs_mut == repeat(10i).take(16).collect::<Vec<_>>());
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::str::from_str;
-
#[test]
fn test_bool_from_str() {
- assert_eq!(from_str::<bool>("true"), Some(true));
- assert_eq!(from_str::<bool>("false"), Some(false));
- assert_eq!(from_str::<bool>("not even a boolean"), None);
+ assert_eq!("true".parse(), Some(true));
+ assert_eq!("false".parse(), Some(false));
+ assert_eq!("not even a boolean".parse::<bool>(), None);
}
fn check_contains_all_substrings(s: &str) {
#[test]
fn test_utf16_code_units() {
use unicode::str::Utf16Encoder;
- assert_eq!(Utf16Encoder::new(vec!['é', '\U0001F4A9'].into_iter()).collect::<Vec<u16>>(),
+ assert_eq!(Utf16Encoder::new(vec!['é', '\u{1F4A9}'].into_iter()).collect::<Vec<u16>>(),
vec![0xE9, 0xD83D, 0xDCA9])
}
/// A piece is a portion of the format string which represents the next part
/// to emit. These are emitted as a stream by the `Parser` class.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Piece<'a> {
/// A literal string which should directly be emitted
String(&'a str),
}
/// Representation of an argument specification.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub struct Argument<'a> {
/// Where to find this argument
pub position: Position<'a>,
}
/// Specification for the formatting of an argument in the format string.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub struct FormatSpec<'a> {
/// Optionally specified character to fill alignment with
pub fill: Option<char>,
}
/// Enum describing where an argument for a format can be located.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Position<'a> {
/// The argument will be in the next position. This is the default.
ArgumentNext,
}
/// Enum of alignments which are supported.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Alignment {
/// The value will be aligned to the left.
AlignLeft,
/// Various flags which can be applied to format strings. The meaning of these
/// flags is defined by the formatters themselves.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Flag {
/// A `+` will be used to denote positive numbers.
FlagSignPlus,
/// A count is used for the precision and width parameters of an integer, and
/// can reference either an argument or a literal integer.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Count<'a> {
/// The count is specified explicitly.
CountIs(uint),
use std::result;
/// Name of an option. Either a string or a single char.
-#[deriving(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
pub enum Name {
/// A string representing the long name of an option.
/// For example: "help"
}
/// Describes whether an option has an argument.
-#[deriving(Clone, Copy, PartialEq, Eq)]
+#[derive(Clone, Copy, PartialEq, Eq)]
pub enum HasArg {
/// The option requires an argument.
Yes,
}
/// Describes how often an option may occur.
-#[deriving(Clone, Copy, PartialEq, Eq)]
+#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Occur {
/// The option occurs once.
Req,
}
/// A description of a possible option.
-#[deriving(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
pub struct Opt {
/// Name of the option
pub name: Name,
/// One group of options, e.g., both `-h` and `--help`, along with
/// their shared description and properties.
-#[deriving(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
pub struct OptGroup {
/// Short name of the option, e.g. `h` for a `-h` option
pub short_name: String,
}
/// Describes whether an option is given at all or has a value.
-#[deriving(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
enum Optval {
Val(String),
Given,
/// The result of checking command line arguments. Contains a vector
/// of matches and a vector of free strings.
-#[deriving(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
pub struct Matches {
/// Options that matched
opts: Vec<Opt>,
/// The type returned when the command line does not conform to the
/// expected format. Use the `Show` implementation to output detailed
/// information.
-#[deriving(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
pub enum Fail {
/// The option requires an argument but none was passed.
ArgumentMissing(String),
}
/// The type of failure that occurred.
-#[deriving(Copy, PartialEq, Eq)]
+#[derive(Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum FailType {
ArgumentMissing_,
line
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum SplitWithinState {
A, // leading whitespace, initial state
B, // words
C, // internal and trailing whitespace
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum Whitespace {
Ws, // current char is whitespace
Cr // current char is not whitespace
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum LengthLimit {
UnderLim, // current char makes current substring still fit in limit
OverLim // current char makes current substring no longer fit in limit
//! dot::Id::new(format!("N{}", n)).unwrap()
//! }
//! fn node_label<'b>(&'b self, n: &Nd) -> dot::LabelText<'b> {
-//! dot::LabelStr(self.nodes[*n].as_slice().into_cow())
+//! dot::LabelText::LabelStr(self.nodes[*n].as_slice().into_cow())
//! }
//! fn edge_label<'b>(&'b self, _: &Ed) -> dot::LabelText<'b> {
-//! dot::LabelStr("⊆".into_cow())
+//! dot::LabelText::LabelStr("⊆".into_cow())
//! }
//! }
//!
//! }
//! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
//! let &(i, _) = n;
-//! dot::LabelStr(self.nodes[i].as_slice().into_cow())
+//! dot::LabelText::LabelStr(self.nodes[i].as_slice().into_cow())
//! }
//! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
-//! dot::LabelStr("⊆".into_cow())
+//! dot::LabelText::LabelStr("⊆".into_cow())
//! }
//! }
//!
#![feature(globs, slicing_syntax)]
#![feature(unboxed_closures)]
-pub use self::LabelText::*;
+use self::LabelText::*;
use std::borrow::IntoCow;
use std::io;
-use std::str::CowString;
+use std::string::CowString;
use std::vec::CowVec;
pub mod maybe_owned_vec;
fn target(&'a self, edge: &E) -> N;
}
-#[deriving(Copy, PartialEq, Eq, Show)]
+#[derive(Copy, PartialEq, Eq, Show)]
pub enum RenderOption {
NoEdgeLabels,
NoNodeLabels,
#[cfg(test)]
mod tests {
use self::NodeLabels::*;
- use super::{Id, LabelText, LabelStr, EscStr, Labeller};
- use super::{Nodes, Edges, GraphWalk, render};
+ use super::{Id, Labeller, Nodes, Edges, GraphWalk, render};
+ use super::LabelText::{mod, LabelStr, EscStr};
use std::io::IoResult;
- use std::str;
use std::borrow::IntoCow;
+ use std::iter::repeat;
/// each node is an index in a vector in the graph.
type Node = uint;
fn to_opt_strs(self) -> Vec<Option<&'static str>> {
match self {
UnlabelledNodes(len)
- => Vec::from_elem(len, None).into_iter().collect(),
+ => repeat(None).take(len).collect(),
AllNodesLabelled(lbls)
=> lbls.into_iter().map(
|l|Some(l)).collect(),
pub use self::MaybeOwnedVector::*;
-use std::cmp::{Equiv, Ordering};
+use std::cmp::Ordering;
use std::default::Default;
use std::fmt;
use std::iter::FromIterator;
}
}
-#[allow(deprecated)]
-impl<'a, T: PartialEq> Equiv<[T]> for MaybeOwnedVector<'a, T> {
- fn equiv(&self, other: &[T]) -> bool {
- self.as_slice() == other
- }
-}
-
// The `Vector` trait is provided in the prelude and is implemented on
// both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it
// seamlessly. The other vector related traits from the prelude do
pub type pthread_t = c_ulong;
#[repr(C)]
- #[deriving(Copy)] pub struct glob_t {
+ #[derive(Copy)] pub struct glob_t {
pub gl_pathc: size_t,
pub gl_pathv: *mut *mut c_char,
pub gl_offs: size_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timeval {
+ #[derive(Copy)] pub struct timeval {
pub tv_sec: time_t,
pub tv_usec: suseconds_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timespec {
+ #[derive(Copy)] pub struct timespec {
pub tv_sec: time_t,
pub tv_nsec: c_long,
}
- #[deriving(Copy)] pub enum timezone {}
+ #[derive(Copy)] pub enum timezone {}
pub type sighandler_t = size_t;
}
pub type in_port_t = u16;
pub type in_addr_t = u32;
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr {
+ #[derive(Copy)] pub struct sockaddr {
pub sa_family: sa_family_t,
pub sa_data: [u8; 14],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_storage {
+ #[derive(Copy)] pub struct sockaddr_storage {
pub ss_family: sa_family_t,
pub __ss_align: i64,
pub __ss_pad2: [u8; 112],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in {
+ #[derive(Copy)] pub struct sockaddr_in {
pub sin_family: sa_family_t,
pub sin_port: in_port_t,
pub sin_addr: in_addr,
pub sin_zero: [u8; 8],
}
#[repr(C)]
- #[deriving(Copy)] pub struct in_addr {
+ #[derive(Copy)] pub struct in_addr {
pub s_addr: in_addr_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in6 {
+ #[derive(Copy)] pub struct sockaddr_in6 {
pub sin6_family: sa_family_t,
pub sin6_port: in_port_t,
pub sin6_flowinfo: u32,
pub sin6_scope_id: u32,
}
#[repr(C)]
- #[deriving(Copy)] pub struct in6_addr {
+ #[derive(Copy)] pub struct in6_addr {
pub s6_addr: [u16; 8]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip_mreq {
+ #[derive(Copy)] pub struct ip_mreq {
pub imr_multiaddr: in_addr,
pub imr_interface: in_addr,
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip6_mreq {
+ #[derive(Copy)] pub struct ip6_mreq {
pub ipv6mr_multiaddr: in6_addr,
pub ipv6mr_interface: c_uint,
}
#[repr(C)]
- #[deriving(Copy)] pub struct addrinfo {
+ #[derive(Copy)] pub struct addrinfo {
pub ai_flags: c_int,
pub ai_family: c_int,
pub ai_socktype: c_int,
pub ai_next: *mut addrinfo,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_un {
+ #[derive(Copy)] pub struct sockaddr_un {
pub sun_family: sa_family_t,
pub sun_path: [c_char; 108]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ifaddrs {
+ #[derive(Copy)] pub struct ifaddrs {
pub ifa_next: *mut ifaddrs,
pub ifa_name: *mut c_char,
pub ifa_flags: c_uint,
pub type blkcnt_t = i32;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: dev_t,
pub __pad1: c_short,
pub st_ino: ino_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct pthread_attr_t {
+ #[derive(Copy)] pub struct pthread_attr_t {
pub __size: [u32; 9]
}
}
pub type blkcnt_t = u32;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: c_ulonglong,
pub __pad0: [c_uchar; 4],
pub __st_ino: ino_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct pthread_attr_t {
+ #[derive(Copy)] pub struct pthread_attr_t {
pub __size: [u32; 9]
}
}
pub type blkcnt_t = i32;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: c_ulong,
pub st_pad1: [c_long; 3],
pub st_ino: ino_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct pthread_attr_t {
+ #[derive(Copy)] pub struct pthread_attr_t {
pub __size: [u32; 9]
}
}
pub mod extra {
use types::os::arch::c95::{c_ushort, c_int, c_uchar};
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_ll {
+ #[derive(Copy)] pub struct sockaddr_ll {
pub sll_family: c_ushort,
pub sll_protocol: c_ushort,
pub sll_ifindex: c_int,
pub type blkcnt_t = i64;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: dev_t,
pub st_ino: ino_t,
pub st_nlink: nlink_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct pthread_attr_t {
+ #[derive(Copy)] pub struct pthread_attr_t {
pub __size: [u64; 7]
}
}
pub type blkcnt_t = i64;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: dev_t,
pub st_ino: ino_t,
pub st_mode: mode_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct pthread_attr_t {
+ #[derive(Copy)] pub struct pthread_attr_t {
pub __size: [u64; 8]
}
}
}
pub mod extra {
use types::os::arch::c95::{c_ushort, c_int, c_uchar};
- #[deriving(Copy)] pub struct sockaddr_ll {
+ #[derive(Copy)] pub struct sockaddr_ll {
pub sll_family: c_ushort,
pub sll_protocol: c_ushort,
pub sll_ifindex: c_int,
pub type pthread_t = uintptr_t;
#[repr(C)]
- #[deriving(Copy)] pub struct glob_t {
+ #[derive(Copy)] pub struct glob_t {
pub gl_pathc: size_t,
pub __unused1: size_t,
pub gl_offs: size_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timeval {
+ #[derive(Copy)] pub struct timeval {
pub tv_sec: time_t,
pub tv_usec: suseconds_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timespec {
+ #[derive(Copy)] pub struct timespec {
pub tv_sec: time_t,
pub tv_nsec: c_long,
}
- #[deriving(Copy)] pub enum timezone {}
+ #[derive(Copy)] pub enum timezone {}
pub type sighandler_t = size_t;
}
pub type in_port_t = u16;
pub type in_addr_t = u32;
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr {
+ #[derive(Copy)] pub struct sockaddr {
pub sa_len: u8,
pub sa_family: sa_family_t,
pub sa_data: [u8; 14],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_storage {
+ #[derive(Copy)] pub struct sockaddr_storage {
pub ss_len: u8,
pub ss_family: sa_family_t,
pub __ss_pad1: [u8; 6],
pub __ss_pad2: [u8; 112],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in {
+ #[derive(Copy)] pub struct sockaddr_in {
pub sin_len: u8,
pub sin_family: sa_family_t,
pub sin_port: in_port_t,
pub sin_zero: [u8; 8],
}
#[repr(C)]
- #[deriving(Copy)] pub struct in_addr {
+ #[derive(Copy)] pub struct in_addr {
pub s_addr: in_addr_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in6 {
+ #[derive(Copy)] pub struct sockaddr_in6 {
pub sin6_len: u8,
pub sin6_family: sa_family_t,
pub sin6_port: in_port_t,
pub sin6_scope_id: u32,
}
#[repr(C)]
- #[deriving(Copy)] pub struct in6_addr {
+ #[derive(Copy)] pub struct in6_addr {
pub s6_addr: [u16; 8]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip_mreq {
+ #[derive(Copy)] pub struct ip_mreq {
pub imr_multiaddr: in_addr,
pub imr_interface: in_addr,
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip6_mreq {
+ #[derive(Copy)] pub struct ip6_mreq {
pub ipv6mr_multiaddr: in6_addr,
pub ipv6mr_interface: c_uint,
}
#[repr(C)]
- #[deriving(Copy)] pub struct addrinfo {
+ #[derive(Copy)] pub struct addrinfo {
pub ai_flags: c_int,
pub ai_family: c_int,
pub ai_socktype: c_int,
pub ai_next: *mut addrinfo,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_un {
+ #[derive(Copy)] pub struct sockaddr_un {
pub sun_len: u8,
pub sun_family: sa_family_t,
pub sun_path: [c_char; 104]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ifaddrs {
+ #[derive(Copy)] pub struct ifaddrs {
pub ifa_next: *mut ifaddrs,
pub ifa_name: *mut c_char,
pub ifa_flags: c_uint,
pub type blkcnt_t = i64;
pub type fflags_t = u32;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: dev_t,
pub st_ino: ino_t,
pub st_mode: mode_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
pub type pthread_t = uintptr_t;
#[repr(C)]
- #[deriving(Copy)] pub struct glob_t {
+ #[derive(Copy)] pub struct glob_t {
pub gl_pathc: size_t,
pub __unused1: size_t,
pub gl_offs: size_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timeval {
+ #[derive(Copy)] pub struct timeval {
pub tv_sec: time_t,
pub tv_usec: suseconds_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timespec {
+ #[derive(Copy)] pub struct timespec {
pub tv_sec: time_t,
pub tv_nsec: c_long,
}
- #[deriving(Copy)] pub enum timezone {}
+ #[derive(Copy)] pub enum timezone {}
pub type sighandler_t = size_t;
}
pub type in_port_t = u16;
pub type in_addr_t = u32;
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr {
+ #[derive(Copy)] pub struct sockaddr {
pub sa_len: u8,
pub sa_family: sa_family_t,
pub sa_data: [u8; 14],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_storage {
+ #[derive(Copy)] pub struct sockaddr_storage {
pub ss_len: u8,
pub ss_family: sa_family_t,
pub __ss_pad1: [u8; 6],
pub __ss_pad2: [u8; 112],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in {
+ #[derive(Copy)] pub struct sockaddr_in {
pub sin_len: u8,
pub sin_family: sa_family_t,
pub sin_port: in_port_t,
pub sin_zero: [u8; 8],
}
#[repr(C)]
- #[deriving(Copy)] pub struct in_addr {
+ #[derive(Copy)] pub struct in_addr {
pub s_addr: in_addr_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in6 {
+ #[derive(Copy)] pub struct sockaddr_in6 {
pub sin6_len: u8,
pub sin6_family: sa_family_t,
pub sin6_port: in_port_t,
pub sin6_scope_id: u32,
}
#[repr(C)]
- #[deriving(Copy)] pub struct in6_addr {
+ #[derive(Copy)] pub struct in6_addr {
pub s6_addr: [u16; 8]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip_mreq {
+ #[derive(Copy)] pub struct ip_mreq {
pub imr_multiaddr: in_addr,
pub imr_interface: in_addr,
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip6_mreq {
+ #[derive(Copy)] pub struct ip6_mreq {
pub ipv6mr_multiaddr: in6_addr,
pub ipv6mr_interface: c_uint,
}
#[repr(C)]
- #[deriving(Copy)] pub struct addrinfo {
+ #[derive(Copy)] pub struct addrinfo {
pub ai_flags: c_int,
pub ai_family: c_int,
pub ai_socktype: c_int,
pub ai_next: *mut addrinfo,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_un {
+ #[derive(Copy)] pub struct sockaddr_un {
pub sun_len: u8,
pub sun_family: sa_family_t,
pub sun_path: [c_char; 104]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ifaddrs {
+ #[derive(Copy)] pub struct ifaddrs {
pub ifa_next: *mut ifaddrs,
pub ifa_name: *mut c_char,
pub ifa_flags: c_uint,
pub type fflags_t = u32;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_ino: ino_t,
pub st_nlink: nlink_t,
pub st_dev: dev_t,
pub st_qspare2: int64_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
// pub Note: this is the struct called stat64 in Windows. Not stat,
// nor stati64.
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: dev_t,
pub st_ino: ino_t,
pub st_mode: u16,
// note that this is called utimbuf64 in Windows
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time64_t,
pub modtime: time64_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timeval {
+ #[derive(Copy)] pub struct timeval {
pub tv_sec: c_long,
pub tv_usec: c_long,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timespec {
+ #[derive(Copy)] pub struct timespec {
pub tv_sec: time_t,
pub tv_nsec: c_long,
}
- #[deriving(Copy)] pub enum timezone {}
+ #[derive(Copy)] pub enum timezone {}
}
pub mod bsd44 {
pub type in_port_t = u16;
pub type in_addr_t = u32;
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr {
+ #[derive(Copy)] pub struct sockaddr {
pub sa_family: sa_family_t,
pub sa_data: [u8; 14],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_storage {
+ #[derive(Copy)] pub struct sockaddr_storage {
pub ss_family: sa_family_t,
pub __ss_pad1: [u8; 6],
pub __ss_align: i64,
pub __ss_pad2: [u8; 112],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in {
+ #[derive(Copy)] pub struct sockaddr_in {
pub sin_family: sa_family_t,
pub sin_port: in_port_t,
pub sin_addr: in_addr,
pub sin_zero: [u8; 8],
}
#[repr(C)]
- #[deriving(Copy)] pub struct in_addr {
+ #[derive(Copy)] pub struct in_addr {
pub s_addr: in_addr_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in6 {
+ #[derive(Copy)] pub struct sockaddr_in6 {
pub sin6_family: sa_family_t,
pub sin6_port: in_port_t,
pub sin6_flowinfo: u32,
pub sin6_scope_id: u32,
}
#[repr(C)]
- #[deriving(Copy)] pub struct in6_addr {
+ #[derive(Copy)] pub struct in6_addr {
pub s6_addr: [u16; 8]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip_mreq {
+ #[derive(Copy)] pub struct ip_mreq {
pub imr_multiaddr: in_addr,
pub imr_interface: in_addr,
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip6_mreq {
+ #[derive(Copy)] pub struct ip6_mreq {
pub ipv6mr_multiaddr: in6_addr,
pub ipv6mr_interface: c_uint,
}
#[repr(C)]
- #[deriving(Copy)] pub struct addrinfo {
+ #[derive(Copy)] pub struct addrinfo {
pub ai_flags: c_int,
pub ai_family: c_int,
pub ai_socktype: c_int,
pub ai_next: *mut addrinfo,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_un {
+ #[derive(Copy)] pub struct sockaddr_un {
pub sun_family: sa_family_t,
pub sun_path: [c_char; 108]
}
pub type LPCH = *mut CHAR;
#[repr(C)]
- #[deriving(Copy)] pub struct SECURITY_ATTRIBUTES {
+ #[derive(Copy)] pub struct SECURITY_ATTRIBUTES {
pub nLength: DWORD,
pub lpSecurityDescriptor: LPVOID,
pub bInheritHandle: BOOL,
pub type int64 = i64;
#[repr(C)]
- #[deriving(Copy)] pub struct STARTUPINFO {
+ #[derive(Copy)] pub struct STARTUPINFO {
pub cb: DWORD,
pub lpReserved: LPWSTR,
pub lpDesktop: LPWSTR,
pub type LPSTARTUPINFO = *mut STARTUPINFO;
#[repr(C)]
- #[deriving(Copy)] pub struct PROCESS_INFORMATION {
+ #[derive(Copy)] pub struct PROCESS_INFORMATION {
pub hProcess: HANDLE,
pub hThread: HANDLE,
pub dwProcessId: DWORD,
pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION;
#[repr(C)]
- #[deriving(Copy)] pub struct SYSTEM_INFO {
+ #[derive(Copy)] pub struct SYSTEM_INFO {
pub wProcessorArchitecture: WORD,
pub wReserved: WORD,
pub dwPageSize: DWORD,
pub type LPSYSTEM_INFO = *mut SYSTEM_INFO;
#[repr(C)]
- #[deriving(Copy)] pub struct MEMORY_BASIC_INFORMATION {
+ #[derive(Copy)] pub struct MEMORY_BASIC_INFORMATION {
pub BaseAddress: LPVOID,
pub AllocationBase: LPVOID,
pub AllocationProtect: DWORD,
pub type LPMEMORY_BASIC_INFORMATION = *mut MEMORY_BASIC_INFORMATION;
#[repr(C)]
- #[deriving(Copy)] pub struct OVERLAPPED {
+ #[derive(Copy)] pub struct OVERLAPPED {
pub Internal: *mut c_ulong,
pub InternalHigh: *mut c_ulong,
pub Offset: DWORD,
pub type LPOVERLAPPED = *mut OVERLAPPED;
#[repr(C)]
- #[deriving(Copy)] pub struct FILETIME {
+ #[derive(Copy)] pub struct FILETIME {
pub dwLowDateTime: DWORD,
pub dwHighDateTime: DWORD,
}
pub type LPFILETIME = *mut FILETIME;
#[repr(C)]
- #[deriving(Copy)] pub struct GUID {
+ #[derive(Copy)] pub struct GUID {
pub Data1: DWORD,
pub Data2: WORD,
pub Data3: WORD,
}
#[repr(C)]
- #[deriving(Copy)] pub struct WSAPROTOCOLCHAIN {
+ #[derive(Copy)] pub struct WSAPROTOCOLCHAIN {
pub ChainLen: c_int,
pub ChainEntries: [DWORD; MAX_PROTOCOL_CHAIN as uint],
}
pub type LPWSAPROTOCOLCHAIN = *mut WSAPROTOCOLCHAIN;
#[repr(C)]
- #[deriving(Copy)] pub struct WSAPROTOCOL_INFO {
+ #[derive(Copy)] pub struct WSAPROTOCOL_INFO {
pub dwServiceFlags1: DWORD,
pub dwServiceFlags2: DWORD,
pub dwServiceFlags3: DWORD,
pub type GROUP = c_uint;
#[repr(C)]
- #[deriving(Copy)] pub struct WIN32_FIND_DATAW {
+ #[derive(Copy)] pub struct WIN32_FIND_DATAW {
pub dwFileAttributes: DWORD,
pub ftCreationTime: FILETIME,
pub ftLastAccessTime: FILETIME,
pub type pthread_t = uintptr_t;
#[repr(C)]
- #[deriving(Copy)] pub struct glob_t {
+ #[derive(Copy)] pub struct glob_t {
pub gl_pathc: size_t,
pub __unused1: c_int,
pub gl_offs: size_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timeval {
+ #[derive(Copy)] pub struct timeval {
pub tv_sec: time_t,
pub tv_usec: suseconds_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct timespec {
+ #[derive(Copy)] pub struct timespec {
pub tv_sec: time_t,
pub tv_nsec: c_long,
}
- #[deriving(Copy)] pub enum timezone {}
+ #[derive(Copy)] pub enum timezone {}
pub type sighandler_t = size_t;
}
pub type in_port_t = u16;
pub type in_addr_t = u32;
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr {
+ #[derive(Copy)] pub struct sockaddr {
pub sa_len: u8,
pub sa_family: sa_family_t,
pub sa_data: [u8; 14],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_storage {
+ #[derive(Copy)] pub struct sockaddr_storage {
pub ss_len: u8,
pub ss_family: sa_family_t,
pub __ss_pad1: [u8; 6],
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in {
+ #[derive(Copy)] pub struct sockaddr_in {
pub sin_len: u8,
pub sin_family: sa_family_t,
pub sin_port: in_port_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct in_addr {
+ #[derive(Copy)] pub struct in_addr {
pub s_addr: in_addr_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_in6 {
+ #[derive(Copy)] pub struct sockaddr_in6 {
pub sin6_len: u8,
pub sin6_family: sa_family_t,
pub sin6_port: in_port_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct in6_addr {
+ #[derive(Copy)] pub struct in6_addr {
pub s6_addr: [u16; 8]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip_mreq {
+ #[derive(Copy)] pub struct ip_mreq {
pub imr_multiaddr: in_addr,
pub imr_interface: in_addr,
}
#[repr(C)]
- #[deriving(Copy)] pub struct ip6_mreq {
+ #[derive(Copy)] pub struct ip6_mreq {
pub ipv6mr_multiaddr: in6_addr,
pub ipv6mr_interface: c_uint,
}
#[repr(C)]
- #[deriving(Copy)] pub struct addrinfo {
+ #[derive(Copy)] pub struct addrinfo {
pub ai_flags: c_int,
pub ai_family: c_int,
pub ai_socktype: c_int,
}
#[repr(C)]
- #[deriving(Copy)] pub struct sockaddr_un {
+ #[derive(Copy)] pub struct sockaddr_un {
pub sun_len: u8,
pub sun_family: sa_family_t,
pub sun_path: [c_char; 104]
}
#[repr(C)]
- #[deriving(Copy)] pub struct ifaddrs {
+ #[derive(Copy)] pub struct ifaddrs {
pub ifa_next: *mut ifaddrs,
pub ifa_name: *mut c_char,
pub ifa_flags: c_uint,
pub type blkcnt_t = i32;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: dev_t,
pub st_mode: mode_t,
pub st_nlink: nlink_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct pthread_attr_t {
+ #[derive(Copy)] pub struct pthread_attr_t {
pub __sig: c_long,
pub __opaque: [c_char; 36]
}
}
pub mod extra {
#[repr(C)]
- #[deriving(Copy)] pub struct mach_timebase_info {
+ #[derive(Copy)] pub struct mach_timebase_info {
pub numer: u32,
pub denom: u32,
}
pub type blkcnt_t = i32;
#[repr(C)]
- #[deriving(Copy)] pub struct stat {
+ #[derive(Copy)] pub struct stat {
pub st_dev: dev_t,
pub st_mode: mode_t,
pub st_nlink: nlink_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct utimbuf {
+ #[derive(Copy)] pub struct utimbuf {
pub actime: time_t,
pub modtime: time_t,
}
#[repr(C)]
- #[deriving(Copy)] pub struct pthread_attr_t {
+ #[derive(Copy)] pub struct pthread_attr_t {
pub __sig: c_long,
pub __opaque: [c_char; 56]
}
}
pub mod extra {
#[repr(C)]
- #[deriving(Copy)] pub struct mach_timebase_info {
+ #[derive(Copy)] pub struct mach_timebase_info {
pub numer: u32,
pub denom: u32,
}
use std::ascii::AsciiExt;
use std::cmp;
-#[deriving(Show, Clone)]
+#[derive(Show, Clone)]
pub struct LogDirective {
pub name: Option<String>,
pub level: u32,
}
/// Wraps the log level with fmt implementations.
-#[deriving(Copy, PartialEq, PartialOrd)]
+#[derive(Copy, PartialEq, PartialOrd)]
pub struct LogLevel(pub u32);
impl fmt::Show for LogLevel {
/// A LogRecord is created by the logging macros, and passed as the only
/// argument to Loggers.
-#[deriving(Show)]
+#[derive(Show)]
pub struct LogRecord<'a> {
/// The module path of where the LogRecord originated.
}
#[doc(hidden)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct LogLocation {
pub module_path: &'static str,
pub file: &'static str,
/// [1]: D. J. Bernstein, [*ChaCha, a variant of
/// Salsa20*](http://cr.yp.to/chacha.html)
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct ChaChaRng {
buffer: [u32; STATE_WORDS], // Internal buffer of output
state: [u32; STATE_WORDS], // Initial state
let seed : &[_] = &[0u32; 8];
let mut ra: ChaChaRng = SeedableRng::from_seed(seed);
- let v = Vec::from_fn(16, |_| ra.next_u32());
+ let v = range(0, 16).map(|_| ra.next_u32()).collect::<Vec<_>>();
assert_eq!(v,
vec!(0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653,
0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b,
0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8,
0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2));
- let v = Vec::from_fn(16, |_| ra.next_u32());
+ let v = range(0, 16).map(|_| ra.next_u32()).collect::<Vec<_>>();
assert_eq!(v,
vec!(0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73,
0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32,
/// Generate Normal Random
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
/// College, Oxford
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Exp1(pub f64);
// This could be done via `-rng.gen::<f64>().ln()` but that is slower.
/// let v = exp.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a Exp(2) distribution", v);
/// ```
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Exp {
/// `lambda` stored as `1/lambda`, since this is what we scale by.
lambda_inverse: f64
use {Rng, Rand};
use super::{RandSample, WeightedChoice, Weighted, Sample, IndependentSample};
- #[deriving(PartialEq, Show)]
+ #[derive(PartialEq, Show)]
struct ConstRand(uint);
impl Rand for ConstRand {
fn rand<R: Rng>(_: &mut R) -> ConstRand {
/// Generate Normal Random
/// Samples*](http://www.doornik.com/research/ziggurat.pdf). Nuffield
/// College, Oxford
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct StandardNormal(pub f64);
impl Rand for StandardNormal {
/// let v = normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Normal {
mean: f64,
std_dev: f64,
/// let v = log_normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct LogNormal {
norm: Normal
}
///
/// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
/// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct IsaacRng {
cnt: u32,
rsl: [u32; RAND_SIZE_UINT],
///
/// [1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number
/// generator*](http://www.burtleburtle.net/bob/rand/isaacafa.html)
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Isaac64Rng {
cnt: uint,
rsl: [u64; RAND_SIZE_64],
let seed: &[_] = &[1, 23, 456, 7890, 12345];
let mut ra: IsaacRng = SeedableRng::from_seed(seed);
// Regression test that isaac is actually using the above vector
- let v = Vec::from_fn(10, |_| ra.next_u32());
+ let v = range(0, 10).map(|_| ra.next_u32()).collect::<Vec<_>>();
assert_eq!(v,
vec!(2558573138, 873787463, 263499565, 2103644246, 3595684709,
4203127393, 264982119, 2765226902, 2737944514, 3900253796));
// skip forward to the 10000th number
for _ in range(0u, 10000) { rb.next_u32(); }
- let v = Vec::from_fn(10, |_| rb.next_u32());
+ let v = range(0, 10).map(|_| rb.next_u32()).collect::<Vec<_>>();
assert_eq!(v,
vec!(3676831399, 3183332890, 2834741178, 3854698763, 2717568474,
1576568959, 3507990155, 179069555, 141456972, 2478885421));
let seed: &[_] = &[1, 23, 456, 7890, 12345];
let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
// Regression test that isaac is actually using the above vector
- let v = Vec::from_fn(10, |_| ra.next_u64());
+ let v = range(0, 10).map(|_| ra.next_u64()).collect::<Vec<_>>();
assert_eq!(v,
vec!(547121783600835980, 14377643087320773276, 17351601304698403469,
1238879483818134882, 11952566807690396487, 13970131091560099343,
// skip forward to the 10000th number
for _ in range(0u, 10000) { rb.next_u64(); }
- let v = Vec::from_fn(10, |_| rb.next_u64());
+ let v = range(0, 10).map(|_| rb.next_u64()).collect::<Vec<_>>();
assert_eq!(v,
vec!(18143823860592706164, 8491801882678285927, 2699425367717515619,
17196852593171130876, 2606123525235546165, 15790932315217671084,
/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct ReseedWithDefault;
impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
mod test {
use std::prelude::v1::*;
- use core::iter::order;
+ use core::iter::{order, repeat};
use super::{ReseedingRng, ReseedWithDefault};
use std::default::Default;
use {SeedableRng, Rng};
static FILL_BYTES_V_LEN: uint = 13579;
#[test]
fn test_rng_fill_bytes() {
- let mut v = Vec::from_elem(FILL_BYTES_V_LEN, 0u8);
+ let mut v = repeat(0u8).take(FILL_BYTES_V_LEN).collect::<Vec<_>>();
::test::rng().fill_bytes(v.as_mut_slice());
// Sanity test: if we've gotten here, `fill_bytes` has not infinitely
extern crate test;
use super::SeekableMemWriter;
use std::io;
+ use std::iter::repeat;
use test::Bencher;
#[test]
}
fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) {
- let src: Vec<u8> = Vec::from_elem(len, 5);
+ let src: Vec<u8> = repeat(5).take(len).collect();
b.bytes = (times * len) as u64;
b.iter(|| {
pub mod io;
/// Common data structures
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct Doc<'a> {
pub data: &'a [u8],
pub start: uint,
pub doc: Doc<'a>,
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum EbmlEncoderTag {
EsUint, // 0
EsU64, // 1
EsLabel, // Used only when debugging
}
-#[deriving(Show)]
+#[derive(Show)]
pub enum Error {
IntTooBig(uint),
Expected(String),
)
}
- #[deriving(Copy)]
+ #[derive(Copy)]
pub struct Res {
pub val: uint,
pub next: uint
#[bench]
pub fn vuint_at_A_aligned(b: &mut Bencher) {
- let data = Vec::from_fn(4*100, |i| {
+ let data = range(0, 4*100).map(|i| {
match i % 2 {
0 => 0x80u8,
_ => i as u8,
}
- });
+ }).collect::<Vec<_>>();
let mut sum = 0u;
b.iter(|| {
let mut i = 0;
#[bench]
pub fn vuint_at_A_unaligned(b: &mut Bencher) {
- let data = Vec::from_fn(4*100+1, |i| {
+ let data = range(0, 4*100+1).map(|i| {
match i % 2 {
1 => 0x80u8,
_ => i as u8
}
- });
+ }).collect::<Vec<_>>();
let mut sum = 0u;
b.iter(|| {
let mut i = 1;
#[bench]
pub fn vuint_at_D_aligned(b: &mut Bencher) {
- let data = Vec::from_fn(4*100, |i| {
+ let data = range(0, 4*100).map(|i| {
match i % 4 {
0 => 0x10u8,
3 => i as u8,
_ => 0u8
}
- });
+ }).collect::<Vec<_>>();
let mut sum = 0u;
b.iter(|| {
let mut i = 0;
#[bench]
pub fn vuint_at_D_unaligned(b: &mut Bencher) {
- let data = Vec::from_fn(4*100+1, |i| {
+ let data = range(0, 4*100+1).map(|i| {
match i % 4 {
1 => 0x10u8,
0 => i as u8,
_ => 0u8
}
- });
+ }).collect::<Vec<_>>();
let mut sum = 0u;
b.iter(|| {
let mut i = 1;
type InstIdx = uint;
-#[deriving(Show, Clone)]
+#[derive(Show, Clone)]
pub enum Inst {
// When a Match instruction is executed, the current thread is successful.
Match,
/// All of the data in a compiled expression is wrapped in "MaybeStatic" or
/// "MaybeOwned" types so that a `Program` can be represented as static data.
/// (This makes it convenient and efficient for use with the `regex!` macro.)
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Program {
/// A sequence of instructions.
pub insts: Vec<Inst>,
//
// ignore-lexer-test FIXME #15679
-//! This crate provides a native implementation of regular expressions that is
-//! heavily based on RE2 both in syntax and in implementation. Notably,
-//! backreferences and arbitrary lookahead/lookbehind assertions are not
-//! provided. In return, regular expression searching provided by this package
-//! has excellent worst case performance. The specific syntax supported is
-//! documented further down.
+//! Regular expressions implemented in Rust
//!
-//! This crate's documentation provides some simple examples, describes Unicode
-//! support and exhaustively lists the supported syntax. For more specific
-//! details on the API, please see the documentation for the `Regex` type.
-//!
-//! # First example: find a date
-//!
-//! General use of regular expressions in this package involves compiling an
-//! expression and then using it to search, split or replace text. For example,
-//! to confirm that some text resembles a date:
-//!
-//! ```rust
-//! use regex::Regex;
-//! let re = match Regex::new(r"^\d{4}-\d{2}-\d{2}$") {
-//! Ok(re) => re,
-//! Err(err) => panic!("{}", err),
-//! };
-//! assert_eq!(re.is_match("2014-01-01"), true);
-//! ```
-//!
-//! Notice the use of the `^` and `$` anchors. In this crate, every expression
-//! is executed with an implicit `.*?` at the beginning and end, which allows
-//! it to match anywhere in the text. Anchors can be used to ensure that the
-//! full text matches an expression.
-//!
-//! This example also demonstrates the utility of [raw
-//! strings](../reference.html#character-and-string-literals) in Rust, which
-//! are just like regular strings except they are prefixed with an `r` and do
-//! not process any escape sequences. For example, `"\\d"` is the same
-//! expression as `r"\d"`.
-//!
-//! # The `regex!` macro
-//!
-//! Rust's compile time meta-programming facilities provide a way to write a
-//! `regex!` macro which compiles regular expressions *when your program
-//! compiles*. Said differently, if you only use `regex!` to build regular
-//! expressions in your program, then your program cannot compile with an
-//! invalid regular expression. Moreover, the `regex!` macro compiles the
-//! given expression to native Rust code, which makes it much faster for
-//! searching text.
-//!
-//! Since `regex!` provides compiled regular expressions that are both safer
-//! and faster to use, you should use them whenever possible. The only
-//! requirement for using them is that you have a string literal corresponding
-//! to your expression. Otherwise, it is indistinguishable from an expression
-//! compiled at runtime with `Regex::new`.
-//!
-//! To use the `regex!` macro, you must enable the `phase` feature and import
-//! the `regex_macros` crate as a syntax extension:
-//!
-//! ```rust
-//! #![feature(phase)]
-//! #[phase(plugin)]
-//! extern crate regex_macros;
-//! extern crate regex;
-//!
-//! fn main() {
-//! let re = regex!(r"^\d{4}-\d{2}-\d{2}$");
-//! assert_eq!(re.is_match("2014-01-01"), true);
-//! }
-//! ```
-//!
-//! There are a few things worth mentioning about using the `regex!` macro.
-//! Firstly, the `regex!` macro *only* accepts string *literals*.
-//! Secondly, the `regex` crate *must* be linked with the name `regex` since
-//! the generated code depends on finding symbols in the `regex` crate.
-//!
-//! The only downside of using the `regex!` macro is that it can increase the
-//! size of your program's binary since it generates specialized Rust code.
-//! The extra size probably won't be significant for a small number of
-//! expressions, but 100+ calls to `regex!` will probably result in a
-//! noticeably bigger binary.
-//!
-//! # Example: iterating over capture groups
-//!
-//! This crate provides convenient iterators for matching an expression
-//! repeatedly against a search string to find successive non-overlapping
-//! matches. For example, to find all dates in a string and be able to access
-//! them by their component pieces:
-//!
-//! ```rust
-//! # #![feature(phase)]
-//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
-//! # fn main() {
-//! let re = regex!(r"(\d{4})-(\d{2})-(\d{2})");
-//! let text = "2012-03-14, 2013-01-01 and 2014-07-05";
-//! for cap in re.captures_iter(text) {
-//! println!("Month: {} Day: {} Year: {}",
-//! cap.at(2).unwrap_or(""), cap.at(3).unwrap_or(""),
-//! cap.at(1).unwrap_or(""));
-//! }
-//! // Output:
-//! // Month: 03 Day: 14 Year: 2012
-//! // Month: 01 Day: 01 Year: 2013
-//! // Month: 07 Day: 05 Year: 2014
-//! # }
-//! ```
-//!
-//! Notice that the year is in the capture group indexed at `1`. This is
-//! because the *entire match* is stored in the capture group at index `0`.
-//!
-//! # Example: replacement with named capture groups
-//!
-//! Building on the previous example, perhaps we'd like to rearrange the date
-//! formats. This can be done with text replacement. But to make the code
-//! clearer, we can *name* our capture groups and use those names as variables
-//! in our replacement text:
-//!
-//! ```rust
-//! # #![feature(phase)]
-//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
-//! # fn main() {
-//! let re = regex!(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})");
-//! let before = "2012-03-14, 2013-01-01 and 2014-07-05";
-//! let after = re.replace_all(before, "$m/$d/$y");
-//! assert_eq!(after.as_slice(), "03/14/2012, 01/01/2013 and 07/05/2014");
-//! # }
-//! ```
-//!
-//! The `replace` methods are actually polymorphic in the replacement, which
-//! provides more flexibility than is seen here. (See the documentation for
-//! `Regex::replace` for more details.)
-//!
-//! # Pay for what you use
-//!
-//! With respect to searching text with a regular expression, there are three
-//! questions that can be asked:
-//!
-//! 1. Does the text match this expression?
-//! 2. If so, where does it match?
-//! 3. Where are the submatches?
-//!
-//! Generally speaking, this crate could provide a function to answer only #3,
-//! which would subsume #1 and #2 automatically. However, it can be
-//! significantly more expensive to compute the location of submatches, so it's
-//! best not to do it if you don't need to.
-//!
-//! Therefore, only use what you need. For example, don't use `find` if you
-//! only need to test if an expression matches a string. (Use `is_match`
-//! instead.)
-//!
-//! # Unicode
-//!
-//! This implementation executes regular expressions **only** on sequences of
-//! Unicode code points while exposing match locations as byte indices into the
-//! search string.
-//!
-//! Currently, only naive case folding is supported. Namely, when matching
-//! case insensitively, the characters are first converted to their uppercase
-//! forms and then compared.
-//!
-//! Regular expressions themselves are also **only** interpreted as a sequence
-//! of Unicode code points. This means you can use Unicode characters
-//! directly in your expression:
-//!
-//! ```rust
-//! # #![feature(phase)]
-//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
-//! # fn main() {
-//! let re = regex!(r"(?i)Δ+");
-//! assert_eq!(re.find("ΔδΔ"), Some((0, 6)));
-//! # }
-//! ```
-//!
-//! Finally, Unicode general categories and scripts are available as character
-//! classes. For example, you can match a sequence of numerals, Greek or
-//! Cherokee letters:
-//!
-//! ```rust
-//! # #![feature(phase)]
-//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
-//! # fn main() {
-//! let re = regex!(r"[\pN\p{Greek}\p{Cherokee}]+");
-//! assert_eq!(re.find("abcΔᎠβⅠᏴγδⅡxyz"), Some((3, 23)));
-//! # }
-//! ```
-//!
-//! # Syntax
-//!
-//! The syntax supported in this crate is almost in an exact correspondence
-//! with the syntax supported by RE2.
-//!
-//! ## Matching one character
-//!
-//! <pre class="rust">
-//! . any character except new line (includes new line with s flag)
-//! [xyz] A character class matching either x, y or z.
-//! [^xyz] A character class matching any character except x, y and z.
-//! [a-z] A character class matching any character in range a-z.
-//! \d Perl character class ([0-9])
-//! \D Negated Perl character class ([^0-9])
-//! [:alpha:] ASCII character class ([A-Za-z])
-//! [:^alpha:] Negated ASCII character class ([^A-Za-z])
-//! \pN One letter name Unicode character class
-//! \p{Greek} Unicode character class (general category or script)
-//! \PN Negated one letter name Unicode character class
-//! \P{Greek} negated Unicode character class (general category or script)
-//! </pre>
-//!
-//! Any named character class may appear inside a bracketed `[...]` character
-//! class. For example, `[\p{Greek}\pN]` matches any Greek or numeral
-//! character.
-//!
-//! ## Composites
-//!
-//! <pre class="rust">
-//! xy concatenation (x followed by y)
-//! x|y alternation (x or y, prefer x)
-//! </pre>
-//!
-//! ## Repetitions
-//!
-//! <pre class="rust">
-//! x* zero or more of x (greedy)
-//! x+ one or more of x (greedy)
-//! x? zero or one of x (greedy)
-//! x*? zero or more of x (ungreedy)
-//! x+? one or more of x (ungreedy)
-//! x?? zero or one of x (ungreedy)
-//! x{n,m} at least n x and at most m x (greedy)
-//! x{n,} at least n x (greedy)
-//! x{n} exactly n x
-//! x{n,m}? at least n x and at most m x (ungreedy)
-//! x{n,}? at least n x (ungreedy)
-//! x{n}? exactly n x
-//! </pre>
-//!
-//! ## Empty matches
-//!
-//! <pre class="rust">
-//! ^ the beginning of text (or start-of-line with multi-line mode)
-//! $ the end of text (or end-of-line with multi-line mode)
-//! \A only the beginning of text (even with multi-line mode enabled)
-//! \z only the end of text (even with multi-line mode enabled)
-//! \b a Unicode word boundary (\w on one side and \W, \A, or \z on other)
-//! \B not a Unicode word boundary
-//! </pre>
-//!
-//! ## Grouping and flags
-//!
-//! <pre class="rust">
-//! (exp) numbered capture group (indexed by opening parenthesis)
-//! (?P<name>exp) named (also numbered) capture group (allowed chars: [_0-9a-zA-Z])
-//! (?:exp) non-capturing group
-//! (?flags) set flags within current group
-//! (?flags:exp) set flags for exp (non-capturing)
-//! </pre>
-//!
-//! Flags are each a single character. For example, `(?x)` sets the flag `x`
-//! and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at
-//! the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets
-//! the `x` flag and clears the `y` flag.
-//!
-//! All flags are by default disabled. They are:
-//!
-//! <pre class="rust">
-//! i case insensitive
-//! m multi-line mode: ^ and $ match begin/end of line
-//! s allow . to match \n
-//! U swap the meaning of x* and x*?
-//! </pre>
-//!
-//! Here's an example that matches case insensitively for only part of the
-//! expression:
-//!
-//! ```rust
-//! # #![feature(phase)]
-//! # extern crate regex; #[phase(plugin)] extern crate regex_macros;
-//! # fn main() {
-//! let re = regex!(r"(?i)a+(?-i)b+");
-//! let cap = re.captures("AaAaAbbBBBb").unwrap();
-//! assert_eq!(cap.at(0), Some("AaAaAbb"));
-//! # }
-//! ```
-//!
-//! Notice that the `a+` matches either `a` or `A`, but the `b+` only matches
-//! `b`.
-//!
-//! ## Escape sequences
-//!
-//! <pre class="rust">
-//! \* literal *, works for any punctuation character: \.+*?()|[]{}^$
-//! \a bell (\x07)
-//! \f form feed (\x0C)
-//! \t horizontal tab
-//! \n new line
-//! \r carriage return
-//! \v vertical tab (\x0B)
-//! \123 octal character code (up to three digits)
-//! \x7F hex character code (exactly two digits)
-//! \x{10FFFF} any hex character code corresponding to a Unicode code point
-//! </pre>
-//!
-//! ## Perl character classes (Unicode friendly)
-//!
-//! These classes are based on the definitions provided in
-//! [UTS#18](http://www.unicode.org/reports/tr18/#Compatibility_Properties):
-//!
-//! <pre class="rust">
-//! \d digit (\p{Nd})
-//! \D not digit
-//! \s whitespace (\p{White_Space})
-//! \S not whitespace
-//! \w word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control})
-//! \W not word character
-//! </pre>
-//!
-//! ## ASCII character classes
-//!
-//! <pre class="rust">
-//! [:alnum:] alphanumeric ([0-9A-Za-z])
-//! [:alpha:] alphabetic ([A-Za-z])
-//! [:ascii:] ASCII ([\x00-\x7F])
-//! [:blank:] blank ([\t ])
-//! [:cntrl:] control ([\x00-\x1F\x7F])
-//! [:digit:] digits ([0-9])
-//! [:graph:] graphical ([!-~])
-//! [:lower:] lower case ([a-z])
-//! [:print:] printable ([ -~])
-//! [:punct:] punctuation ([!-/:-@[-`{-~])
-//! [:space:] whitespace ([\t\n\v\f\r ])
-//! [:upper:] upper case ([A-Z])
-//! [:word:] word characters ([0-9A-Za-z_])
-//! [:xdigit:] hex digit ([0-9A-Fa-f])
-//! </pre>
-//!
-//! # Untrusted input
-//!
-//! There are two factors to consider here: untrusted regular expressions and
-//! untrusted search text.
-//!
-//! Currently, there are no counter-measures in place to prevent a malicious
-//! user from writing an expression that may use a lot of resources. One such
-//! example is to repeat counted repetitions: `((a{100}){100}){100}` will try
-//! to repeat the `a` instruction `100^3` times. Essentially, this means it's
-//! very easy for an attacker to exhaust your system's memory if they are
-//! allowed to execute arbitrary regular expressions. A possible solution to
-//! this is to impose a hard limit on the size of a compiled expression, but it
-//! does not yet exist.
-//!
-//! The story is a bit better with untrusted search text, since this crate's
-//! implementation provides `O(nm)` search where `n` is the number of
-//! characters in the search text and `m` is the number of instructions in a
-//! compiled expression.
+//! For official documentation, see the rust-lang/regex crate
#![crate_name = "regex"]
#![crate_type = "rlib"]
///
/// Note that this representation prevents one from reproducing the regex as
/// it was typed. (But it could be used to reproduce an equivalent regex.)
-#[deriving(Show, Clone)]
+#[derive(Show, Clone)]
pub enum Ast {
Nothing,
Literal(char, Flags),
Rep(Box<Ast>, Repeater, Greed),
}
-#[deriving(Show, PartialEq, Clone)]
+#[derive(Show, PartialEq, Clone)]
pub enum Repeater {
ZeroOne,
ZeroMore,
OneMore,
}
-#[deriving(Copy, Show, Clone)]
+#[derive(Copy, Show, Clone)]
pub enum Greed {
Greedy,
Ungreedy,
/// constructing an abstract syntax tree. Its central purpose is to facilitate
/// parsing groups and alternations while also maintaining a stack of flag
/// state.
-#[deriving(Show)]
+#[derive(Show)]
enum BuildAst {
Expr(Ast),
Paren(Flags, uint, String), // '('
use std::borrow::IntoCow;
use std::collections::HashMap;
use std::fmt;
-use std::str::CowString;
+use std::string::CowString;
use compile::Program;
use parse;
}
/// A compiled regular expression
-///
-/// It is represented as either a sequence of bytecode instructions (dynamic)
-/// or as a specialized Rust function (native). It can be used to search, split
-/// or replace text. All searching is done with an implicit `.*?` at the
-/// beginning and end of an expression. To force an expression to match the
-/// whole string (or a prefix or a suffix), you must use an anchor like `^` or
-/// `$` (or `\A` and `\z`).
-///
-/// While this crate will handle Unicode strings (whether in the regular
-/// expression or in the search text), all positions returned are **byte
-/// indices**. Every byte index is guaranteed to be at a Unicode code point
-/// boundary.
-///
-/// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a
-/// compiled regular expression and text to search, respectively.
-///
-/// The only methods that allocate new strings are the string replacement
-/// methods. All other methods (searching and splitting) return borrowed
-/// pointers into the string given.
-///
-/// # Examples
-///
-/// Find the location of a US phone number:
-///
-/// ```rust
-/// # use regex::Regex;
-/// let re = match Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}") {
-/// Ok(re) => re,
-/// Err(err) => panic!("{}", err),
-/// };
-/// assert_eq!(re.find("phone: 111-222-3333"), Some((7, 19)));
-/// ```
-///
-/// You can also use the `regex!` macro to compile a regular expression when
-/// you compile your program:
-///
-/// ```rust
-/// #![feature(phase)]
-/// extern crate regex;
-/// #[phase(plugin)] extern crate regex_macros;
-///
-/// fn main() {
-/// let re = regex!(r"\d+");
-/// assert_eq!(re.find("123 abc"), Some((0, 3)));
-/// }
-/// ```
-///
-/// Given an incorrect regular expression, `regex!` will cause the Rust
-/// compiler to produce a compile time error.
-/// Note that `regex!` will compile the expression to native Rust code, which
-/// makes it much faster when searching text.
-/// More details about the `regex!` macro can be found in the `regex` crate
-/// documentation.
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum Regex {
// The representation of `Regex` is exported to support the `regex!`
// syntax extension. Do not rely on it.
Native(ExNative),
}
-#[deriving(Clone)]
+#[derive(Clone)]
#[doc(hidden)]
pub struct ExDynamic {
original: String,
}
#[doc(hidden)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct ExNative {
#[doc(hidden)]
pub original: &'static str,
}
/// Returns true if and only if the regex matches the string given.
- ///
- /// # Example
- ///
- /// Test if some text contains at least one word with exactly 13
- /// characters:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let text = "I categorically deny having triskaidekaphobia.";
- /// let matched = regex!(r"\b\w{13}\b").is_match(text);
- /// assert!(matched);
- /// # }
- /// ```
pub fn is_match(&self, text: &str) -> bool {
has_match(&exec(self, Exists, text))
}
/// Returns the start and end byte range of the leftmost-first match in
/// `text`. If no match exists, then `None` is returned.
- ///
- /// Note that this should only be used if you want to discover the position
- /// of the match. Testing the existence of a match is faster if you use
- /// `is_match`.
- ///
- /// # Example
- ///
- /// Find the start and end location of the first word with exactly 13
- /// characters:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let text = "I categorically deny having triskaidekaphobia.";
- /// let pos = regex!(r"\b\w{13}\b").find(text);
- /// assert_eq!(pos, Some((2, 15)));
- /// # }
- /// ```
pub fn find(&self, text: &str) -> Option<(uint, uint)> {
let caps = exec(self, Location, text);
if has_match(&caps) {
/// Returns an iterator for each successive non-overlapping match in
/// `text`, returning the start and end byte indices with respect to
/// `text`.
- ///
- /// # Example
- ///
- /// Find the start and end location of every word with exactly 13
- /// characters:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let text = "Retroactively relinquishing remunerations is reprehensible.";
- /// for pos in regex!(r"\b\w{13}\b").find_iter(text) {
- /// println!("{}", pos);
- /// }
- /// // Output:
- /// // (0, 13)
- /// // (14, 27)
- /// // (28, 41)
- /// // (45, 58)
- /// # }
- /// ```
pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> {
FindMatches {
re: self,
/// You should only use `captures` if you need access to submatches.
/// Otherwise, `find` is faster for discovering the location of the overall
/// match.
- ///
- /// # Examples
- ///
- /// Say you have some text with movie names and their release years,
- /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text
- /// looking like that, while also extracting the movie name and its release
- /// year separately.
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let re = regex!(r"'([^']+)'\s+\((\d{4})\)");
- /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
- /// let caps = re.captures(text).unwrap();
- /// assert_eq!(caps.at(1), Some("Citizen Kane"));
- /// assert_eq!(caps.at(2), Some("1941"));
- /// assert_eq!(caps.at(0), Some("'Citizen Kane' (1941)"));
- /// # }
- /// ```
- ///
- /// Note that the full match is at capture group `0`. Each subsequent
- /// capture group is indexed by the order of its opening `(`.
- ///
- /// We can make this example a bit clearer by using *named* capture groups:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)");
- /// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
- /// let caps = re.captures(text).unwrap();
- /// assert_eq!(caps.name("title"), Some("Citizen Kane"));
- /// assert_eq!(caps.name("year"), Some("1941"));
- /// assert_eq!(caps.at(0), Some("'Citizen Kane' (1941)"));
- /// # }
- /// ```
- ///
- /// Here we name the capture groups, which we can access with the `name`
- /// method. Note that the named capture groups are still accessible with
- /// `at`.
- ///
- /// The `0`th capture group is always unnamed, so it must always be
- /// accessed with `at(0)`.
pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
let caps = exec(self, Submatches, text);
Captures::new(self, text, caps)
/// Returns an iterator over all the non-overlapping capture groups matched
/// in `text`. This is operationally the same as `find_iter` (except it
/// yields information about submatches).
- ///
- /// # Example
- ///
- /// We can use this to find all movie titles and their release years in
- /// some text, where the movie is formatted like "'Title' (xxxx)":
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let re = regex!(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)");
- /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
- /// for caps in re.captures_iter(text) {
- /// println!("Movie: {}, Released: {}", caps.name("title"), caps.name("year"));
- /// }
- /// // Output:
- /// // Movie: Citizen Kane, Released: 1941
- /// // Movie: The Wizard of Oz, Released: 1939
- /// // Movie: M, Released: 1931
- /// # }
- /// ```
pub fn captures_iter<'r, 't>(&'r self, text: &'t str)
-> FindCaptures<'r, 't> {
FindCaptures {
/// matched by the regular expression.
///
/// This method will *not* copy the text given.
- ///
- /// # Example
- ///
- /// To split a string delimited by arbitrary amounts of spaces or tabs:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let re = regex!(r"[ \t]+");
- /// let fields: Vec<&str> = re.split("a b \t c\td e").collect();
- /// assert_eq!(fields, vec!("a", "b", "c", "d", "e"));
- /// # }
- /// ```
pub fn split<'r, 't>(&'r self, text: &'t str) -> RegexSplits<'r, 't> {
RegexSplits {
finder: self.find_iter(text),
/// in the iterator.
///
/// This method will *not* copy the text given.
- ///
- /// # Example
- ///
- /// Get the first two words in some text:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let re = regex!(r"\W+");
- /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect();
- /// assert_eq!(fields, vec!("Hey", "How", "are you?"));
- /// # }
- /// ```
pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: uint)
-> RegexSplitsN<'r, 't> {
RegexSplitsN {
/// `Captures` and returns the replaced string.
///
/// If no match is found, then a copy of the string is returned unchanged.
- ///
- /// # Examples
- ///
- /// Note that this function is polymorphic with respect to the replacement.
- /// In typical usage, this can just be a normal string:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let re = regex!("[^01]+");
- /// assert_eq!(re.replace("1078910", ""), "1010");
- /// # }
- /// ```
- ///
- /// But anything satisfying the `Replacer` trait will work. For example,
- /// a closure of type `|&Captures| -> String` provides direct access to the
- /// captures corresponding to a match. This allows one to access
- /// submatches easily:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # #![feature(unboxed_closures)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # use regex::Captures; fn main() {
- /// let re = regex!(r"([^,\s]+),\s+(\S+)");
- /// let result = re.replace("Springsteen, Bruce", |&: caps: &Captures| {
- /// format!("{} {}", caps.at(2).unwrap_or(""), caps.at(1).unwrap_or(""))
- /// });
- /// assert_eq!(result, "Bruce Springsteen");
- /// # }
- /// ```
- ///
- /// But this is a bit cumbersome to use all the time. Instead, a simple
- /// syntax is supported that expands `$name` into the corresponding capture
- /// group. Here's the last example, but using this expansion technique
- /// with named capture groups:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// let re = regex!(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)");
- /// let result = re.replace("Springsteen, Bruce", "$first $last");
- /// assert_eq!(result, "Bruce Springsteen");
- /// # }
- /// ```
- ///
- /// Note that using `$2` instead of `$first` or `$1` instead of `$last`
- /// would produce the same result. To write a literal `$` use `$$`.
- ///
- /// Finally, sometimes you just want to replace a literal string with no
- /// submatch expansion. This can be done by wrapping a string with
- /// `NoExpand`:
- ///
- /// ```rust
- /// # #![feature(phase)]
- /// # extern crate regex; #[phase(plugin)] extern crate regex_macros;
- /// # fn main() {
- /// use regex::NoExpand;
- ///
- /// let re = regex!(r"(?P<last>[^,\s]+),\s+(\S+)");
- /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last"));
- /// assert_eq!(result, "$2 $last");
- /// # }
- /// ```
pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> String {
self.replacen(text, 1, rep)
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum NamesIter<'a> {
NamesIterNative(::std::slice::Iter<'a, Option<&'static str>>),
NamesIterDynamic(::std::slice::Iter<'a, Option<String>>)
///
/// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
/// of the string being split.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct RegexSplits<'r, 't> {
finder: FindMatches<'r, 't>,
last: uint,
///
/// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
/// of the string being split.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct RegexSplitsN<'r, 't> {
splits: RegexSplits<'r, 't>,
cur: uint,
/// expression.
///
/// `'t` is the lifetime of the matched text.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct SubCaptures<'t> {
idx: uint,
caps: &'t Captures<'t>,
/// Positions are byte indices in terms of the original string matched.
///
/// `'t` is the lifetime of the matched text.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct SubCapturesPos<'t> {
idx: uint,
caps: &'t Captures<'t>,
///
/// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
/// of the matched string.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct FindCaptures<'r, 't> {
re: &'r Regex,
search: &'t str,
///
/// `'r` is the lifetime of the compiled expression and `'t` is the lifetime
/// of the matched string.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct FindMatches<'r, 't> {
re: &'r Regex,
search: &'t str,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#[cfg(not(stage1))]
-#[phase(plugin)]
-extern crate regex_macros;
-
-#[cfg(not(stage1))]
-#[path = "bench.rs"]
-mod native_bench;
-
-#[cfg(not(stage1))]
-#[path = "tests.rs"]
-mod native_tests;
-
-#[cfg(not(stage1))]
-mod native_static;
-
-// Due to macro scoping rules, this definition only applies for the modules
-// defined below. Effectively, it allows us to use the same tests for both
-// native and dynamic regexes.
macro_rules! regex {
($re:expr) => (
match ::regex::Regex::new($re) {
pub use self::StepState::*;
use std::cmp;
-use std::cmp::Ordering::{mod, Less, Equal, Greater};
+use std::cmp::Ordering::{self, Less, Equal, Greater};
use std::mem;
use std::iter::repeat;
use std::slice::SliceExt;
pub type CaptureLocs = Vec<Option<uint>>;
/// Indicates the type of match to be performed by the VM.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum MatchKind {
/// Only checks if a match exists or not. Does not return location.
Exists,
/// Indicates the next action to take after a single non-empty instruction
/// is processed.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum StepState {
/// This is returned if and only if a Match instruction is reached and
/// we only care about the existence of a match. It instructs the VM to
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! This crate provides the `regex!` macro. Its use is documented in the
-//! `regex` crate.
-
-#![crate_name = "regex_macros"]
-#![crate_type = "dylib"]
-#![experimental = "use the crates.io `regex_macros` library instead"]
-#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
- html_favicon_url = "http://www.rust-lang.org/favicon.ico",
- html_root_url = "http://doc.rust-lang.org/nightly/")]
-
-#![feature(plugin_registrar, quote)]
-#![feature(unboxed_closures)]
-
-extern crate regex;
-extern crate syntax;
-extern crate rustc;
-
-use std::rc::Rc;
-
-use syntax::ast;
-use syntax::codemap;
-use syntax::ext::build::AstBuilder;
-use syntax::ext::base::{ExtCtxt, MacResult, MacExpr, DummyResult};
-use syntax::parse::token;
-use syntax::print::pprust;
-use syntax::fold::Folder;
-use syntax::ptr::P;
-
-use rustc::plugin::Registry;
-
-use regex::Regex;
-use regex::native::{
- OneChar, CharClass, Any, Save, Jump, Split,
- Match, EmptyBegin, EmptyEnd, EmptyWordBoundary,
- Program, Dynamic, ExDynamic, Native,
- FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_NEGATED,
-};
-
-/// For the `regex!` syntax extension. Do not use.
-#[plugin_registrar]
-#[doc(hidden)]
-pub fn plugin_registrar(reg: &mut Registry) {
- reg.register_macro("regex", native);
-}
-
-/// Generates specialized code for the Pike VM for a particular regular
-/// expression.
-///
-/// There are two primary differences between the code generated here and the
-/// general code in vm.rs.
-///
-/// 1. All heap allocation is removed. Sized vector types are used instead.
-/// Care must be taken to make sure that these vectors are not copied
-/// gratuitously. (If you're not sure, run the benchmarks. They will yell
-/// at you if you do.)
-/// 2. The main `match instruction { ... }` expressions are replaced with more
-/// direct `match pc { ... }`. The generators can be found in
-/// `step_insts` and `add_insts`.
-///
-/// Other more minor changes include eliding code when possible (although this
-/// isn't completely thorough at the moment), and translating character class
-/// matching from using a binary search to a simple `match` expression (see
-/// `match_class`).
-///
-/// It is strongly recommended to read the dynamic implementation in vm.rs
-/// first before trying to understand the code generator. The implementation
-/// strategy is identical and vm.rs has comments and will be easier to follow.
-#[allow(experimental)]
-fn native(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree])
- -> Box<MacResult+'static> {
- let regex = match parse(cx, tts) {
- Some(r) => r,
- // error is logged in 'parse' with cx.span_err
- None => return DummyResult::any(sp),
- };
- let re = match Regex::new(regex.as_slice()) {
- Ok(re) => re,
- Err(err) => {
- cx.span_err(sp, err.to_string().as_slice());
- return DummyResult::any(sp)
- }
- };
- let prog = match re {
- Dynamic(ExDynamic { ref prog, .. }) => prog.clone(),
- Native(_) => unreachable!(),
- };
-
- let mut gen = NfaGen {
- cx: &*cx, sp: sp, prog: prog,
- names: re.names_iter().collect(), original: re.as_str().to_string(),
- };
- MacExpr::new(gen.code())
-}
-
-struct NfaGen<'a> {
- cx: &'a ExtCtxt<'a>,
- sp: codemap::Span,
- prog: Program,
- names: Vec<Option<String>>,
- original: String,
-}
-
-impl<'a> NfaGen<'a> {
- fn code(&mut self) -> P<ast::Expr> {
- // Most or all of the following things are used in the quasiquoted
- // expression returned.
- let num_cap_locs = 2 * self.prog.num_captures();
- let num_insts = self.prog.insts.len();
- let cap_names = self.vec_expr(self.names.iter(),
- |cx, name| match *name {
- Some(ref name) => {
- let name = name.as_slice();
- quote_expr!(cx, Some($name))
- }
- None => cx.expr_none(self.sp),
- }
- );
- let prefix_anchor =
- match self.prog.insts[1] {
- EmptyBegin(flags) if flags & FLAG_MULTI == 0 => true,
- _ => false,
- };
- let init_groups = self.vec_expr(range(0, num_cap_locs),
- |cx, _| cx.expr_none(self.sp));
-
- let prefix_lit = Rc::new(self.prog.prefix.as_bytes().to_vec());
- let prefix_bytes = self.cx.expr_lit(self.sp, ast::LitBinary(prefix_lit));
-
- let check_prefix = self.check_prefix();
- let step_insts = self.step_insts();
- let add_insts = self.add_insts();
- let regex = self.original.as_slice();
-
- quote_expr!(self.cx, {
-// When `regex!` is bound to a name that is not used, we have to make sure
-// that dead_code warnings don't bubble up to the user from the generated
-// code. Therefore, we suppress them by allowing dead_code. The effect is that
-// the user is only warned about *their* unused variable/code, and not the
-// unused code generated by regex!. See #14185 for an example.
-#[allow(dead_code)]
-static CAP_NAMES: &'static [Option<&'static str>] = &$cap_names;
-
-#[allow(dead_code)]
-fn exec<'t>(which: ::regex::native::MatchKind, input: &'t str,
- start: uint, end: uint) -> Vec<Option<uint>> {
- #![allow(unused_imports)]
- #![allow(unused_mut)]
-
- use regex::native::{
- MatchKind, Exists, Location, Submatches,
- StepState, StepMatchEarlyReturn, StepMatch, StepContinue,
- CharReader, find_prefix,
- };
-
- return Nfa {
- which: which,
- input: input,
- ic: 0,
- chars: CharReader::new(input),
- }.run(start, end);
-
- type Captures = [Option<uint>; $num_cap_locs];
-
- struct Nfa<'t> {
- which: MatchKind,
- input: &'t str,
- ic: uint,
- chars: CharReader<'t>,
- }
-
- impl<'t> Nfa<'t> {
- #[allow(unused_variables)]
- fn run(&mut self, start: uint, end: uint) -> Vec<Option<uint>> {
- let mut matched = false;
- let prefix_bytes: &[u8] = $prefix_bytes;
- let mut clist = &mut Threads::new(self.which);
- let mut nlist = &mut Threads::new(self.which);
-
- let mut groups = $init_groups;
-
- self.ic = start;
- let mut next_ic = self.chars.set(start);
- while self.ic <= end {
- if clist.size == 0 {
- if matched {
- break
- }
- $check_prefix
- }
- if clist.size == 0 || (!$prefix_anchor && !matched) {
- self.add(clist, 0, &mut groups)
- }
-
- self.ic = next_ic;
- next_ic = self.chars.advance();
-
- for i in range(0, clist.size) {
- let pc = clist.pc(i);
- let step_state = self.step(&mut groups, nlist,
- clist.groups(i), pc);
- match step_state {
- StepMatchEarlyReturn =>
- return vec![Some(0u), Some(0u)],
- StepMatch => { matched = true; break },
- StepContinue => {},
- }
- }
- ::std::mem::swap(&mut clist, &mut nlist);
- nlist.empty();
- }
- match self.which {
- Exists if matched => vec![Some(0u), Some(0u)],
- Exists => vec![None, None],
- Location | Submatches => groups.iter().map(|x| *x).collect(),
- }
- }
-
- // Sometimes `nlist` is never used (for empty regexes).
- #[allow(unused_variables)]
- #[inline]
- fn step(&self, groups: &mut Captures, nlist: &mut Threads,
- caps: &mut Captures, pc: uint) -> StepState {
- $step_insts
- StepContinue
- }
-
- fn add(&self, nlist: &mut Threads, pc: uint,
- groups: &mut Captures) {
- if nlist.contains(pc) {
- return
- }
- $add_insts
- }
- }
-
- struct Thread {
- pc: uint,
- groups: Captures,
- }
-
- struct Threads {
- which: MatchKind,
- queue: [Thread; $num_insts],
- sparse: [uint; $num_insts],
- size: uint,
- }
-
- impl Threads {
- fn new(which: MatchKind) -> Threads {
- Threads {
- which: which,
- // These unsafe blocks are used for performance reasons, as it
- // gives us a zero-cost initialization of a sparse set. The
- // trick is described in more detail here:
- // http://research.swtch.com/sparse
- // The idea here is to avoid initializing threads that never
- // need to be initialized, particularly for larger regexs with
- // a lot of instructions.
- queue: unsafe { ::std::mem::uninitialized() },
- sparse: unsafe { ::std::mem::uninitialized() },
- size: 0,
- }
- }
-
- #[inline]
- fn add(&mut self, pc: uint, groups: &Captures) {
- let t = &mut self.queue[self.size];
- t.pc = pc;
- match self.which {
- Exists => {},
- Location => {
- t.groups[0] = groups[0];
- t.groups[1] = groups[1];
- }
- Submatches => {
- for (slot, val) in t.groups.iter_mut().zip(groups.iter()) {
- *slot = *val;
- }
- }
- }
- self.sparse[pc] = self.size;
- self.size += 1;
- }
-
- #[inline]
- fn add_empty(&mut self, pc: uint) {
- self.queue[self.size].pc = pc;
- self.sparse[pc] = self.size;
- self.size += 1;
- }
-
- #[inline]
- fn contains(&self, pc: uint) -> bool {
- let s = self.sparse[pc];
- s < self.size && self.queue[s].pc == pc
- }
-
- #[inline]
- fn empty(&mut self) {
- self.size = 0;
- }
-
- #[inline]
- fn pc(&self, i: uint) -> uint {
- self.queue[i].pc
- }
-
- #[inline]
- fn groups<'r>(&'r mut self, i: uint) -> &'r mut Captures {
- &mut self.queue[i].groups
- }
- }
-}
-
-::regex::native::Native(::regex::native::ExNative {
- original: $regex,
- names: &CAP_NAMES,
- prog: exec,
-})
- })
- }
-
- // Generates code for the `add` method, which is responsible for adding
- // zero-width states to the next queue of states to visit.
- fn add_insts(&self) -> P<ast::Expr> {
- let arms = self.prog.insts.iter().enumerate().map(|(pc, inst)| {
- let nextpc = pc + 1;
- let body = match *inst {
- EmptyBegin(flags) => {
- let cond =
- if flags & FLAG_MULTI > 0 {
- quote_expr!(self.cx,
- self.chars.is_begin()
- || self.chars.prev == Some('\n')
- )
- } else {
- quote_expr!(self.cx, self.chars.is_begin())
- };
- quote_expr!(self.cx, {
- nlist.add_empty($pc);
- if $cond { self.add(nlist, $nextpc, &mut *groups) }
- })
- }
- EmptyEnd(flags) => {
- let cond =
- if flags & FLAG_MULTI > 0 {
- quote_expr!(self.cx,
- self.chars.is_end()
- || self.chars.cur == Some('\n')
- )
- } else {
- quote_expr!(self.cx, self.chars.is_end())
- };
- quote_expr!(self.cx, {
- nlist.add_empty($pc);
- if $cond { self.add(nlist, $nextpc, &mut *groups) }
- })
- }
- EmptyWordBoundary(flags) => {
- let cond =
- if flags & FLAG_NEGATED > 0 {
- quote_expr!(self.cx, !self.chars.is_word_boundary())
- } else {
- quote_expr!(self.cx, self.chars.is_word_boundary())
- };
- quote_expr!(self.cx, {
- nlist.add_empty($pc);
- if $cond { self.add(nlist, $nextpc, &mut *groups) }
- })
- }
- Save(slot) => {
- let save = quote_expr!(self.cx, {
- let old = groups[$slot];
- groups[$slot] = Some(self.ic);
- self.add(nlist, $nextpc, &mut *groups);
- groups[$slot] = old;
- });
- let add = quote_expr!(self.cx, {
- self.add(nlist, $nextpc, &mut *groups);
- });
- // If this is saving a submatch location but we request
- // existence or only full match location, then we can skip
- // right over it every time.
- if slot > 1 {
- quote_expr!(self.cx, {
- nlist.add_empty($pc);
- match self.which {
- Submatches => $save,
- Exists | Location => $add,
- }
- })
- } else {
- quote_expr!(self.cx, {
- nlist.add_empty($pc);
- match self.which {
- Submatches | Location => $save,
- Exists => $add,
- }
- })
- }
- }
- Jump(to) => {
- quote_expr!(self.cx, {
- nlist.add_empty($pc);
- self.add(nlist, $to, &mut *groups);
- })
- }
- Split(x, y) => {
- quote_expr!(self.cx, {
- nlist.add_empty($pc);
- self.add(nlist, $x, &mut *groups);
- self.add(nlist, $y, &mut *groups);
- })
- }
- // For Match, OneChar, CharClass, Any
- _ => quote_expr!(self.cx, nlist.add($pc, &*groups)),
- };
- self.arm_inst(pc, body)
- }).collect::<Vec<ast::Arm>>();
-
- self.match_insts(arms)
- }
-
- // Generates the code for the `step` method, which processes all states
- // in the current queue that consume a single character.
- fn step_insts(&self) -> P<ast::Expr> {
- let arms = self.prog.insts.iter().enumerate().map(|(pc, inst)| {
- let nextpc = pc + 1;
- let body = match *inst {
- Match => {
- quote_expr!(self.cx, {
- match self.which {
- Exists => {
- return StepMatchEarlyReturn
- }
- Location => {
- groups[0] = caps[0];
- groups[1] = caps[1];
- return StepMatch
- }
- Submatches => {
- for (slot, val) in groups.iter_mut().zip(caps.iter()) {
- *slot = *val;
- }
- return StepMatch
- }
- }
- })
- }
- OneChar(c, flags) => {
- if flags & FLAG_NOCASE > 0 {
- let upc = c.to_uppercase();
- quote_expr!(self.cx, {
- let upc = self.chars.prev.map(|c| c.to_uppercase());
- if upc == Some($upc) {
- self.add(nlist, $nextpc, caps);
- }
- })
- } else {
- quote_expr!(self.cx, {
- if self.chars.prev == Some($c) {
- self.add(nlist, $nextpc, caps);
- }
- })
- }
- }
- CharClass(ref ranges, flags) => {
- let negate = flags & FLAG_NEGATED > 0;
- let casei = flags & FLAG_NOCASE > 0;
- let get_char =
- if casei {
- quote_expr!(self.cx, self.chars.prev.unwrap().to_uppercase())
- } else {
- quote_expr!(self.cx, self.chars.prev.unwrap())
- };
- let negcond =
- if negate {
- quote_expr!(self.cx, !found)
- } else {
- quote_expr!(self.cx, found)
- };
- let mranges = self.match_class(casei, ranges.as_slice());
- quote_expr!(self.cx, {
- if self.chars.prev.is_some() {
- let c = $get_char;
- let found = $mranges;
- if $negcond {
- self.add(nlist, $nextpc, caps);
- }
- }
- })
- }
- Any(flags) => {
- if flags & FLAG_DOTNL > 0 {
- quote_expr!(self.cx, self.add(nlist, $nextpc, caps))
- } else {
- quote_expr!(self.cx, {
- if self.chars.prev != Some('\n') {
- self.add(nlist, $nextpc, caps)
- }
- ()
- })
- }
- }
- // EmptyBegin, EmptyEnd, EmptyWordBoundary, Save, Jump, Split
- _ => self.empty_block(),
- };
- self.arm_inst(pc, body)
- }).collect::<Vec<ast::Arm>>();
-
- self.match_insts(arms)
- }
-
- // Translates a character class into a match expression.
- // This avoids a binary search (and is hopefully replaced by a jump
- // table).
- fn match_class(&self, casei: bool, ranges: &[(char, char)]) -> P<ast::Expr> {
- let mut arms = ranges.iter().map(|&(mut start, mut end)| {
- if casei {
- start = start.to_uppercase();
- end = end.to_uppercase();
- }
- let pat = self.cx.pat(self.sp, ast::PatRange(quote_expr!(self.cx, $start),
- quote_expr!(self.cx, $end)));
- self.cx.arm(self.sp, vec!(pat), quote_expr!(self.cx, true))
- }).collect::<Vec<ast::Arm>>();
-
- arms.push(self.wild_arm_expr(quote_expr!(self.cx, false)));
-
- let match_on = quote_expr!(self.cx, c);
- self.cx.expr_match(self.sp, match_on, arms)
- }
-
- // Generates code for checking a literal prefix of the search string.
- // The code is only generated if the regex *has* a literal prefix.
- // Otherwise, a no-op is returned.
- fn check_prefix(&self) -> P<ast::Expr> {
- if self.prog.prefix.len() == 0 {
- self.empty_block()
- } else {
- quote_expr!(self.cx,
- if clist.size == 0 {
- let haystack = self.input.as_bytes()[self.ic..];
- match find_prefix(prefix_bytes, haystack) {
- None => break,
- Some(i) => {
- self.ic += i;
- next_ic = self.chars.set(self.ic);
- }
- }
- }
- )
- }
- }
-
- // Builds a `match pc { ... }` expression from a list of arms, specifically
- // for matching the current program counter with an instruction.
- // A wild-card arm is automatically added that executes a no-op. It will
- // never be used, but is added to satisfy the compiler complaining about
- // non-exhaustive patterns.
- fn match_insts(&self, mut arms: Vec<ast::Arm>) -> P<ast::Expr> {
- arms.push(self.wild_arm_expr(self.empty_block()));
- self.cx.expr_match(self.sp, quote_expr!(self.cx, pc), arms)
- }
-
- fn empty_block(&self) -> P<ast::Expr> {
- quote_expr!(self.cx, {})
- }
-
- // Creates a match arm for the instruction at `pc` with the expression
- // `body`.
- fn arm_inst(&self, pc: uint, body: P<ast::Expr>) -> ast::Arm {
- let pc_pat = self.cx.pat_lit(self.sp, quote_expr!(self.cx, $pc));
-
- self.cx.arm(self.sp, vec!(pc_pat), body)
- }
-
- // Creates a wild-card match arm with the expression `body`.
- fn wild_arm_expr(&self, body: P<ast::Expr>) -> ast::Arm {
- ast::Arm {
- attrs: vec!(),
- pats: vec!(P(ast::Pat{
- id: ast::DUMMY_NODE_ID,
- span: self.sp,
- node: ast::PatWild(ast::PatWildSingle),
- })),
- guard: None,
- body: body,
- }
- }
-
-
- // Converts `xs` to a `[x1, x2, .., xN]` expression by calling `to_expr`
- // on each element in `xs`.
- fn vec_expr<T, It, F>(&self, xs: It, mut to_expr: F) -> P<ast::Expr> where
- It: Iterator<Item=T>,
- F: FnMut(&ExtCtxt, T) -> P<ast::Expr>,
- {
- let exprs = xs.map(|x| to_expr(self.cx, x)).collect();
- self.cx.expr_vec(self.sp, exprs)
- }
-}
-
-/// Looks for a single string literal and returns it.
-/// Otherwise, logs an error with cx.span_err and returns None.
-fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<String> {
- let mut parser = cx.new_parser_from_tts(tts);
- let entry = cx.expander().fold_expr(parser.parse_expr());
- let regex = match entry.node {
- ast::ExprLit(ref lit) => {
- match lit.node {
- ast::LitStr(ref s, _) => s.to_string(),
- _ => {
- cx.span_err(entry.span, format!(
- "expected string literal but got `{}`",
- pprust::lit_to_string(&**lit)).as_slice());
- return None
- }
- }
- }
- _ => {
- cx.span_err(entry.span, format!(
- "expected string literal but got `{}`",
- pprust::expr_to_string(&*entry)).as_slice());
- return None
- }
- };
- if !parser.eat(&token::Eof) {
- cx.span_err(parser.span, "only one string literal allowed");
- return None;
- }
- Some(regex)
-}
use metadata::csearch;
use middle::def::*;
use middle::subst::Substs;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::{def, pat_util, stability};
use middle::const_eval::{eval_const_expr_partial, const_int, const_uint};
use util::ppaux::{ty_to_string};
use syntax::{abi, ast, ast_map};
use syntax::ast_util::is_shift_binop;
-use syntax::attr::{mod, AttrMetaMethods};
+use syntax::attr::{self, AttrMetaMethods};
use syntax::codemap::{Span, DUMMY_SP};
use syntax::parse::token;
use syntax::ast::{TyI, TyU, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
use syntax::ast_util;
use syntax::ptr::P;
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
declare_lint! {
WHILE_TRUE,
"suggest using `loop { }` instead of `while true { }`"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct WhileTrue;
impl LintPass for WhileTrue {
"detects unnecessary type casts that can be removed"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnusedCasts;
impl LintPass for UnusedCasts {
"shift exceeds the type's number of bits"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct TypeLimits {
/// Id of the last visited negated expression
negated_expr_id: ast::NodeId,
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct ImproperCTypes;
impl LintPass for ImproperCTypes {
"use of owned (Box type) heap memory"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct BoxPointers;
impl BoxPointers {
"detects attributes that were not used by the compiler"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnusedAttributes;
impl LintPass for UnusedAttributes {
"path statements with no effect"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct PathStatements;
impl LintPass for PathStatements {
"unused result of an expression in a statement"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnusedResults;
impl LintPass for UnusedResults {
"types, variants, traits and type parameters should have camel case names"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct NonCamelCaseTypes;
impl NonCamelCaseTypes {
}
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
enum MethodContext {
TraitDefaultImpl,
TraitImpl,
"methods, functions, lifetime parameters and modules should have snake case names"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct NonSnakeCase;
impl NonSnakeCase {
"static constants should have uppercase identifiers"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct NonUpperCaseGlobals;
impl LintPass for NonUpperCaseGlobals {
"`if`, `match`, `while` and `return` do not need parentheses"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnusedParens;
impl UnusedParens {
"unnecessary braces around an imported item"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnusedImportBraces;
impl LintPass for UnusedImportBraces {
"using `Struct { x: x }` instead of `Struct { x }`"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct NonShorthandFieldPatterns;
impl LintPass for NonShorthandFieldPatterns {
"unnecessary use of an `unsafe` block"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnusedUnsafe;
impl LintPass for UnusedUnsafe {
"usage of an `unsafe` block"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnsafeBlocks;
impl LintPass for UnsafeBlocks {
"detect mut variables which don't need to be mutable"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnusedMut;
impl UnusedMut {
"detects unnecessary allocations that can be eliminated"
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnusedAllocation;
impl LintPass for UnusedAllocation {
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct MissingCopyImplementations;
impl LintPass for MissingCopyImplementations {
/// Checks for use of items with `#[deprecated]`, `#[experimental]` and
/// `#[unstable]` attributes, or no stability attribute.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Stability;
impl Stability {
/// Does nothing as a lint pass, but registers some `Lint`s
/// which are used by other parts of the compiler.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct HardwiredLints;
impl LintPass for HardwiredLints {
use self::TargetLint::*;
use middle::privacy::ExportedItems;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use session::{early_error, Session};
use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass, LintPassObject};
use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid};
pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs};
/// Specification of a single lint.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Lint {
/// A string identifier for the lint.
///
pub type LintPassObject = Box<LintPass + 'static>;
/// Identifies a lint known to the compiler.
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct LintId {
// Identity is based on pointer equality of this field.
lint: &'static Lint,
}
/// Setting for how to handle a lint.
-#[deriving(Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
+#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
pub enum Level {
Allow, Warn, Deny, Forbid
}
}
/// How a lint level was set.
-#[deriving(Clone, Copy, PartialEq, Eq)]
+#[derive(Clone, Copy, PartialEq, Eq)]
pub enum LintSource {
/// Lint is at the default level as declared
/// in rustc or a plugin.
pub const tag_items_data_item_reexport_name: uint = 0x3a;
// used to encode crate_ctxt side tables
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
#[repr(uint)]
pub enum astencode_tag { // Reserves 0x40 -- 0x5f
tag_ast = 0x40,
pub const tag_items_data_item_repr: uint = 0x93;
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct LinkMeta {
pub crate_name: String,
pub crate_hash: Svh,
use std::collections::hash_map::HashMap;
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct MethodInfo {
pub name: ast::Name,
pub def_id: ast::DefId,
pub span: Span,
}
-#[deriving(Copy, Show, PartialEq, Clone)]
+#[derive(Copy, Show, PartialEq, Clone)]
pub enum LinkagePreference {
RequireDynamic,
RequireStatic,
}
-#[deriving(Copy, Clone, PartialEq, FromPrimitive)]
+#[derive(Copy, Clone, PartialEq, FromPrimitive)]
pub enum NativeLibraryKind {
NativeStatic, // native static library (.a archive)
NativeFramework, // OSX-specific
// Where a crate came from on the local filesystem. One of these two options
// must be non-None.
-#[deriving(PartialEq, Clone)]
+#[derive(PartialEq, Clone)]
pub struct CrateSource {
pub dylib: Option<Path>,
pub rlib: Option<Path>,
use middle::lang_items;
use middle::subst;
use middle::ty::{ImplContainer, TraitContainer};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::astencode::vtable_decoder_helpers;
use std::collections::HashMap;
find_item(item_id, items)
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
enum Family {
ImmStatic, // c
MutStatic, // b
}
// Something that a name can resolve to.
-#[deriving(Copy, Clone, Show)]
+#[derive(Copy, Clone, Show)]
pub enum DefLike {
DlDef(def::Def),
DlImpl(ast::DefId),
get_attributes(rbml::Doc::new(data))
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct CrateDep {
pub cnum: ast::CrateNum,
pub name: String,
use metadata::tyencode;
use middle::def;
use middle::ty::{lookup_item_type};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::stability;
use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
use std::hash::Hash;
use std::hash;
use syntax::abi;
-use syntax::ast::{mod, DefId, NodeId};
+use syntax::ast::{self, DefId, NodeId};
use syntax::ast_map::{PathElem, PathElems};
use syntax::ast_map;
use syntax::ast_util::*;
rbml_w.wr_tagged_str(tag_def_id, def_to_string(id)[]);
}
-#[deriving(Clone)]
+#[derive(Clone)]
struct entry<T> {
val: T,
pos: u64
use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
use middle::region;
use middle::subst;
use middle::subst::VecPerParamSpace;
-use middle::ty::{mod, AsPredicate, Ty};
+use middle::ty::{self, AsPredicate, Ty};
use std::rc::Rc;
use std::str;
// def-id will depend on where it originated from. Therefore, the conversion
// function is given an indicator of the source of the def-id. See
// astencode.rs for more information.
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum DefIdSource {
// Identifies a struct, trait, enum, etc.
NominalType,
use middle::subst;
use middle::subst::VecPerParamSpace;
use middle::ty::ParamTy;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::nodemap::FnvHashMap;
use syntax::abi::Abi;
*/
use middle::def;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use syntax::ast;
use util::ppaux::Repr;
use middle::mem_categorization::Typer;
use middle::subst;
use middle::subst::VecPerParamSpace;
-use middle::ty::{mod, Ty, MethodCall, MethodCallee, MethodOrigin};
+use middle::ty::{self, Ty, MethodCall, MethodCallee, MethodOrigin};
use util::ppaux::ty_to_string;
use syntax::{ast, ast_map, ast_util, codemap, fold};
loop_scopes: Vec<LoopScope>,
}
-#[deriving(Copy)]
+#[derive(Copy)]
struct LoopScope {
loop_id: ast::NodeId, // id of loop/while node
continue_index: CFGIndex, // where to go on a `loop`
let method_call = ty::MethodCall::expr(call_expr.id);
let return_ty = ty::ty_fn_ret(match self.tcx.method_map.borrow().get(&method_call) {
Some(method) => method.ty,
- None => ty::expr_ty(self.tcx, func_or_rcvr)
+ None => ty::expr_ty_adjusted(self.tcx, func_or_rcvr)
});
let func_or_rcvr_exit = self.expr(func_or_rcvr, pred);
fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> {
if i == self.cfg.entry {
- dot::LabelStr("entry".into_cow())
+ dot::LabelText::LabelStr("entry".into_cow())
} else if i == self.cfg.exit {
- dot::LabelStr("exit".into_cow())
+ dot::LabelText::LabelStr("exit".into_cow())
} else if n.data.id == ast::DUMMY_NODE_ID {
- dot::LabelStr("(dummy_node)".into_cow())
+ dot::LabelText::LabelStr("(dummy_node)".into_cow())
} else {
let s = self.ast_map.node_to_string(n.data.id);
// left-aligns the lines
let s = replace_newline_with_backslash_l(s);
- dot::EscStr(s.into_cow())
+ dot::LabelText::EscStr(s.into_cow())
}
}
let s = replace_newline_with_backslash_l(s);
label.push_str(format!("exiting scope_{} {}", i, s[])[]);
}
- dot::EscStr(label.into_cow())
+ dot::LabelText::EscStr(label.into_cow())
}
}
pub exit: CFGIndex,
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct CFGNodeData {
pub id: ast::NodeId
}
use util::ppaux;
use syntax::ast;
-use syntax::ast_util;
-use syntax::visit::Visitor;
-use syntax::visit;
+use syntax::visit::{self, Visitor};
struct CheckCrateVisitor<'a, 'tcx: 'a> {
tcx: &'a ty::ctxt<'tcx>,
{
self.with_const(true, f);
}
- fn outside_const<F>(&mut self, f: F) where
- F: FnOnce(&mut CheckCrateVisitor<'a, 'tcx>),
- {
- self.with_const(false, f);
- }
}
impl<'a, 'tcx, 'v> Visitor<'v> for CheckCrateVisitor<'a, 'tcx> {
fn visit_item(&mut self, i: &ast::Item) {
- check_item(self, i);
+ match i.node {
+ ast::ItemStatic(_, _, ref ex) |
+ ast::ItemConst(_, ref ex) => {
+ self.inside_const(|v| v.visit_expr(&**ex));
+ }
+ ast::ItemEnum(ref enum_definition, _) => {
+ self.inside_const(|v| {
+ for var in enum_definition.variants.iter() {
+ if let Some(ref ex) = var.node.disr_expr {
+ v.visit_expr(&**ex);
+ }
+ }
+ });
+ }
+ _ => self.with_const(false, |v| visit::walk_item(v, i))
+ }
}
fn visit_pat(&mut self, p: &ast::Pat) {
- check_pat(self, p);
+ let is_const = match p.node {
+ ast::PatLit(_) | ast::PatRange(..) => true,
+ _ => false
+ };
+ self.with_const(is_const, |v| visit::walk_pat(v, p))
}
fn visit_expr(&mut self, ex: &ast::Expr) {
- if check_expr(self, ex) {
- visit::walk_expr(self, ex);
+ if self.in_const {
+ check_expr(self, ex);
}
+ visit::walk_expr(self, ex);
}
}
tcx.sess.abort_if_errors();
}
-fn check_item(v: &mut CheckCrateVisitor, it: &ast::Item) {
- match it.node {
- ast::ItemStatic(_, _, ref ex) |
- ast::ItemConst(_, ref ex) => {
- v.inside_const(|v| v.visit_expr(&**ex));
- }
- ast::ItemEnum(ref enum_definition, _) => {
- for var in (*enum_definition).variants.iter() {
- for ex in var.node.disr_expr.iter() {
- v.inside_const(|v| v.visit_expr(&**ex));
- }
- }
- }
- _ => v.outside_const(|v| visit::walk_item(v, it))
- }
-}
-
-fn check_pat(v: &mut CheckCrateVisitor, p: &ast::Pat) {
- fn is_str(e: &ast::Expr) -> bool {
- match e.node {
- ast::ExprBox(_, ref expr) => {
- match expr.node {
- ast::ExprLit(ref lit) => ast_util::lit_is_str(&**lit),
- _ => false,
- }
- }
- _ => false,
- }
- }
- match p.node {
- // Let through plain ~-string literals here
- ast::PatLit(ref a) => if !is_str(&**a) { v.inside_const(|v| v.visit_expr(&**a)); },
- ast::PatRange(ref a, ref b) => {
- if !is_str(&**a) { v.inside_const(|v| v.visit_expr(&**a)); }
- if !is_str(&**b) { v.inside_const(|v| v.visit_expr(&**b)); }
- }
- _ => v.outside_const(|v| visit::walk_pat(v, p))
- }
-}
-
-fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) -> bool {
- if !v.in_const { return true }
-
+fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) {
match e.node {
ast::ExprUnary(ast::UnDeref, _) => {}
ast::ExprUnary(ast::UnUniq, _) => {
span_err!(v.tcx.sess, e.span, E0010,
"cannot do allocations in constant expressions");
- return false;
}
- ast::ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => {}
ast::ExprBinary(..) | ast::ExprUnary(..) => {
let method_call = ty::MethodCall::expr(e.id);
if v.tcx.method_map.borrow().contains_key(&method_call) {
expressions");
}
}
- ast::ExprLit(_) => (),
+ ast::ExprLit(_) => {}
ast::ExprCast(ref from, _) => {
let toty = ty::expr_ty(v.tcx, e);
let fromty = ty::expr_ty(v.tcx, &**from);
expression");
}
}
- ast::ExprPath(ref pth) => {
- // NB: In the future you might wish to relax this slightly
- // to handle on-demand instantiation of functions via
- // foo::<bar> in a const. Currently that is only done on
- // a path in trans::callee that only works in block contexts.
- if !pth.segments.iter().all(|segment| segment.parameters.is_empty()) {
- span_err!(v.tcx.sess, e.span, E0013,
- "paths in constants may only refer to items without \
- type parameters");
- }
- match v.tcx.def_map.borrow().get(&e.id) {
- Some(&DefStatic(..)) |
- Some(&DefConst(..)) |
- Some(&DefFn(..)) |
- Some(&DefVariant(_, _, _)) |
- Some(&DefStruct(_)) => { }
+ ast::ExprPath(_) => {
+ match v.tcx.def_map.borrow()[e.id] {
+ DefStatic(..) | DefConst(..) |
+ DefFn(..) | DefStaticMethod(..) | DefMethod(..) |
+ DefStruct(_) | DefVariant(_, _, _) => {}
- Some(&def) => {
+ def => {
debug!("(checking const) found bad def: {}", def);
span_err!(v.tcx.sess, e.span, E0014,
"paths in constants may only refer to constants \
or functions");
}
- None => {
- v.tcx.sess.span_bug(e.span, "unbound path in const?!");
- }
}
}
ast::ExprCall(ref callee, _) => {
- match v.tcx.def_map.borrow().get(&callee.id) {
- Some(&DefStruct(..)) |
- Some(&DefVariant(..)) => {} // OK.
-
+ match v.tcx.def_map.borrow()[callee.id] {
+ DefStruct(..) | DefVariant(..) => {} // OK.
_ => {
span_err!(v.tcx.sess, e.span, E0015,
"function calls in constants are limited to \
"blocks in constants are limited to items and \
tail expressions");
match stmt.node {
- ast::StmtDecl(ref span, _) => {
- match span.node {
- ast::DeclLocal(_) => block_span_err(span.span),
+ ast::StmtDecl(ref decl, _) => {
+ match decl.node {
+ ast::DeclLocal(_) => block_span_err(decl.span),
// Item statements are allowed
ast::DeclItem(_) => {}
}
}
}
- match block.expr {
- Some(ref expr) => { check_expr(v, &**expr); }
- None => {}
- }
}
ast::ExprVec(_) |
ast::ExprAddrOf(ast::MutImmutable, _) |
}
}
- _ => {
- span_err!(v.tcx.sess, e.span, E0019,
- "constant contains unimplemented expression type");
- return false;
- }
+ _ => span_err!(v.tcx.sess, e.span, E0019,
+ "constant contains unimplemented expression type")
}
- true
}
use syntax::visit::Visitor;
use syntax::visit;
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
enum Context {
Normal, Loop, Closure
}
-#[deriving(Copy)]
+#[derive(Copy)]
struct CheckLoopVisitor<'a> {
sess: &'a Session,
cx: Context
use std::iter::{range_inclusive, AdditiveIterator, FromIterator, repeat};
use std::num::Float;
use std::slice;
-use syntax::ast::{mod, DUMMY_NODE_ID, NodeId, Pat};
+use syntax::ast::{self, DUMMY_NODE_ID, NodeId, Pat};
use syntax::ast_util::walk_pat;
use syntax::codemap::{Span, Spanned, DUMMY_SP};
use syntax::fold::{Folder, noop_fold_pat};
use syntax::print::pprust::pat_to_string;
use syntax::parse::token;
use syntax::ptr::P;
-use syntax::visit::{mod, Visitor, FnKind};
+use syntax::visit::{self, Visitor, FnKind};
use util::ppaux::ty_to_string;
pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
pub param_env: ParameterEnvironment<'a, 'tcx>,
}
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
pub enum Constructor {
/// The constructor of all patterns that don't vary by constructor,
/// e.g. struct patterns and fixed-length arrays.
SliceWithSubslice(uint, uint)
}
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
enum Usefulness {
Useful,
UsefulWithWitness(Vec<P<Pat>>),
NotUseful
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum WitnessPreference {
ConstructWitness,
LeaveOutWitness
use syntax::codemap::Span;
use syntax::visit;
-#[deriving(Copy, Eq, PartialEq)]
+#[derive(Copy, Eq, PartialEq)]
enum Mode {
InConstant,
InStatic,
use metadata::csearch;
use middle::{astencode, def};
use middle::pat_util::def_to_path;
-use middle::ty::{mod};
+use middle::ty::{self};
use middle::astconv_util::{ast_ty_to_prim_ty};
use util::nodemap::DefIdMap;
-use syntax::ast::{mod, Expr};
+use syntax::ast::{self, Expr};
use syntax::parse::token::InternedString;
use syntax::ptr::P;
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
use syntax::{ast_map, ast_util, codemap};
use std::collections::hash_map::Entry::Vacant;
// - Non-constants: everything else.
//
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum constness {
integral_const,
general_const,
// FIXME (#33): this doesn't handle big integer/float literals correctly
// (nor does the rest of our literal handling).
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
pub enum const_val {
const_float(f64),
const_int(i64),
use syntax::print::{pp, pprust};
use util::nodemap::NodeMap;
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum EntryOrExit {
Entry,
Exit,
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct DataFlowContext<'a, 'tcx: 'a, O> {
tcx: &'a ty::ctxt<'tcx>,
use std::collections::HashSet;
use syntax::{ast, ast_map, codemap};
use syntax::ast_util::{local_def, is_local, PostExpansionMethod};
-use syntax::attr::{mod, AttrMetaMethods};
-use syntax::visit::{mod, Visitor};
+use syntax::attr::{self, AttrMetaMethods};
+use syntax::visit::{self, Visitor};
// Any local node that may call something in its body block should be
// explored. For example, if it's a live NodeItem that is a
use std::cell::RefCell;
-#[deriving(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Def {
DefFn(ast::DefId, bool /* is_ctor */),
DefStaticMethod(/* method */ ast::DefId, MethodProvenance),
// within.
pub type ExportMap = NodeMap<Vec<Export>>;
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Export {
pub name: ast::Name, // The name of the target.
pub def_id: ast::DefId, // The definition of the target.
}
-#[deriving(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum MethodProvenance {
FromTrait(ast::DefId),
FromImpl(ast::DefId),
}
-#[deriving(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum TyParamProvenance {
FromSelf(ast::DefId),
FromParam(ast::DefId),
}
}
-#[deriving(Clone, Copy, Eq, PartialEq)]
+#[derive(Clone, Copy, Eq, PartialEq)]
pub enum TraitItemKind {
NonstaticMethodTraitItemKind,
StaticMethodTraitItemKind,
use self::UnsafeContext::*;
use middle::def;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::MethodCall;
use util::ppaux;
use syntax::visit;
use syntax::visit::Visitor;
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
enum UnsafeContext {
SafeContext,
UnsafeFn,
use middle::{def, region, pat_util};
use middle::mem_categorization as mc;
use middle::mem_categorization::Typer;
-use middle::ty::{mod};
+use middle::ty::{self};
use middle::ty::{MethodCall, MethodObject, MethodTraitObject};
use middle::ty::{MethodOrigin, MethodParam, MethodTypeParam};
use middle::ty::{MethodStatic, MethodStaticUnboxedClosure};
mode: MutateMode);
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum LoanCause {
ClosureCapture(Span),
AddrOf,
MatchDiscriminant
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum ConsumeMode {
Copy, // reference to x where x has a type that copies
Move(MoveReason), // reference to x where x has a type that moves
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum MoveReason {
DirectRefMove,
PatBindingMove,
CaptureMove,
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum MatchMode {
NonBindingMatch,
BorrowingMatch,
MovingMatch,
}
-#[deriving(PartialEq,Show)]
+#[derive(PartialEq,Show)]
enum TrackMatchMode<T> {
Unknown,
Definite(MatchMode),
}
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum MutateMode {
Init,
JustWrite, // x = y
WriteAndRead, // x += y
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum OverloadedCallType {
FnOverloadedCall,
FnMutOverloadedCall,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use syntax::ast;
use self::SimplifiedType::*;
/// See `simplify_type
-#[deriving(Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum SimplifiedType {
BoolSimplifiedType,
CharSimplifiedType,
}
}
-#[deriving(Clone, Copy, PartialEq, Show)]
+#[derive(Clone, Copy, PartialEq, Show)]
pub struct NodeIndex(pub uint);
#[allow(non_upper_case_globals)]
pub const InvalidNodeIndex: NodeIndex = NodeIndex(uint::MAX);
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub struct EdgeIndex(pub uint);
#[allow(non_upper_case_globals)]
pub const InvalidEdgeIndex: EdgeIndex = EdgeIndex(uint::MAX);
// Use a private field here to guarantee no more instances are created:
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub struct Direction { repr: uint }
#[allow(non_upper_case_globals)]
pub const Outgoing: Direction = Direction { repr: 0 };
use middle::subst;
use middle::ty::{AutoPtr, AutoDerefRef, AdjustDerefRef, AutoUnsize, AutoUnsafe};
use middle::ty::{mt};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::ppaux;
use util::ppaux::Repr;
use middle::ty::{FloatVar, FnSig, IntVar, TyVar};
use middle::ty::{IntType, UintType};
use middle::ty::{BuiltinBounds};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty_fold;
use middle::ty_fold::{TypeFoldable};
use util::ppaux::Repr;
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct CombineFields<'a, 'tcx: 'a> {
pub infcx: &'a InferCtxt<'a, 'tcx>,
pub a_is_expected: bool,
// except according to those terms.
use middle::ty::{BuiltinBounds};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::TyVar;
use middle::infer::combine::*;
use middle::infer::{cres};
use middle::def;
use middle::infer;
use middle::subst;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::{Region, ReFree};
use std::cell::{Cell, RefCell};
use std::char::from_u32;
//! variable only once, and it does so as soon as it can, so it is reasonable to ask what the type
//! inferencer knows "so far".
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty_fold;
use middle::ty_fold::TypeFoldable;
use middle::ty_fold::TypeFolder;
-use std::collections::hash_map::{mod, Entry};
+use std::collections::hash_map::{self, Entry};
use super::InferCtxt;
use super::unify::InferCtxtMethodsForSimplyUnifiableTypes;
use super::{TypeTrace, Subtype};
use middle::ty::{BuiltinBounds};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use syntax::ast::{Many, Once, MutImmutable, MutMutable};
use syntax::ast::{Onceness, Unsafety};
use util::ppaux::mt_to_string;
use super::{CombinedSnapshot, cres, InferCtxt, HigherRankedType, SkolemizationMap};
use super::combine::{Combine, Combineable};
-use middle::ty::{mod, Binder};
-use middle::ty_fold::{mod, TypeFoldable};
+use middle::ty::{self, Binder};
+use middle::ty_fold::{self, TypeFoldable};
use syntax::codemap::Span;
use util::nodemap::{FnvHashMap, FnvHashSet};
use util::ppaux::Repr;
use super::lub::Lub;
use middle::ty::{TyVar};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::ppaux::Repr;
pub trait LatticeDir<'tcx> {
use super::{TypeTrace, Subtype};
use middle::ty::{BuiltinBounds};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use syntax::ast::{Many, Once};
use syntax::ast::{Onceness, Unsafety};
use syntax::ast::{MutMutable, MutImmutable};
use middle::subst::Substs;
use middle::ty::{TyVid, IntVid, FloatVid, RegionVid, UnconstrainedNumeric};
use middle::ty::replace_late_bound_regions;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty_fold::{TypeFolder, TypeFoldable};
use std::cell::{RefCell};
use std::rc::Rc;
/// Why did we require that the two types be related?
///
/// See `error_reporting.rs` for more details
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub enum TypeOrigin {
// Not yet categorized in a better way
Misc(Span),
}
/// See `error_reporting.rs` for more details
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub enum ValuePairs<'tcx> {
Types(ty::expected_found<Ty<'tcx>>),
TraitRefs(ty::expected_found<Rc<ty::TraitRef<'tcx>>>),
/// encounter an error or subtyping constraint.
///
/// See `error_reporting.rs` for more details.
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct TypeTrace<'tcx> {
origin: TypeOrigin,
values: ValuePairs<'tcx>,
/// The origin of a `r1 <= r2` constraint.
///
/// See `error_reporting.rs` for more details
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub enum SubregionOrigin<'tcx> {
// Arose from a subtyping relation
Subtype(TypeTrace<'tcx>),
}
/// Times when we replace late-bound regions with variables:
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub enum LateBoundRegionConversionTime {
/// when a fn is called
FnCall,
/// Reasons to create a region inference variable
///
/// See `error_reporting.rs` for more details
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub enum RegionVariableOrigin<'tcx> {
// Region variables created for ill-categorized reasons,
// mostly indicates places in need of refactoring
BoundRegionInCoherence(ast::Name),
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum fixup_err {
unresolved_int_ty(IntVid),
unresolved_float_ty(FloatVid),
use util::ppaux::Repr;
use std::collections::hash_map::Entry::Vacant;
-use std::io::{mod, File};
+use std::io::{self, File};
use std::os;
-use std::sync::atomic;
+use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT};
use syntax::ast;
fn print_help_message() {
let output_path = {
let output_template = match requested_output {
Some(ref s) if s.as_slice() == "help" => {
- static PRINTED_YET : atomic::AtomicBool = atomic::ATOMIC_BOOL_INIT;
- if !PRINTED_YET.load(atomic::SeqCst) {
+ static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT;
+ if !PRINTED_YET.load(Ordering::SeqCst) {
print_help_message();
- PRINTED_YET.store(true, atomic::SeqCst);
+ PRINTED_YET.store(true, Ordering::SeqCst);
}
return;
}
node_ids: FnvHashMap<Node, uint>,
}
-#[deriving(Clone, Hash, PartialEq, Eq, Show)]
+#[derive(Clone, Hash, PartialEq, Eq, Show)]
enum Node {
RegionVid(ty::RegionVid),
Region(ty::Region),
use util::ppaux::Repr;
use std::cell::{Cell, RefCell};
-use std::cmp::Ordering::{mod, Less, Greater, Equal};
+use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::iter::repeat;
use std::u32;
use syntax::ast;
mod graphviz;
// A constraint that influences the inference process.
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub enum Constraint {
// One region variable is subregion of another
ConstrainVarSubVar(RegionVid, RegionVid),
VerifyParamBound(ty::ParamTy, SubregionOrigin<'tcx>, Region, Vec<Region>),
}
-#[deriving(Copy, PartialEq, Eq, Hash)]
+#[derive(Copy, PartialEq, Eq, Hash)]
pub struct TwoRegions {
a: Region,
b: Region,
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum UndoLogEntry {
OpenSnapshot,
CommitedSnapshot,
AddCombination(CombineMapType, TwoRegions)
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum CombineMapType {
Lub, Glb
}
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub enum RegionResolutionError<'tcx> {
/// `ConcreteFailure(o, a, b)`:
///
/// ```
/// would report an error because we expect 'a and 'b to match, and so we group
/// 'a and 'b together inside a SameRegions struct
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct SameRegions {
pub scope_id: ast::NodeId,
pub regions: Vec<BoundRegion>
values: RefCell<Option<Vec<VarValue>>>,
}
-#[deriving(Show)]
+#[derive(Show)]
#[allow(missing_copy_implementations)]
pub struct RegionSnapshot {
length: uint,
// ______________________________________________________________________
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
enum Classification { Expanding, Contracting }
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum VarValue { NoValue, Value(Region), ErrorValue }
struct VarData {
// except according to those terms.
use super::{InferCtxt, fixup_err, fres, unresolved_ty, unresolved_int_ty, unresolved_float_ty};
-use middle::ty::{mod, Ty};
-use middle::ty_fold::{mod, TypeFoldable};
+use middle::ty::{self, Ty};
+use middle::ty_fold::{self, TypeFoldable};
use util::ppaux::Repr;
///////////////////////////////////////////////////////////////////////////
use super::type_variable::{SubtypeOf, SupertypeOf};
use middle::ty::{BuiltinBounds};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::TyVar;
use util::ppaux::{Repr};
use self::TypeVariableValue::*;
use self::UndoEntry::*;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use std::cmp::min;
use std::mem;
use std::u32;
type Relation = (RelationDir, ty::TyVid);
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum RelationDir {
SubtypeOf, SupertypeOf, EqTo
}
use std::kinds::marker;
use middle::ty::{expected_found, IntVarValue};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::infer::{uok, ures};
use middle::infer::InferCtxt;
use std::cell::RefCell;
/// to keep the DAG relatively balanced, which helps keep the running
/// time of the algorithm under control. For more information, see
/// <http://en.wikipedia.org/wiki/Disjoint-set_data_structure>.
-#[deriving(PartialEq,Clone)]
+#[derive(PartialEq,Clone)]
pub enum VarValue<K,V> {
Redirect(K),
Root(V, uint),
pub rank: uint,
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Delegate;
// We can't use V:LatticeValue, much as I would like to,
use middle::def::DefFn;
use middle::subst::{Subst, Substs, EnumeratedItems};
use middle::ty::{TransmuteRestriction, ctxt, ty_bare_fn};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::ppaux::Repr;
use syntax::abi::RustIntrinsic;
$( $variant:ident, $name:expr, $method:ident; )*
) => {
-#[deriving(Copy, FromPrimitive, PartialEq, Eq, Hash)]
+#[derive(Copy, FromPrimitive, PartialEq, Eq, Hash)]
pub enum LangItem {
$($variant),*
}
use std::{fmt, io, uint};
use std::rc::Rc;
use std::iter::repeat;
-use syntax::ast::{mod, NodeId, Expr};
+use syntax::ast::{self, NodeId, Expr};
use syntax::codemap::{BytePos, original_sp, Span};
-use syntax::parse::token::{mod, special_idents};
+use syntax::parse::token::{self, special_idents};
use syntax::print::pprust::{expr_to_string, block_to_string};
use syntax::ptr::P;
use syntax::ast_util;
-use syntax::visit::{mod, Visitor, FnKind};
+use syntax::visit::{self, Visitor, FnKind};
/// For use with `propagate_through_loop`.
enum LoopKind<'a> {
ForLoop(&'a ast::Pat),
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
struct Variable(uint);
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
struct LiveNode(uint);
impl Variable {
}
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
enum LiveNodeKind {
FreeVarNode(Span),
ExprNode(Span),
var_nid: NodeId
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
struct LocalInfo {
id: NodeId,
ident: ast::Ident
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
enum VarKind {
Arg(NodeId, ast::Ident),
Local(LocalInfo),
// Actually we compute just a bit more than just liveness, but we use
// the same basic propagation framework in all cases.
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
struct Users {
reader: LiveNode,
writer: LiveNode,
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
struct Specials {
exit_ln: LiveNode,
fallthrough_ln: LiveNode,
ast::ExprCall(ref f, ref args) => {
let diverges = !self.ir.tcx.is_method_call(expr.id) && {
- let t_ret = ty::ty_fn_ret(ty::expr_ty(self.ir.tcx, &**f));
+ let t_ret = ty::ty_fn_ret(ty::expr_ty_adjusted(self.ir.tcx, &**f));
t_ret == ty::FnDiverging
};
let succ = if diverges {
use middle::def;
use middle::region;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::nodemap::{NodeMap};
use util::ppaux::{Repr};
use std::cell::RefCell;
use std::rc::Rc;
-#[deriving(Clone, PartialEq, Show)]
+#[derive(Clone, PartialEq, Show)]
pub enum categorization<'tcx> {
cat_rvalue(ty::Region), // temporary val, argument is its scope
cat_static_item,
}
// Represents any kind of upvar
-#[deriving(Clone, Copy, PartialEq, Show)]
+#[derive(Clone, Copy, PartialEq, Show)]
pub struct Upvar {
pub id: ty::UpvarId,
// Unboxed closure kinds are used even for old-style closures for simplicity
}
// different kinds of pointers:
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub enum PointerKind {
Unique,
BorrowedPtr(ty::BorrowKind, ty::Region),
// We use the term "interior" to mean "something reachable from the
// base without a pointer dereference", e.g. a field
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub enum InteriorKind {
InteriorField(FieldName),
InteriorElement(ElementKind),
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub enum FieldName {
NamedField(ast::Name),
PositionalField(uint)
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub enum ElementKind {
VecElement,
OtherElement,
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub enum MutabilityCategory {
McImmutable, // Immutable.
McDeclared, // Directly declared as mutable.
// Upvar categorization can generate a variable number of nested
// derefs. The note allows detecting them without deep pattern
// matching on the categorization.
-#[deriving(Clone, Copy, PartialEq, Show)]
+#[derive(Clone, Copy, PartialEq, Show)]
pub enum Note {
NoteClosureEnv(ty::UpvarId), // Deref through closure env
NoteUpvarRef(ty::UpvarId), // Deref through by-ref upvar
// dereference, but its type is the type *before* the dereference
// (`@T`). So use `cmt.ty` to find the type of the value in a consistent
// fashion. For more details, see the method `cat_pattern`
-#[deriving(Clone, PartialEq, Show)]
+#[derive(Clone, PartialEq, Show)]
pub struct cmt_<'tcx> {
pub id: ast::NodeId, // id of expr/pat producing this value
pub span: Span, // span of same expr/pat
// We pun on *T to mean both actual deref of a ptr as well
// as accessing of components:
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum deref_kind {
deref_ptr(PointerKind),
deref_interior(InteriorKind),
id, expr_ty.repr(self.tcx()), def);
match def {
- def::DefStruct(..) | def::DefVariant(..) | def::DefFn(..) |
- def::DefStaticMethod(..) | def::DefConst(..) => {
+ def::DefStruct(..) | def::DefVariant(..) | def::DefConst(..) |
+ def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => {
Ok(self.cat_rvalue_node(id, span, expr_ty))
}
def::DefMod(_) | def::DefForeignMod(_) | def::DefUse(_) |
def::DefTrait(_) | def::DefTy(..) | def::DefPrimTy(_) |
def::DefTyParam(..) | def::DefTyParamBinder(..) | def::DefRegion(_) |
- def::DefLabel(_) | def::DefSelfTy(..) | def::DefMethod(..) |
+ def::DefLabel(_) | def::DefSelfTy(..) |
def::DefAssociatedTy(..) | def::DefAssociatedPath(..)=> {
Ok(Rc::new(cmt_ {
id:id,
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum InteriorSafety {
InteriorUnsafe,
InteriorSafe
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum AliasableReason {
AliasableBorrowed,
AliasableClosure(ast::NodeId), // Aliasable due to capture Fn closure env
use metadata::csearch;
use middle::def;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::{MethodCall, MethodMap, MethodOrigin, MethodParam, MethodTypeParam};
use middle::ty::{MethodStatic, MethodStaticUnboxedClosure, MethodObject, MethodTraitObject};
use util::nodemap::{DefIdSet, NodeMap, NodeSet};
use syntax::ast_util::{is_local, local_def, PostExpansionMethod};
use syntax::codemap::Span;
use syntax::parse::token;
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
type Context<'a, 'tcx> = (&'a MethodMap<'tcx>, &'a def::ExportMap);
// FIXME: dox
pub type LastPrivateMap = NodeMap<LastPrivate>;
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum LastPrivate {
LastMod(PrivateDep),
// `use` directives (imports) can refer to two separate definitions in the
type_used: ImportUse},
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum PrivateDep {
AllPublic,
DependsOn(ast::DefId),
}
// How an import is used.
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum ImportUse {
Unused, // The import is not used.
Used, // The import is used.
//! `middle/typeck/infer/region_inference.rs`
use session::Session;
-use middle::ty::{mod, Ty, FreeRegion};
+use middle::ty::{self, Ty, FreeRegion};
use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap};
use util::common::can_reach;
/// placate the same deriving in `ty::FreeRegion`, but we may want to
/// actually attach a more meaningful ordering to scopes than the one
/// generated via deriving here.
-#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
+#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
RustcDecodable, Show, Copy)]
pub enum CodeExtent {
Misc(ast::NodeId)
terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Context {
var_parent: Option<ast::NodeId>,
use self::ScopeChain::*;
use session::Session;
-use middle::def::{mod, DefMap};
+use middle::def::{self, DefMap};
use middle::region;
use middle::subst;
use middle::ty;
use syntax::visit::Visitor;
use util::nodemap::NodeMap;
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show)]
pub enum DefRegion {
DefStaticRegion,
DefEarlyBoundRegion(/* space */ subst::ParamSpace,
pub use self::ParamSpace::*;
pub use self::RegionSubsts::*;
-use middle::ty::{mod, Ty};
-use middle::ty_fold::{mod, TypeFoldable, TypeFolder};
+use middle::ty::{self, Ty};
+use middle::ty_fold::{self, TypeFoldable, TypeFolder};
use util::ppaux::Repr;
use std::fmt;
/// identify each in-scope parameter by an *index* and a *parameter
/// space* (which indices where the parameter is defined; see
/// `ParamSpace`).
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct Substs<'tcx> {
pub types: VecPerParamSpace<Ty<'tcx>>,
pub regions: RegionSubsts,
/// Represents the values to use when substituting lifetime parameters.
/// If the value is `ErasedRegions`, then this subst is occurring during
/// trans, and all region parameters will be replaced with `ty::ReStatic`.
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub enum RegionSubsts {
ErasedRegions,
NonerasedRegions(VecPerParamSpace<ty::Region>)
///////////////////////////////////////////////////////////////////////////
// ParamSpace
-#[deriving(PartialOrd, Ord, PartialEq, Eq, Copy,
+#[derive(PartialOrd, Ord, PartialEq, Eq, Copy,
Clone, Hash, RustcEncodable, RustcDecodable, Show)]
pub enum ParamSpace {
TypeSpace, // Type parameters attached to a type definition, trait, or impl
/// Vector of things sorted by param space. Used to keep
/// the set of things declared on the type, self, or method
/// distinct.
-#[deriving(PartialEq, Eq, Clone, Hash, RustcEncodable, RustcDecodable)]
+#[derive(PartialEq, Eq, Clone, Hash, RustcEncodable, RustcDecodable)]
pub struct VecPerParamSpace<T> {
// This was originally represented as a tuple with one Vec<T> for
// each variant of ParamSpace, and that remains the abstraction
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct EnumeratedItems<'a,T:'a> {
vec: &'a VecPerParamSpace<T>,
space_index: uint,
use super::util;
use middle::subst::Subst;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::infer::InferCtxt;
use std::collections::HashSet;
use std::rc::Rc;
};
use middle::infer::InferCtxt;
-use middle::ty::{mod, AsPredicate, ReferencesError, ToPolyTraitRef};
+use middle::ty::{self, AsPredicate, ReferencesError, ToPolyTraitRef};
use syntax::codemap::Span;
use util::ppaux::{Repr, UserString};
use middle::infer::{InferCtxt};
use middle::mem_categorization::Typer;
-use middle::ty::{mod, RegionEscape, Ty};
+use middle::ty::{self, RegionEscape, Ty};
use std::collections::HashSet;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::default::Default;
use middle::mem_categorization::Typer;
use middle::subst;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::infer::InferCtxt;
use std::slice::Iter;
use std::rc::Rc;
/// either identifying an `impl` (e.g., `impl Eq for int`) that
/// provides the required vtable, or else finding a bound that is in
/// scope. The eventual result is usually a `Selection` (defined below).
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Obligation<'tcx, T> {
pub cause: ObligationCause<'tcx>,
pub recursion_depth: uint,
pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
/// Why did we incur this obligation? Used for error reporting.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct ObligationCause<'tcx> {
pub span: Span,
pub code: ObligationCauseCode<'tcx>
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum ObligationCauseCode<'tcx> {
/// Not well classified or should be obvious from span.
MiscObligation,
ImplDerivedObligation(DerivedObligationCause<'tcx>),
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct DerivedObligationCause<'tcx> {
/// The trait reference of the parent obligation that led to the
/// current obligation. Note that only trait obligations lead to
pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
-#[deriving(Clone,Show)]
+#[derive(Clone,Show)]
pub enum SelectionError<'tcx> {
Unimplemented,
Overflow,
pub code: FulfillmentErrorCode<'tcx>
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum FulfillmentErrorCode<'tcx> {
CodeSelectionError(SelectionError<'tcx>),
CodeProjectionError(MismatchedProjectionTypes<'tcx>),
/// ### The type parameter `N`
///
/// See explanation on `VtableImplData`.
-#[deriving(Show,Clone)]
+#[derive(Show,Clone)]
pub enum Vtable<'tcx, N> {
/// Vtable identifying a particular impl.
VtableImpl(VtableImplData<'tcx, N>),
/// is `Obligation`, as one might expect. During trans, however, this
/// is `()`, because trans only requires a shallow resolution of an
/// impl, and nested obligations are satisfied later.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct VtableImplData<'tcx, N> {
pub impl_def_id: ast::DefId,
pub substs: subst::Substs<'tcx>,
pub nested: subst::VecPerParamSpace<N>
}
-#[deriving(Show,Clone)]
+#[derive(Show,Clone)]
pub struct VtableBuiltinData<N> {
pub nested: subst::VecPerParamSpace<N>
}
/// A vtable for some object-safe trait `Foo` automatically derived
/// for the object type `Foo`.
-#[deriving(PartialEq,Eq,Clone)]
+#[derive(PartialEq,Eq,Clone)]
pub struct VtableObjectData<'tcx> {
pub object_ty: Ty<'tcx>,
}
use super::supertraits;
use super::elaborate_predicates;
-use middle::subst::{mod, SelfSpace};
+use middle::subst::{self, SelfSpace};
use middle::traits;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use std::rc::Rc;
use syntax::ast;
use util::ppaux::Repr;
}
/// Reasons a method might not be object-safe.
-#[deriving(Copy,Clone,Show)]
+#[derive(Copy,Clone,Show)]
pub enum MethodViolationCode {
/// e.g., `fn(self)`
ByValueSelf,
use middle::infer;
use middle::subst::Subst;
-use middle::ty::{mod, AsPredicate, ReferencesError, RegionEscape,
+use middle::ty::{self, AsPredicate, ReferencesError, RegionEscape,
HasProjectionTypes, ToPolyTraitRef, Ty};
-use middle::ty_fold::{mod, TypeFoldable, TypeFolder};
+use middle::ty_fold::{self, TypeFoldable, TypeFolder};
use std::rc::Rc;
use util::ppaux::Repr;
TraitSelectionError(SelectionError<'tcx>),
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct MismatchedProjectionTypes<'tcx> {
pub err: ty::type_err<'tcx>
}
use middle::fast_reject;
use middle::mem_categorization::Typer;
use middle::subst::{Subst, Substs, TypeSpace, VecPerParamSpace};
-use middle::ty::{mod, AsPredicate, RegionEscape, ToPolyTraitRef, Ty};
+use middle::ty::{self, AsPredicate, RegionEscape, ToPolyTraitRef, Ty};
use middle::infer;
use middle::infer::{InferCtxt, TypeFreshener};
use middle::ty_fold::TypeFoldable;
previous: Option<&'prev TraitObligationStack<'prev, 'tcx>>
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct SelectionCache<'tcx> {
hashmap: RefCell<HashMap<Rc<ty::TraitRef<'tcx>>,
SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
MethodDidNotMatch,
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum MethodMatchedData {
// In the case of a precise match, we don't really need to store
// how the match was found. So don't.
/// matching where clause. Part of the reason for this is that where
/// clauses can give additional information (like, the types of output
/// parameters) that would have to be inferred from the impl.
-#[deriving(PartialEq,Eq,Show,Clone)]
+#[derive(PartialEq,Eq,Show,Clone)]
enum SelectionCandidate<'tcx> {
BuiltinCandidate(ty::BuiltinBound),
ParamCandidate(ty::PolyTraitRef<'tcx>),
AmbiguousBuiltin
}
-#[deriving(Show)]
+#[derive(Show)]
enum EvaluationResult<'tcx> {
EvaluatedToOk,
EvaluatedToAmbig,
use middle::subst::{Substs, VecPerParamSpace};
use middle::infer::InferCtxt;
-use middle::ty::{mod, Ty, AsPredicate, ToPolyTraitRef};
+use middle::ty::{self, Ty, AsPredicate, ToPolyTraitRef};
use std::collections::HashSet;
use std::fmt;
use std::rc::Rc;
use metadata::csearch;
use middle;
use middle::const_eval;
-use middle::def::{mod, DefMap, ExportMap};
+use middle::def::{self, DefMap, ExportMap};
use middle::dependency_format;
use middle::lang_items::{FnTraitLangItem, FnMutTraitLangItem};
use middle::lang_items::{FnOnceTraitLangItem, TyDescStructLangItem};
use middle::resolve_lifetime;
use middle::infer;
use middle::stability;
-use middle::subst::{mod, Subst, Substs, VecPerParamSpace};
+use middle::subst::{self, Subst, Substs, VecPerParamSpace};
use middle::traits;
use middle::ty;
-use middle::ty_fold::{mod, TypeFoldable, TypeFolder};
+use middle::ty_fold::{self, TypeFoldable, TypeFolder};
use middle::ty_walk::TypeWalker;
use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string};
use util::ppaux::{trait_store_to_string, ty_to_string};
use arena::TypedArena;
use std::borrow::BorrowFrom;
use std::cell::{Cell, RefCell};
-use std::cmp::{mod, Ordering};
-use std::fmt::{mod, Show};
+use std::cmp::{self, Ordering};
+use std::fmt::{self, Show};
use std::hash::{Hash, sip, Writer};
use std::mem;
use std::ops;
use syntax::ast::{MutImmutable, MutMutable, Name, NamedField, NodeId};
use syntax::ast::{Onceness, StmtExpr, StmtSemi, StructField, UnnamedField};
use syntax::ast::{Visibility};
-use syntax::ast_util::{mod, is_local, lit_is_str, local_def, PostExpansionMethod};
-use syntax::attr::{mod, AttrMetaMethods};
+use syntax::ast_util::{self, is_local, lit_is_str, local_def, PostExpansionMethod};
+use syntax::attr::{self, AttrMetaMethods};
use syntax::codemap::Span;
-use syntax::parse::token::{mod, InternedString, special_idents};
+use syntax::parse::token::{self, InternedString, special_idents};
use syntax::{ast, ast_map};
pub type Disr = u64;
pub glob_map: Option<GlobMap>,
}
-#[deriving(Copy, PartialEq, Eq, Hash)]
+#[derive(Copy, PartialEq, Eq, Hash)]
pub struct field<'tcx> {
pub name: ast::Name,
pub mt: mt<'tcx>
}
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub enum ImplOrTraitItemContainer {
TraitContainer(ast::DefId),
ImplContainer(ast::DefId),
}
}
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub enum ImplOrTraitItem<'tcx> {
MethodTraitItem(Rc<Method<'tcx>>),
TypeTraitItem(Rc<AssociatedType>),
}
}
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub enum ImplOrTraitItemId {
MethodTraitItemId(ast::DefId),
TypeTraitItemId(ast::DefId),
}
}
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct Method<'tcx> {
pub name: ast::Name,
pub generics: ty::Generics<'tcx>,
}
}
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub struct AssociatedType {
pub name: ast::Name,
pub vis: ast::Visibility,
pub container: ImplOrTraitItemContainer,
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub struct mt<'tcx> {
pub ty: Ty<'tcx>,
pub mutbl: ast::Mutability,
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show)]
pub enum TraitStore {
/// Box<Trait>
UniqTraitStore,
RegionTraitStore(Region, ast::Mutability),
}
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub struct field_ty {
pub name: Name,
pub id: DefId,
// Contains information needed to resolve types and (in the future) look up
// the types of AST nodes.
-#[deriving(Copy, PartialEq, Eq, Hash)]
+#[derive(Copy, PartialEq, Eq, Hash)]
pub struct creader_cache_key {
pub cnum: CrateNum,
pub pos: uint,
pub len: uint
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum ast_ty_to_ty_cache_entry<'tcx> {
atttce_unresolved, /* not resolved yet */
atttce_resolved(Ty<'tcx>) /* resolved to a type, irrespective of region */
}
-#[deriving(Clone, PartialEq, RustcDecodable, RustcEncodable)]
+#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable)]
pub struct ItemVariances {
pub types: VecPerParamSpace<Variance>,
pub regions: VecPerParamSpace<Variance>,
}
-#[deriving(Clone, PartialEq, RustcDecodable, RustcEncodable, Show, Copy)]
+#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Show, Copy)]
pub enum Variance {
Covariant, // T<A> <: T<B> iff A <: B -- e.g., function return type
Invariant, // T<A> <: T<B> iff B == A -- e.g., type of mutable cell
Bivariant, // T<A> <: T<B> -- e.g., unused type parameter
}
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub enum AutoAdjustment<'tcx> {
AdjustAddEnv(ast::DefId, ty::TraitStore),
AdjustReifyFnPointer(ast::DefId), // go from a fn-item type to a fn-pointer type
AdjustDerefRef(AutoDerefRef<'tcx>)
}
-#[deriving(Clone, PartialEq, Show)]
+#[derive(Clone, PartialEq, Show)]
pub enum UnsizeKind<'tcx> {
// [T, ..n] -> [T], the uint field is n.
UnsizeLength(uint),
UnsizeVtable(TyTrait<'tcx>, /* the self type of the trait */ Ty<'tcx>)
}
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct AutoDerefRef<'tcx> {
pub autoderefs: uint,
pub autoref: Option<AutoRef<'tcx>>
}
-#[deriving(Clone, PartialEq, Show)]
+#[derive(Clone, PartialEq, Show)]
pub enum AutoRef<'tcx> {
/// Convert from T to &T
/// The third field allows us to wrap other AutoRef adjustments.
}
}
-#[deriving(Clone, Copy, RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Show)]
+#[derive(Clone, Copy, RustcEncodable, RustcDecodable, PartialEq, PartialOrd, Show)]
pub struct param_index {
pub space: subst::ParamSpace,
pub index: uint
}
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub enum MethodOrigin<'tcx> {
// fully statically resolved method
MethodStatic(ast::DefId),
// details for a method invoked with a receiver whose type is a type parameter
// with a bounded trait.
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct MethodParam<'tcx> {
// the precise trait reference that occurs as a bound -- this may
// be a supertrait of what the user actually typed. Note that it
}
// details for a method invoked with a receiver whose type is an object
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct MethodObject<'tcx> {
// the (super)trait containing the method to be invoked
pub trait_ref: Rc<ty::TraitRef<'tcx>>,
pub real_index: uint,
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct MethodCallee<'tcx> {
pub origin: MethodOrigin<'tcx>,
pub ty: Ty<'tcx>,
/// needed to add to the side tables. Thus to disambiguate
/// we also keep track of whether there's an adjustment in
/// our key.
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub struct MethodCall {
pub expr_id: ast::NodeId,
pub adjustment: ExprAdjustment
}
-#[deriving(Clone, PartialEq, Eq, Hash, Show, RustcEncodable, RustcDecodable, Copy)]
+#[derive(Clone, PartialEq, Eq, Hash, Show, RustcEncodable, RustcDecodable, Copy)]
pub enum ExprAdjustment {
NoAdjustment,
AutoDeref(uint),
// Resolutions for bounds of all parameters, left to right, for a given path.
pub type vtable_res<'tcx> = VecPerParamSpace<vtable_param_res<'tcx>>;
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum vtable_origin<'tcx> {
/*
Statically known vtable. def_id gives the impl item
/// will push one or more such restriction into the
/// `transmute_restrictions` vector during `intrinsicck`. They are
/// then checked during `trans` by the fn `check_intrinsics`.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct TransmuteRestriction<'tcx> {
/// The span whence the restriction comes.
pub span: Span,
// variable names.
mod inner {
use middle::ty;
- #[deriving(Copy)]
+ #[derive(Copy)]
struct DebugStat {
total: uint,
region_infer: uint,
}
}
-#[deriving(Show)]
+#[derive(Show)]
pub struct TyS<'tcx> {
pub sty: sty<'tcx>,
pub flags: TypeFlags,
ty.region_depth > depth
}
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct BareFnTy<'tcx> {
pub unsafety: ast::Unsafety,
pub abi: abi::Abi,
pub sig: PolyFnSig<'tcx>,
}
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct ClosureTy<'tcx> {
pub unsafety: ast::Unsafety,
pub onceness: ast::Onceness,
pub abi: abi::Abi,
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum FnOutput<'tcx> {
FnConverging(Ty<'tcx>),
FnDiverging
/// - `inputs` is the list of arguments and their modes.
/// - `output` is the return type.
/// - `variadic` indicates whether this is a varidic function. (only true for foreign fns)
-#[deriving(Clone, PartialEq, Eq, Hash)]
+#[derive(Clone, PartialEq, Eq, Hash)]
pub struct FnSig<'tcx> {
pub inputs: Vec<Ty<'tcx>>,
pub output: FnOutput<'tcx>,
pub type PolyFnSig<'tcx> = Binder<FnSig<'tcx>>;
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub struct ParamTy {
pub space: subst::ParamSpace,
pub idx: u32,
/// is the outer fn.
///
/// [dbi]: http://en.wikipedia.org/wiki/De_Bruijn_index
-#[deriving(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show, Copy)]
pub struct DebruijnIndex {
// We maintain the invariant that this is never 0. So 1 indicates
// the innermost binder. To ensure this, create with `DebruijnIndex::new`.
}
/// Representation of regions:
-#[deriving(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Show, Copy)]
pub enum Region {
// Region bound in a type or fn declaration which will be
// substituted 'early' -- that is, at the same time when type
/// Upvars do not get their own node-id. Instead, we use the pair of
/// the original var id (that is, the root variable that is referenced
/// by the upvar) and the id of the closure expression.
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)]
pub struct UpvarId {
pub var_id: ast::NodeId,
pub closure_expr_id: ast::NodeId,
}
-#[deriving(Clone, PartialEq, Eq, Hash, Show, RustcEncodable, RustcDecodable, Copy)]
+#[derive(Clone, PartialEq, Eq, Hash, Show, RustcEncodable, RustcDecodable, Copy)]
pub enum BorrowKind {
/// Data must be immutable and is aliasable.
ImmBorrow,
/// - Through mutation, the borrowed upvars can actually escape
/// the closure, so sometimes it is necessary for them to be larger
/// than the closure lifetime itself.
-#[deriving(PartialEq, Clone, RustcEncodable, RustcDecodable, Show, Copy)]
+#[derive(PartialEq, Clone, RustcEncodable, RustcDecodable, Show, Copy)]
pub struct UpvarBorrow {
pub kind: BorrowKind,
pub region: ty::Region,
}
}
-#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
+#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
RustcEncodable, RustcDecodable, Show, Copy)]
/// A "free" region `fr` can be interpreted as "some region
/// at least as big as the scope `fr.scope`".
pub bound_region: BoundRegion
}
-#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
+#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash,
RustcEncodable, RustcDecodable, Show, Copy)]
pub enum BoundRegion {
/// An anonymous region parameter for a given fn (&T)
// NB: If you change this, you'll probably want to change the corresponding
// AST structure in libsyntax/ast.rs as well.
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub enum sty<'tcx> {
ty_bool,
ty_char,
// on non-useful type error messages)
}
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct TyTrait<'tcx> {
pub principal: ty::PolyTraitRef<'tcx>,
pub bounds: ExistentialBounds<'tcx>,
/// Note that a `TraitRef` introduces a level of region binding, to
/// account for higher-ranked trait bounds like `T : for<'a> Foo<&'a
/// U>` or higher-ranked object types.
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct TraitRef<'tcx> {
pub def_id: DefId,
pub substs: &'tcx Substs<'tcx>,
/// erase, or otherwise "discharge" these bound reons, we change the
/// type from `Binder<T>` to just `T` (see
/// e.g. `liberate_late_bound_regions`).
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct Binder<T>(pub T);
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
pub enum IntVarValue {
IntType(ast::IntTy),
UintType(ast::UintTy),
}
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub enum terr_vstore_kind {
terr_vec,
terr_str,
terr_trait
}
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub struct expected_found<T> {
pub expected: T,
pub found: T
}
// Data structures used in type unification
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub enum type_err<'tcx> {
terr_mismatch,
terr_unsafety_mismatch(expected_found<ast::Unsafety>),
/// Bounds suitable for a named type parameter like `A` in `fn foo<A>`
/// as well as the existential type parameter in an object type.
-#[deriving(PartialEq, Eq, Hash, Clone, Show)]
+#[derive(PartialEq, Eq, Hash, Clone, Show)]
pub struct ParamBounds<'tcx> {
pub region_bounds: Vec<ty::Region>,
pub builtin_bounds: BuiltinBounds,
/// major difference between this case and `ParamBounds` is that
/// general purpose trait bounds are omitted and there must be
/// *exactly one* region.
-#[deriving(PartialEq, Eq, Hash, Clone, Show)]
+#[derive(PartialEq, Eq, Hash, Clone, Show)]
pub struct ExistentialBounds<'tcx> {
pub region_bound: ty::Region,
pub builtin_bounds: BuiltinBounds,
pub type BuiltinBounds = EnumSet<BuiltinBound>;
-#[deriving(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
+#[derive(Clone, RustcEncodable, PartialEq, Eq, RustcDecodable, Hash,
Show, Copy)]
#[repr(uint)]
pub enum BuiltinBound {
}
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct TyVid {
pub index: u32
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct IntVid {
pub index: u32
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FloatVid {
pub index: u32
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub struct RegionVid {
pub index: u32
}
-#[deriving(Clone, Copy, PartialEq, Eq, Hash)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum InferTy {
TyVar(TyVid),
IntVar(IntVid),
FreshIntTy(u32),
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
pub enum UnconstrainedNumeric {
UnconstrainedFloat,
UnconstrainedInt,
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, Eq, Hash, Show, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, Eq, Hash, Show, Copy)]
pub enum InferRegion {
ReVar(RegionVid),
ReSkolemized(u32, BoundRegion)
}
}
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct TypeParameterDef<'tcx> {
pub name: ast::Name,
pub def_id: ast::DefId,
pub default: Option<Ty<'tcx>>,
}
-#[deriving(RustcEncodable, RustcDecodable, Clone, Show)]
+#[derive(RustcEncodable, RustcDecodable, Clone, Show)]
pub struct RegionParameterDef {
pub name: ast::Name,
pub def_id: ast::DefId,
/// Information about the formal type/lifetime parameters associated
/// with an item or method. Analogous to ast::Generics.
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct Generics<'tcx> {
pub types: VecPerParamSpace<TypeParameterDef<'tcx>>,
pub regions: VecPerParamSpace<RegionParameterDef>,
}
}
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub enum Predicate<'tcx> {
/// Corresponds to `where Foo : Bar<A,B,C>`. `Foo` here would be
/// the `Self` type of the trait reference and `A`, `B`, and `C`
Projection(PolyProjectionPredicate<'tcx>),
}
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct TraitPredicate<'tcx> {
pub trait_ref: Rc<TraitRef<'tcx>>
}
}
}
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct EquatePredicate<'tcx>(pub Ty<'tcx>, pub Ty<'tcx>); // `0 == 1`
pub type PolyEquatePredicate<'tcx> = ty::Binder<EquatePredicate<'tcx>>;
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct OutlivesPredicate<A,B>(pub A, pub B); // `A : B`
pub type PolyOutlivesPredicate<A,B> = ty::Binder<OutlivesPredicate<A,B>>;
pub type PolyRegionOutlivesPredicate = PolyOutlivesPredicate<ty::Region, ty::Region>;
/// equality between arbitrary types. Processing an instance of Form
/// #2 eventually yields one of these `ProjectionPredicate`
/// instances to normalize the LHS.
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct ProjectionPredicate<'tcx> {
pub projection_ty: ProjectionTy<'tcx>,
pub ty: Ty<'tcx>,
/// Represents the projection of an associated type. In explicit UFCS
/// form this would be written `<T as Trait<..>>::N`.
-#[deriving(Clone, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, Hash, Show)]
pub struct ProjectionTy<'tcx> {
/// The trait reference `T as Trait<..>`.
pub trait_ref: Rc<ty::TraitRef<'tcx>>,
/// `[[], [U:Bar<T>]]`. Now if there were some particular reference
/// like `Foo<int,uint>`, then the `GenericBounds` would be `[[],
/// [uint:Bar<int>]]`.
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct GenericBounds<'tcx> {
pub predicates: VecPerParamSpace<Predicate<'tcx>>,
}
/// bound lifetime parameters are replaced with free ones, but in the
/// future I hope to refine the representation of types so as to make
/// more distinctions clearer.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct ParameterEnvironment<'a, 'tcx:'a> {
pub tcx: &'a ctxt<'tcx>,
/// stray references in a comment or something). We try to reserve the
/// "poly" prefix to refer to higher-ranked things, as in
/// `PolyTraitRef`.
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct TypeScheme<'tcx> {
pub generics: Generics<'tcx>,
pub ty: Ty<'tcx>
/// Records the substitutions used to translate the polytype for an
/// item into the monotype of an item reference.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct ItemSubsts<'tcx> {
pub substs: Substs<'tcx>,
}
/// Records information about each unboxed closure.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct UnboxedClosure<'tcx> {
/// The type of the unboxed closure.
pub closure_type: ClosureTy<'tcx>,
pub kind: UnboxedClosureKind,
}
-#[deriving(Clone, Copy, PartialEq, Eq, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Show)]
pub enum UnboxedClosureKind {
FnUnboxedClosureKind,
FnMutUnboxedClosureKind,
/// The reason we compute type contents and not kinds is that it is
/// easier for me (nmatsakis) to think about what is contained within
/// a type than to think about what is *not* contained within a type.
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct TypeContents {
pub bits: u64
}
///
/// The ordering of the cases is significant. They are sorted so that cmp::max
/// will keep the "more erroneous" of two values.
-#[deriving(Copy, PartialOrd, Ord, Eq, PartialEq, Show)]
+#[derive(Copy, PartialOrd, Ord, Eq, PartialEq, Show)]
pub enum Representability {
Representable,
ContainsRecursive,
/// two kinds of rvalues is an artifact of trans which reflects how we will
/// generate code for that kind of expression. See trans/expr.rs for more
/// information.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum ExprKind {
LvalueExpr,
RvalueDpsExpr,
cx.sess.bug("couldn't find associated type parameter index")
}
-#[deriving(Copy, PartialEq, Eq)]
+#[derive(Copy, PartialEq, Eq)]
pub struct AssociatedTypeInfo {
pub def_id: ast::DefId,
pub index: uint,
}
// Enum information
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct VariantInfo<'tcx> {
pub args: Vec<Ty<'tcx>>,
pub arg_names: Option<Vec<ast::Ident>>,
with_path(cx, id, |path| ast_map::path_to_string(path)).to_string()
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum DtorKind {
NoDtor,
TraitDtor(DefId, bool)
}).collect()
}
-#[deriving(Copy, Clone)]
+#[derive(Copy, Clone)]
pub struct UnboxedClosureUpvar<'tcx> {
pub def: def::Def,
pub span: Span,
/// The category of explicit self.
-#[deriving(Clone, Copy, Eq, PartialEq, Show)]
+#[derive(Clone, Copy, Eq, PartialEq, Show)]
pub enum ExplicitSelfCategory {
StaticExplicitSelfCategory,
ByValueExplicitSelfCategory,
}
/// A free variable referred to in a function.
-#[deriving(Copy, RustcEncodable, RustcDecodable)]
+#[derive(Copy, RustcEncodable, RustcDecodable)]
pub struct Freevar {
/// The variable being accessed free.
pub def: def::Def,
trait_ref.substs.clone().with_method(meth_tps, meth_regions)
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum CopyImplementationError {
FieldDoesNotImplementCopy(ast::Name),
VariantDoesNotImplementCopy(ast::Name),
use middle::subst;
use middle::subst::VecPerParamSpace;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::traits;
use std::rc::Rc;
use syntax::owned_slice::OwnedSlice;
/// track the Debruijn index nesting level.
fn exit_region_binder(&mut self) { }
+ fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T>
+ where T : TypeFoldable<'tcx> + Repr<'tcx>
+ {
+ // FIXME(#20526) this should replace `enter_region_binder`/`exit_region_binder`.
+ super_fold_binder(self, t)
+ }
+
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
super_fold_ty(self, t)
}
}
}
-impl<'tcx, T:TypeFoldable<'tcx>> TypeFoldable<'tcx> for ty::Binder<T> {
+impl<'tcx, T:TypeFoldable<'tcx>+Repr<'tcx>> TypeFoldable<'tcx> for ty::Binder<T> {
fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Binder<T> {
- folder.enter_region_binder();
- let result = ty::Binder(self.0.fold_with(folder));
- folder.exit_region_binder();
- result
+ folder.fold_binder(self)
}
}
//
// They should invoke `foo.fold_with()` to do recursive folding.
+pub fn super_fold_binder<'tcx, T, U>(this: &mut T,
+ binder: &ty::Binder<U>)
+ -> ty::Binder<U>
+ where T : TypeFolder<'tcx>, U : TypeFoldable<'tcx>
+{
+ this.enter_region_binder();
+ let result = ty::Binder(binder.0.fold_with(this));
+ this.exit_region_binder();
+ result
+}
+
pub fn super_fold_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
ty: Ty<'tcx>)
-> Ty<'tcx> {
//! An iterator over the type substructure.
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use std::iter::Iterator;
pub struct TypeWalker<'tcx> {
pub use self::OutputType::*;
pub use self::DebugInfoLevel::*;
-use session::{early_error, Session};
+use session::{early_error, early_warn, Session};
use session::search_paths::SearchPaths;
use rustc_back::target::Target;
pub uint_type: UintTy,
}
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
pub enum OptLevel {
No, // -O0
Less, // -O1
Aggressive // -O3
}
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
pub enum DebugInfoLevel {
NoDebugInfo,
LimitedDebugInfo,
FullDebugInfo,
}
-#[deriving(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
+#[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
pub enum OutputType {
OutputTypeBitcode,
OutputTypeAssembly,
OutputTypeDepInfo,
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Options {
// The crate config requested for the session, which may be combined
// with additional crate configurations during the compile process
pub alt_std_name: Option<String>
}
-#[deriving(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
#[allow(missing_copy_implementations)]
pub enum PrintRequest {
FileNames,
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct OutputFilenames {
pub out_directory: Path,
pub out_filestem: String,
// users can have their own entry
// functions that don't start a
// scheduler
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum EntryFnType {
EntryMain,
EntryStart,
EntryNone,
}
-#[deriving(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash)]
+#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash)]
pub enum CrateType {
CrateTypeExecutable,
CrateTypeDylib,
]
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum Passes {
SomePasses(Vec<String>),
AllPasses,
macro_rules! cgoptions {
($($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
(
- #[deriving(Clone)]
+ #[derive(Clone)]
pub struct CodegenOptions { $(pub $opt: $t),* }
pub fn basic_codegen_options() -> CodegenOptions {
mod cgsetters {
use super::{CodegenOptions, Passes, SomePasses, AllPasses};
- use std::str::from_str;
$(
pub fn $opt(cg: &mut CodegenOptions, v: Option<&str>) -> bool {
}
fn parse_uint(slot: &mut uint, v: Option<&str>) -> bool {
- match v.and_then(from_str) {
+ match v.and_then(|s| s.parse()) {
Some(i) => { *slot = i; true },
None => false
}
fn parse_opt_uint(slot: &mut Option<uint>, v: Option<&str>) -> bool {
match v {
- Some(s) => { *slot = from_str(s); slot.is_some() }
+ Some(s) => { *slot = s.parse(); slot.is_some() }
None => { *slot = None; true }
}
}
.collect()
}
-#[deriving(Copy, Clone, PartialEq, Eq, Show)]
+#[derive(Copy, Clone, PartialEq, Eq, Show)]
pub enum OptionStability { Stable, Unstable }
-#[deriving(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq)]
pub struct RustcOptGroup {
pub opt_group: getopts::OptGroup,
pub stability: OptionStability,
"[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
opt::multi("", "print", "Comma separated list of compiler information to \
print on stdout",
- "[crate-name|output-file-names|sysroot]"),
+ "[crate-name|file-names|sysroot]"),
opt::flag("g", "", "Equivalent to -C debuginfo=2"),
opt::flag("O", "", "Equivalent to -C opt-level=2"),
opt::opt("o", "", "Write output to <filename>", "FILENAME"),
}
let parse_only = if matches.opt_present("parse-only") {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("--parse-only is deprecated in favor of -Z parse-only");
+ // FIXME(acrichto) remove this eventually
+ early_warn("--parse-only is deprecated in favor of -Z parse-only");
true
} else {
debugging_opts & PARSE_ONLY != 0
};
let no_trans = if matches.opt_present("no-trans") {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("--no-trans is deprecated in favor of -Z no-trans");
+ // FIXME(acrichto) remove this eventually
+ early_warn("--no-trans is deprecated in favor of -Z no-trans");
true
} else {
debugging_opts & NO_TRANS != 0
};
let no_analysis = if matches.opt_present("no-analysis") {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("--no-analysis is deprecated in favor of -Z no-analysis");
+ // FIXME(acrichto) remove this eventually
+ early_warn("--no-analysis is deprecated in favor of -Z no-analysis");
true
} else {
debugging_opts & NO_ANALYSIS != 0
}
Default
} else if matches.opt_present("opt-level") {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("--opt-level=N is deprecated in favor of -C opt-level=N");
+ // FIXME(acrichto) remove this eventually
+ early_warn("--opt-level=N is deprecated in favor of -C opt-level=N");
match matches.opt_str("opt-level").as_ref().map(|s| s.as_slice()) {
None |
Some("0") => No,
}
FullDebugInfo
} else if matches.opt_present("debuginfo") {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("--debuginfo=N is deprecated in favor of -C debuginfo=N");
+ // FIXME(acrichto) remove this eventually
+ early_warn("--debuginfo=N is deprecated in favor of -C debuginfo=N");
match matches.opt_str("debuginfo").as_ref().map(|s| s.as_slice()) {
Some("0") => NoDebugInfo,
Some("1") => LimitedDebugInfo,
let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
let test = matches.opt_present("test");
let write_dependency_info = if matches.opt_present("dep-info") {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("--dep-info has been deprecated in favor of --emit");
+ // FIXME(acrichto) remove this eventually
+ early_warn("--dep-info has been deprecated in favor of --emit");
(true, matches.opt_str("dep-info").map(|p| Path::new(p)))
} else {
(output_types.contains(&OutputTypeDepInfo), None)
}
}).collect::<Vec<_>>();
if matches.opt_present("print-crate-name") {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("--print-crate-name has been deprecated in favor of \
- // --print crate-name");
+ // FIXME(acrichto) remove this eventually
+ early_warn("--print-crate-name has been deprecated in favor of \
+ --print crate-name");
prints.push(PrintRequest::CrateName);
}
if matches.opt_present("print-file-name") {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("--print-file-name has been deprecated in favor of \
- // --print file-names");
+ // FIXME(acrichto) remove this eventually
+ early_warn("--print-file-name has been deprecated in favor of \
+ --print file-names");
prints.push(PrintRequest::FileNames);
}
if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
- // FIXME(acrichto) uncomment deprecation warning
- // early_warn("-C remark will not show source locations without \
- // --debuginfo");
+ early_warn("-C remark will not show source locations without \
+ --debuginfo");
}
let color = match matches.opt_str("color").as_ref().map(|s| s[]) {
use syntax::ast::NodeId;
use syntax::codemap::Span;
-use syntax::diagnostic::{mod, Emitter};
+use syntax::diagnostic::{self, Emitter};
use syntax::diagnostics;
use syntax::feature_gate;
use syntax::parse;
use std::slice;
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct SearchPaths {
paths: Vec<(PathKind, Path)>,
}
iter: slice::Iter<'a, (PathKind, Path)>,
}
-#[deriving(Eq, PartialEq, Clone, Copy)]
+#[derive(Eq, PartialEq, Clone, Copy)]
pub enum PathKind {
Native,
Crate,
// Useful type to use with `Result<>` indicate that an error has already
// been reported to the user, so no need to continue checking.
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub struct ErrorReported;
pub fn time<T, U, F>(do_it: bool, what: &str, u: U, f: F) -> T where
// Test bytelength agnosticity
for c in range(0u32, MAX as u32)
.filter_map(|i| from_u32(i))
- .map(|i| String::from_char(1, i)) {
+ .map(|i| i.to_string()) {
assert_eq!(lev_distance(c[], c[]), 0);
}
///
/// This uses FNV hashing, as described here:
/// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
-#[deriving(Clone, Copy, Default)]
+#[derive(Clone, Copy, Default)]
pub struct FnvHasher;
#[allow(missing_copy_implementations)]
use std::mem;
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
pub enum UndoLog<T,U> {
/// Indicates where a snapshot started.
OpenSnapshot,
use syntax::ast;
use syntax::visit;
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
pub struct Svh {
hash: String,
}
// This enum represents the different potential bits of code the
// visitor could encounter that could affect the ABI for the crate,
// and assigns each a distinct tag to feed into the hash computation.
- #[deriving(Hash)]
+ #[derive(Hash)]
enum SawAbiComponent<'a> {
// FIXME (#14132): should we include (some function of)
/// because the SVH is just a developer convenience; there is no
/// guarantee of collision-freedom, hash collisions are just
/// (hopefully) unlikely.)
- #[deriving(Hash)]
+ #[derive(Hash)]
pub enum SawExprComponent<'a> {
SawExprLoop(Option<token::InternedString>),
}
/// SawStmtComponent is analogous to SawExprComponent, but for statements.
- #[deriving(Hash)]
+ #[derive(Hash)]
pub enum SawStmtComponent {
SawStmtDecl,
SawStmtExpr,
/// Everything `rustc` knows about how to compile for a specific target.
///
/// Every field here must be specified, and has no default value.
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct Target {
/// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
pub data_layout: String,
///
/// This has an implementation of `Default`, see each field for what the default is. In general,
/// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub struct TargetOptions {
/// Linker to invoke. Defaults to "cc".
pub linker: String,
}
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
enum UseError<'tcx> {
UseOk,
UseWhileBorrowed(/*loan*/Rc<LoanPath<'tcx>>, /*loan*/Span)
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
-#[deriving(PartialEq, Eq, PartialOrd, Ord)]
+#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Fragment {
// This represents the path described by the move path index
Just(MovePathIndex),
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct MoveSpanAndPath {
pub span: codemap::Span,
pub ident: ast::Ident
use std::rc::Rc;
-#[deriving(Show)]
+#[derive(Show)]
pub enum RestrictionResult<'tcx> {
Safe,
SafeIf(Rc<LoanPath<'tcx>>, Vec<Rc<LoanPath<'tcx>>>)
use rustc::middle::expr_use_visitor as euv;
use rustc::middle::mem_categorization as mc;
use rustc::middle::region;
-use rustc::middle::ty::{mod, Ty};
+use rustc::middle::ty::{self, Ty};
use rustc::util::ppaux::{note_and_explain_region, Repr, UserString};
use std::rc::Rc;
use std::string::String;
pub mod move_data;
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct LoanDataFlowOperator;
pub type LoanDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, LoanDataFlowOperator>;
}
}
-#[deriving(Eq, Hash, Show)]
+#[derive(Eq, Hash, Show)]
pub struct LoanPath<'tcx> {
kind: LoanPathKind<'tcx>,
ty: ty::Ty<'tcx>,
}
}
-#[deriving(PartialEq, Eq, Hash, Show)]
+#[derive(PartialEq, Eq, Hash, Show)]
pub enum LoanPathKind<'tcx> {
LpVar(ast::NodeId), // `x` in doc.rs
LpUpvar(ty::UpvarId), // `x` captured by-value into closure
// b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
static DOWNCAST_PRINTED_OPERATOR : &'static str = " as ";
-#[deriving(Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Copy, PartialEq, Eq, Hash, Show)]
pub enum LoanPathElem {
LpDeref(mc::PointerKind), // `*LV` in doc.rs
LpInterior(mc::InteriorKind) // `LV.f` in doc.rs
// Errors
// Errors that can occur
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
#[allow(missing_copy_implementations)]
pub enum bckerr_code {
err_mutbl,
// Combination of an error code and the categorization of the expression
// that caused it
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
pub struct BckError<'tcx> {
span: Span,
cause: euv::LoanCause,
code: bckerr_code
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum AliasableViolationKind {
MutabilityViolation,
BorrowViolation(euv::LoanCause)
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum MovedValueUseKind {
MovedInUse,
MovedInCapture,
}
/// Index into `MoveData.paths`, used like a pointer
-#[deriving(Copy, PartialEq, Eq, PartialOrd, Ord, Show)]
+#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Show)]
pub struct MovePathIndex(uint);
impl MovePathIndex {
MovePathIndex(uint::MAX);
/// Index into `MoveData.moves`, used like a pointer
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub struct MoveIndex(uint);
impl MoveIndex {
pub next_sibling: MovePathIndex,
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum MoveKind {
Declared, // When declared, variables start out "moved".
MoveExpr, // Expression or binding that moves a variable
Captured // Closure creation that moves a value
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Move {
/// Path being moved.
pub path: MovePathIndex,
pub next_move: MoveIndex
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Assignment {
/// Path being assigned.
pub path: MovePathIndex,
pub span: Span,
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct VariantMatch {
/// downcast to the variant.
pub path: MovePathIndex,
pub mode: euv::MatchMode
}
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct MoveDataFlowOperator;
pub type MoveDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, MoveDataFlowOperator>;
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct AssignDataFlowOperator;
pub type AssignDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, AssignDataFlowOperator>;
use std::rc::Rc;
use std::borrow::IntoCow;
-#[deriving(Show, Copy)]
+#[derive(Show, Copy)]
pub enum Variant {
Loans,
Moves,
let suffix = self.dataflow_for(dataflow::Exit, n);
let inner_label = self.inner.node_label(n);
inner_label
- .prefix_line(dot::LabelStr(prefix.into_cow()))
- .suffix_line(dot::LabelStr(suffix.into_cow()))
+ .prefix_line(dot::LabelText::LabelStr(prefix.into_cow()))
+ .suffix_line(dot::LabelText::LabelStr(suffix.into_cow()))
}
fn edge_label(&'a self, e: &Edge<'a>) -> dot::LabelText<'a> { self.inner.edge_label(e) }
}
// except according to those terms.
use rustc::session::Session;
-use rustc::session::config::{mod, Input, OutputFilenames};
+use rustc::session::config::{self, Input, OutputFilenames};
use rustc::session::search_paths::PathKind;
use rustc::lint;
use rustc::metadata::creader;
use rustc::metadata;
use rustc::DIAGNOSTICS;
-use std::any::AnyRefExt;
use std::cmp::Ordering::Equal;
use std::io;
use std::iter::repeat;
use rustc::middle::cfg;
use rustc::middle::cfg::graphviz::LabelledCFG;
use rustc::session::Session;
-use rustc::session::config::{mod, Input};
+use rustc::session::config::{self, Input};
use rustc::util::ppaux;
use rustc_borrowck as borrowck;
use rustc_borrowck::graphviz as borrowck_dot;
use syntax::ast;
-use syntax::ast_map::{mod, blocks, NodePrinter};
+use syntax::ast_map::{self, blocks, NodePrinter};
use syntax::codemap;
-use syntax::fold::{mod, Folder};
+use syntax::fold::{self, Folder};
use syntax::print::{pp, pprust};
use syntax::ptr::P;
use graphviz as dot;
-use std::io::{mod, MemReader};
+use std::io::{self, MemReader};
use std::option;
use std::str::FromStr;
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum PpSourceMode {
PpmNormal,
PpmEveryBodyLoops,
PpmExpandedHygiene,
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum PpMode {
PpmSource(PpSourceMode),
PpmFlowGraph,
variants
}
-#[deriving(Clone, Show)]
+#[derive(Clone, Show)]
pub enum UserIdentifiedItem {
ItemViaNode(ast::NodeId),
ItemViaPath(Vec<String>),
use driver;
use rustc_resolve as resolve;
use rustc_typeck::middle::lang_items;
-use rustc_typeck::middle::region::{mod, CodeExtent};
+use rustc_typeck::middle::region::{self, CodeExtent};
use rustc_typeck::middle::resolve_lifetime;
use rustc_typeck::middle::stability;
use rustc_typeck::middle::subst;
use rustc_typeck::middle::subst::Subst;
-use rustc_typeck::middle::ty::{mod, Ty};
+use rustc_typeck::middle::ty::{self, Ty};
use rustc_typeck::middle::infer::combine::Combine;
use rustc_typeck::middle::infer;
use rustc_typeck::middle::infer::lub::Lub;
use rustc_typeck::middle::infer::glb::Glb;
use rustc_typeck::middle::infer::sub::Sub;
use rustc_typeck::util::ppaux::{ty_to_string, Repr, UserString};
-use rustc::session::{mod,config};
+use rustc::session::{self,config};
use syntax::{abi, ast, ast_map};
use syntax::codemap;
use syntax::codemap::{Span, CodeMap, DUMMY_SP};
use {ValueRef, TwineRef, DebugLocRef, DiagnosticInfoRef};
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum OptimizationDiagnosticKind {
OptimizationRemark,
OptimizationMissed,
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Diagnostic {
Optimization(OptimizationDiagnostic),
// Consts for the LLVM CallConv type, pre-cast to uint.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum CallConv {
CCallConv = 0,
FastCallConv = 8,
X86_64_Win64 = 79,
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Visibility {
LLVMDefaultVisibility = 0,
HiddenVisibility = 1,
// DLLExportLinkage, GhostLinkage and LinkOnceODRAutoHideLinkage.
// LinkerPrivateLinkage and LinkerPrivateWeakLinkage are not included either;
// they've been removed in upstream LLVM commit r203866.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Linkage {
ExternalLinkage = 0,
AvailableExternallyLinkage = 1,
}
#[repr(C)]
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum DiagnosticSeverity {
Error,
Warning,
#[repr(u64)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum OtherAttribute {
// The following are not really exposed in
// the LLVM c api so instead to add these
NonNullAttribute = 1 << 44,
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum SpecialAttribute {
DereferenceableAttribute(u64)
}
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum AttributeSet {
ReturnIndex = 0,
FunctionIndex = !0
}
// enum for the LLVM IntPredicate type
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum IntPredicate {
IntEQ = 32,
IntNE = 33,
}
// enum for the LLVM RealPredicate type
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum RealPredicate {
RealPredicateFalse = 0,
RealOEQ = 1,
// The LLVM TypeKind type - must stay in sync with the def of
// LLVMTypeKind in llvm/include/llvm-c/Core.h
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
#[repr(C)]
pub enum TypeKind {
Void = 0,
}
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum AtomicBinOp {
AtomicXchg = 0,
AtomicAdd = 1,
}
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum AtomicOrdering {
NotAtomic = 0,
Unordered = 1,
// Consts for the LLVMCodeGenFileType type (in include/llvm/c/TargetMachine.h)
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum FileType {
AssemblyFileType = 0,
ObjectFileType = 1
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum MetadataType {
MD_dbg = 0,
MD_tbaa = 1,
}
// Inline Asm Dialect
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum AsmDialect {
AD_ATT = 0,
AD_Intel = 1
}
-#[deriving(Copy, PartialEq, Clone)]
+#[derive(Copy, PartialEq, Clone)]
#[repr(C)]
pub enum CodeGenOptLevel {
CodeGenLevelNone = 0,
CodeGenLevelAggressive = 3,
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
#[repr(C)]
pub enum RelocMode {
RelocDefault = 0,
}
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum CodeGenModel {
CodeModelDefault = 0,
CodeModelJITDefault = 1,
}
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum DiagnosticKind {
DK_InlineAsm = 0,
DK_StackSize,
pub type DIArray = DIDescriptor;
pub type DISubrange = DIDescriptor;
- #[deriving(Copy)]
+ #[derive(Copy)]
pub enum DIDescriptorFlags {
FlagPrivate = 1 << 0,
FlagProtected = 1 << 1,
use {DefModifiers, PUBLIC, IMPORTABLE};
use ImportDirective;
-use ImportDirectiveSubclass::{mod, SingleImport, GlobImport};
+use ImportDirectiveSubclass::{self, SingleImport, GlobImport};
use ImportResolution;
use Module;
use ModuleKind::*;
use Namespace::{TypeNS, ValueNS};
use NameBindings;
-use ParentLink::{mod, ModuleParentLink, BlockParentLink};
+use ParentLink::{self, ModuleParentLink, BlockParentLink};
use Resolver;
use RibKind::*;
use Shadowable;
use syntax::ast::{Visibility};
use syntax::ast::TyPath;
use syntax::ast;
-use syntax::ast_util::{mod, PostExpansionMethod, local_def};
+use syntax::ast_util::{self, PostExpansionMethod, local_def};
use syntax::attr::AttrMetaMethods;
-use syntax::parse::token::{mod, special_idents};
+use syntax::parse::token::{self, special_idents};
use syntax::codemap::{Span, DUMMY_SP};
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
use std::mem::replace;
use std::ops::{Deref, DerefMut};
// Specifies how duplicates should be handled when adding a child item if
// another item exists with the same name in some namespace.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
enum DuplicateCheckingMode {
ForbidDuplicateModules,
ForbidDuplicateTypesAndModules,
OverwriteDuplicates
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
enum NamespaceError {
NoError,
ModuleError,
use syntax::ast::{ViewItem, ViewItemExternCrate, ViewItemUse};
use syntax::ast::{ViewPathGlob, ViewPathList, ViewPathSimple};
use syntax::codemap::{Span, DUMMY_SP};
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
struct UnusedImportCheckVisitor<'a, 'b:'a, 'tcx:'b> {
resolver: &'a mut Resolver<'b, 'tcx>
use syntax::ast_util::{PostExpansionMethod, local_def, walk_pat};
use syntax::attr::AttrMetaMethods;
use syntax::ext::mtwt;
-use syntax::parse::token::{mod, special_names, special_idents};
+use syntax::parse::token::{self, special_names, special_idents};
use syntax::codemap::{Span, Pos};
use syntax::owned_slice::OwnedSlice;
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry::{Occupied, Vacant};
mod record_exports;
mod build_reduced_graph;
-#[deriving(Copy)]
+#[derive(Copy)]
struct BindingInfo {
span: Span,
binding_mode: BindingMode,
// Map from the name in a pattern to its binding mode.
type BindingMap = HashMap<Name, BindingInfo>;
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
enum PatternBindingMode {
RefutableMode,
LocalIrrefutableMode,
ArgumentIrrefutableMode,
}
-#[deriving(Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Copy, PartialEq, Eq, Hash, Show)]
enum Namespace {
TypeNS,
ValueNS
/// A NamespaceResult represents the result of resolving an import in
/// a particular namespace. The result is either definitely-resolved,
/// definitely- unresolved, or unknown.
-#[deriving(Clone)]
+#[derive(Clone)]
enum NamespaceResult {
/// Means that resolve hasn't gathered enough information yet to determine
/// whether the name is bound in this namespace. (That is, it hasn't
}
/// Contains data for specific types of import directives.
-#[deriving(Copy,Show)]
+#[derive(Copy,Show)]
enum ImportDirectiveSubclass {
SingleImport(Name /* target */, Name /* source */),
GlobImport
TraitMethod(String),
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum TypeParameters<'a> {
NoTypeParameters,
HasTypeParameters(
// The rib kind controls the translation of local
// definitions (`DefLocal`) to upvars (`DefUpvar`).
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
enum RibKind {
// No translation needs to be applied.
NormalRibKind,
}
// Methods can be required or provided. RequiredMethod methods only occur in traits.
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
enum MethodSort {
RequiredMethod,
ProvidedMethod(NodeId)
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum UseLexicalScopeFlag {
DontUseLexicalScope,
UseLexicalScope
PrefixFound(Rc<Module>, uint)
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
enum NameSearchType {
/// We're doing a name search in order to resolve a `use` directive.
ImportSearch,
PathSearch,
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum BareIdentifierPatternResolution {
FoundStructOrEnumVariant(Def, LastPrivate),
FoundConst(Def, LastPrivate),
}
/// One local scope.
-#[deriving(Show)]
+#[derive(Show)]
struct Rib {
bindings: HashMap<Name, DefLike>,
kind: RibKind,
}
/// Whether an import can be shadowed by another import.
-#[deriving(Show,PartialEq,Clone,Copy)]
+#[derive(Show,PartialEq,Clone,Copy)]
enum Shadowable {
Always,
Never
}
/// One import directive.
-#[deriving(Show)]
+#[derive(Show)]
struct ImportDirective {
module_path: Vec<Name>,
subclass: ImportDirectiveSubclass,
}
/// The item that an import resolves to.
-#[deriving(Clone,Show)]
+#[derive(Clone,Show)]
struct Target {
target_module: Rc<Module>,
bindings: Rc<NameBindings>,
}
/// An ImportResolution represents a particular `use` directive.
-#[deriving(Show)]
+#[derive(Show)]
struct ImportResolution {
/// Whether this resolution came from a `use` or a `pub use`. Note that this
/// should *not* be used whenever resolution is being performed, this is
}
/// The link from a module up to its nearest parent node.
-#[deriving(Clone,Show)]
+#[derive(Clone,Show)]
enum ParentLink {
NoParentLink,
ModuleParentLink(Weak<Module>, Name),
}
/// The type of module this is.
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
enum ModuleKind {
NormalModuleKind,
TraitModuleKind,
}
bitflags! {
- #[deriving(Show)]
+ #[derive(Show)]
flags DefModifiers: u8 {
const PUBLIC = 0b0000_0001,
const IMPORTABLE = 0b0000_0010,
}
// Records a possibly-private type definition.
-#[deriving(Clone,Show)]
+#[derive(Clone,Show)]
struct TypeNsDef {
modifiers: DefModifiers, // see note in ImportResolution about how to use this
module_def: Option<Rc<Module>>,
}
// Records a possibly-private value definition.
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
struct ValueNsDef {
modifiers: DefModifiers, // see note in ImportResolution about how to use this
def: Def,
// Records the definitions (at most one for each namespace) that a name is
// bound to.
-#[deriving(Show)]
+#[derive(Show)]
struct NameBindings {
type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
}
/// Ways in which a trait can be referenced
-#[deriving(Copy)]
+#[derive(Copy)]
enum TraitReferenceType {
TraitImplementation, // impl SomeTrait for T { ... }
TraitDerivation, // trait T : SomeTrait { ... }
used_crates: HashSet<CrateNum>,
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
enum FallbackChecks {
Everything,
OnlyTraitAndStatics
pub glob_map: Option<GlobMap>
}
-#[deriving(PartialEq,Copy)]
+#[derive(PartialEq,Copy)]
pub enum MakeGlobMap {
Yes,
No
// processing.
use {Module, NameBindings, Resolver};
-use Namespace::{mod, TypeNS, ValueNS};
+use Namespace::{self, TypeNS, ValueNS};
use build_reduced_graph;
use metadata::{encoder, cstore, filesearch, csearch, creader};
use metadata::filesearch::FileDoesntMatch;
use trans::{CrateContext, CrateTranslation, gensym_name};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::common::time;
use util::ppaux;
use util::sha2::{Digest, Sha256};
use super::link;
use super::write;
-use rustc::session::{mod, config};
+use rustc::session::{self, config};
use llvm;
use llvm::archive_ro::ArchiveRO;
use llvm::{ModuleRef, TargetMachineRef, True, False};
use std::thread;
use libc::{c_uint, c_int, c_void};
-#[deriving(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
+#[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
pub enum OutputType {
OutputTypeBitcode,
OutputTypeAssembly,
// We use an Arc instead of just returning a list of diagnostics from the
// child task because we need to make sure that the messages are seen even
// if the child task panics (for example, when `fatal` is called).
-#[deriving(Clone)]
+#[derive(Clone)]
struct SharedEmitter {
buffer: Arc<Mutex<Vec<Diagnostic>>>,
}
/// Module-specific configuration for `optimize_and_codegen`.
-#[deriving(Clone)]
+#[derive(Clone)]
struct ModuleConfig {
/// LLVM TargetMachine to use for codegen.
tm: TargetMachineRef,
use session::Session;
use middle::def;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use std::cell::Cell;
-use std::io::{mod, File, fs};
+use std::io::{self, File, fs};
use std::os;
-use syntax::ast_util::{mod, PostExpansionMethod};
-use syntax::ast::{mod, NodeId, DefId};
+use syntax::ast_util::{self, PostExpansionMethod};
+use syntax::ast::{self, NodeId, DefId};
use syntax::ast_map::NodeItem;
use syntax::attr;
use syntax::codemap::*;
-use syntax::parse::token::{mod, get_ident, keywords};
+use syntax::parse::token::{self, get_ident, keywords};
use syntax::owned_slice::OwnedSlice;
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
use syntax::print::pprust::{path_to_string,ty_to_string};
use syntax::ptr::P;
})
}
-#[deriving(Copy,Show)]
+#[derive(Copy,Show)]
pub enum Row {
Variable,
Enum,
use syntax::parse::token;
use syntax::parse::token::{keywords, Token};
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct SpanUtils<'a> {
pub sess: &'a Session,
pub err_count: Cell<int>,
use middle::check_match::StaticInliner;
use middle::check_match;
use middle::const_eval;
-use middle::def::{mod, DefMap};
+use middle::def::{self, DefMap};
use middle::expr_use_visitor as euv;
use middle::lang_items::StrEqFnLangItem;
use middle::mem_categorization as mc;
use trans::build::{Mul, Not, Store, Sub, add_comment};
use trans::build;
use trans::callee;
-use trans::cleanup::{mod, CleanupMethods};
+use trans::cleanup::{self, CleanupMethods};
use trans::common::*;
use trans::consts;
use trans::datum::*;
-use trans::expr::{mod, Dest};
+use trans::expr::{self, Dest};
use trans::tvec;
use trans::type_of;
use trans::debuginfo;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use session::config::FullDebugInfo;
use util::common::indenter;
use util::nodemap::FnvHashMap;
use syntax::fold::Folder;
use syntax::ptr::P;
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
struct ConstantExpr<'a>(&'a ast::Expr);
impl<'a> ConstantExpr<'a> {
}
// An option identifying a branch (either a literal, an enum variant or a range)
-#[deriving(Show)]
+#[derive(Show)]
enum Opt<'a, 'tcx> {
ConstantValue(ConstantExpr<'a>),
ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>),
}
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum BranchKind {
NoBranch,
Single,
LowerBound(Result<'blk, 'tcx>)
}
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub enum TransBindingMode {
TrByCopy(/* llbinding */ ValueRef),
TrByMove,
/// - `trmode` is the trans binding mode
/// - `id` is the node id of the binding
/// - `ty` is the Rust type of the binding
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct BindingInfo<'tcx> {
pub llmatch: ValueRef,
pub trmode: TransBindingMode,
use trans::machine;
use trans::type_::Type;
use trans::type_of;
-use middle::ty::{mod, Ty, UnboxedClosureTyper};
+use middle::ty::{self, Ty, UnboxedClosureTyper};
use middle::ty::Disr;
use syntax::ast;
use syntax::attr;
type Hint = attr::ReprAttr;
/// Representations.
-#[deriving(Eq, PartialEq, Show)]
+#[derive(Eq, PartialEq, Show)]
pub enum Repr<'tcx> {
/// C-like enums; basically an int.
CEnum(IntType, Disr, Disr), // discriminant range (signedness based on the IntType)
}
/// For structs, and struct-like parts of anything fancier.
-#[deriving(Eq, PartialEq, Show)]
+#[derive(Eq, PartialEq, Show)]
pub struct Struct<'tcx> {
// If the struct is DST, then the size and alignment do not take into
// account the unsized fields of the struct.
}
}
-#[deriving(Show)]
+#[derive(Show)]
struct IntBounds {
slo: i64,
shi: i64,
use middle::subst;
use middle::weak_lang_items;
use middle::subst::{Subst, Substs};
-use middle::ty::{mod, Ty, UnboxedClosureTyper};
-use session::config::{mod, NoDebugInfo, FullDebugInfo};
+use middle::ty::{self, Ty, UnboxedClosureTyper};
+use session::config::{self, NoDebugInfo, FullDebugInfo};
use session::Session;
use trans::_match;
use trans::adt;
// Since we're in trans we don't care for any region parameters
let substs = subst::Substs::erased(substs.types.clone());
- let (val, _) = monomorphize::monomorphic_fn(ccx, did, &substs, None);
+ let (val, _, _) = monomorphize::monomorphic_fn(ccx, did, &substs, None);
val
} else if did.krate == ast::LOCAL_CRATE {
// Used only for creating scalar comparison glue.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
pub fn compare_scalar_types<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
}
}
-#[deriving(Clone, Copy, Eq, PartialEq)]
+#[derive(Clone, Copy, Eq, PartialEq)]
pub enum IsUnboxedClosureFlag {
NotUnboxedClosure,
IsUnboxedClosure,
/// Enum describing the origin of an LLVM `Value`, for linkage purposes.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum ValueOrigin {
/// The LLVM `Value` is in this context because the corresponding item was
/// assigned to the current compilation unit.
use trans::value::{Users, Value};
use std::iter::{Filter, Map};
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct BasicBlock(pub BasicBlockRef);
pub type Preds = Map<
use trans::cabi_mips;
use trans::type_::Type;
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
pub enum ArgKind {
/// Pass the argument directly using the normal converted
/// LLVM type or by coercing to another specified type
/// should be passed to or returned from a function
///
/// This is borrowed from clang's ABIInfo.h
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct ArgType {
pub kind: ArgKind,
/// Original LLVM type
use std::cmp;
use std::iter::repeat;
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
enum RegClass {
NoClass,
Int,
use trans::closure;
use trans::common;
use trans::common::*;
+use trans::consts;
use trans::datum::*;
use trans::expr;
use trans::glue;
use trans::monomorphize;
use trans::type_::Type;
use trans::type_of;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::MethodCall;
use util::ppaux::Repr;
use util::ppaux::ty_to_string;
use syntax::ast_map;
use syntax::ptr::P;
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct MethodData {
pub llfn: ValueRef,
pub llself: ValueRef,
_ => false
}
} => {
- let substs = node_id_substs(bcx, ExprId(ref_expr.id));
+ let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
+ bcx.fcx.param_substs);
Callee {
bcx: bcx,
data: NamedTupleConstructor(substs, 0)
ty::ty_bare_fn(_, ref f) => f.abi == synabi::RustIntrinsic,
_ => false
} => {
- let substs = node_id_substs(bcx, ExprId(ref_expr.id));
+ let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
+ bcx.fcx.param_substs);
let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
}
def::DefFn(did, _) | def::DefMethod(did, _, def::FromImpl(_)) |
def::DefStaticMethod(did, def::FromImpl(_)) => {
- fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
+ fn_callee(bcx, trans_fn_ref(bcx.ccx(), did, ExprId(ref_expr.id),
+ bcx.fcx.param_substs).val)
}
def::DefStaticMethod(meth_did, def::FromTrait(trait_did)) |
def::DefMethod(meth_did, _, def::FromTrait(trait_did)) => {
- fn_callee(bcx, meth::trans_static_method_callee(bcx, meth_did,
+ fn_callee(bcx, meth::trans_static_method_callee(bcx.ccx(),
+ meth_did,
trait_did,
- ref_expr.id))
+ ref_expr.id,
+ bcx.fcx.param_substs).val)
}
def::DefVariant(tid, vid, _) => {
let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
- let substs = node_id_substs(bcx, ExprId(ref_expr.id));
+ let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
+ bcx.fcx.param_substs);
// Nullary variants are not callable
assert!(vinfo.args.len() > 0u);
}
}
def::DefStruct(_) => {
- let substs = node_id_substs(bcx, ExprId(ref_expr.id));
+ let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
+ bcx.fcx.param_substs);
Callee {
bcx: bcx,
data: NamedTupleConstructor(substs, 0)
/// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
/// pointer. This may require monomorphization or inlining.
-pub fn trans_fn_ref(bcx: Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
+pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
+ def_id: ast::DefId,
+ node: ExprOrMethodCall,
+ param_substs: &subst::Substs<'tcx>)
+ -> Datum<'tcx, Rvalue> {
let _icx = push_ctxt("trans_fn_ref");
- let substs = node_id_substs(bcx, node);
+ let substs = node_id_substs(ccx, node, param_substs);
debug!("trans_fn_ref(def_id={}, node={}, substs={})",
- def_id.repr(bcx.tcx()),
+ def_id.repr(ccx.tcx()),
node,
- substs.repr(bcx.tcx()));
- trans_fn_ref_with_substs(bcx, def_id, node, substs)
+ substs.repr(ccx.tcx()));
+ trans_fn_ref_with_substs(ccx, def_id, node, param_substs, substs)
}
fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
-> Callee<'blk, 'tcx> {
Callee {
bcx: bcx,
- data: Fn(trans_fn_ref_with_substs(bcx,
+ data: Fn(trans_fn_ref_with_substs(bcx.ccx(),
def_id,
ExprId(ref_id),
- substs)),
+ bcx.fcx.param_substs,
+ substs).val),
}
}
///
/// # Parameters
///
-/// - `bcx`: the current block where the reference to the fn occurs
+/// - `ccx`: the crate context
/// - `def_id`: def id of the fn or method item being referenced
/// - `node`: node id of the reference to the fn/method, if applicable.
/// This parameter may be zero; but, if so, the resulting value may not
/// have the right type, so it must be cast before being used.
+/// - `param_substs`: if the `node` is in a polymorphic function, these
+/// are the substitutions required to monomorphize its type
/// - `substs`: values for each of the fn/method's parameters
-pub fn trans_fn_ref_with_substs<'blk, 'tcx>(
- bcx: Block<'blk, 'tcx>, //
- def_id: ast::DefId, // def id of fn
- node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
- substs: subst::Substs<'tcx>) // vtables for the call
- -> ValueRef
+pub fn trans_fn_ref_with_substs<'a, 'tcx>(
+ ccx: &CrateContext<'a, 'tcx>,
+ def_id: ast::DefId,
+ node: ExprOrMethodCall,
+ param_substs: &subst::Substs<'tcx>,
+ substs: subst::Substs<'tcx>)
+ -> Datum<'tcx, Rvalue>
{
let _icx = push_ctxt("trans_fn_ref_with_substs");
- let ccx = bcx.ccx();
- let tcx = bcx.tcx();
+ let tcx = ccx.tcx();
- debug!("trans_fn_ref_with_substs(bcx={}, def_id={}, node={}, \
- substs={})",
- bcx.to_str(),
+ debug!("trans_fn_ref_with_substs(def_id={}, node={}, \
+ param_substs={}, substs={})",
def_id.repr(tcx),
node,
+ param_substs.repr(tcx),
substs.repr(tcx));
assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
(true, source_id, new_substs)
}
ty::TypeTraitItem(_) => {
- bcx.tcx().sess.bug("trans_fn_ref_with_vtables() tried \
- to translate an associated type?!")
+ tcx.sess.bug("trans_fn_ref_with_vtables() tried \
+ to translate an associated type?!")
}
}
}
};
// If this is an unboxed closure, redirect to it.
- match closure::get_or_create_declaration_if_unboxed_closure(bcx,
+ match closure::get_or_create_declaration_if_unboxed_closure(ccx,
def_id,
&substs) {
None => {}
MethodCallKey(_) => None,
};
- let (val, must_cast) =
+ let (val, fn_ty, must_cast) =
monomorphize::monomorphic_fn(ccx, def_id, &substs, opt_ref_id);
- let mut val = val;
if must_cast && node != ExprId(0) {
// Monotype of the REFERENCE to the function (type params
// are subst'd)
let ref_ty = match node {
- ExprId(id) => node_id_type(bcx, id),
+ ExprId(id) => ty::node_id_to_type(tcx, id),
MethodCallKey(method_call) => {
- let t = (*bcx.tcx().method_map.borrow())[method_call].ty;
- monomorphize_type(bcx, t)
+ (*tcx.method_map.borrow())[method_call].ty
}
};
-
- val = PointerCast(
- bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
+ let ref_ty = monomorphize::apply_param_substs(tcx,
+ param_substs,
+ &ref_ty);
+ let llptrty = type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to();
+ if llptrty != val_ty(val) {
+ let val = consts::ptrcast(val, llptrty);
+ return Datum::new(val, ref_ty, Rvalue::new(ByValue));
+ }
}
- return val;
+ return Datum::new(val, fn_ty, Rvalue::new(ByValue));
}
// Type scheme of the function item (may have type params)
let llptrty = llty.ptr_to();
if val_ty(val) != llptrty {
debug!("trans_fn_ref_with_vtables(): casting pointer!");
- val = BitCast(bcx, val, llptrty);
+ val = consts::ptrcast(val, llptrty);
} else {
debug!("trans_fn_ref_with_vtables(): not casting pointer!");
}
- val
+ Datum::new(val, fn_type, Rvalue::new(ByValue))
}
// ______________________________________________________________________
let _icx = push_ctxt("trans_call");
trans_call_inner(in_cx,
Some(common::expr_info(call_ex)),
- expr_ty(in_cx, f),
+ expr_ty_adjusted(in_cx, f),
|cx, _| trans(cx, f),
args,
Some(dest)).bcx
bcx
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum AutorefArg {
DontAutorefArg,
DoAutorefArg(ast::NodeId)
// Temporary due to slicing syntax hacks (KILLME)
//use middle::region;
use trans::type_::Type;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use std::fmt;
use syntax::ast;
use util::ppaux::Repr;
cached_landing_pad: Option<BasicBlockRef>,
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub struct CustomScopeIndex {
index: uint
}
}
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum EarlyExitLabel {
UnwindExit,
ReturnExit,
LoopExit(ast::NodeId, uint)
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct CachedEarlyExit {
label: EarlyExitLabel,
cleanup_block: BasicBlockRef,
pub type CleanupObj<'tcx> = Box<Cleanup<'tcx>+'tcx>;
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum ScopeId {
AstScope(ast::NodeId),
CustomScope(CustomScopeIndex)
// specify any of the types for the function, we just make it a symbol
// that LLVM can later use.
let llpersonality = match pad_bcx.tcx().lang_items.eh_personality() {
- Some(def_id) => callee::trans_fn_ref(pad_bcx, def_id, ExprId(0)),
+ Some(def_id) => {
+ callee::trans_fn_ref(pad_bcx.ccx(), def_id, ExprId(0),
+ pad_bcx.fcx.param_substs).val
+ }
None => {
let mut personality = self.ccx.eh_personality().borrow_mut();
match *personality {
///////////////////////////////////////////////////////////////////////////
// Cleanup types
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct DropValue<'tcx> {
is_immediate: bool,
must_unwind: bool,
}
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum Heap {
HeapExchange
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct FreeValue<'tcx> {
ptr: ValueRef,
heap: Heap,
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct FreeSlice {
ptr: ValueRef,
size: ValueRef,
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct LifetimeEnd {
ptr: ValueRef,
}
use trans::cleanup::{CleanupMethods, ScopeId};
use trans::common::*;
use trans::datum::{Datum, DatumBlock, Expr, Lvalue, rvalue_scratch_datum};
+use trans::datum::{Rvalue, ByValue};
use trans::debuginfo;
use trans::expr;
-use trans::monomorphize::{mod, MonoId};
+use trans::monomorphize::{self, MonoId};
use trans::type_of::*;
use trans::type_::Type;
-use middle::ty::{mod, Ty, UnboxedClosureTyper};
+use middle::ty::{self, Ty, UnboxedClosureTyper};
use middle::subst::{Substs};
use session::config::FullDebugInfo;
use util::ppaux::Repr;
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct EnvValue<'tcx> {
action: ast::CaptureClause,
datum: Datum<'tcx, Lvalue>
Store(bcx, llenvptr, GEPi(bcx, pair, &[0u, abi::FAT_PTR_EXTRA]));
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
pub enum ClosureKind<'tcx> {
NotClosure,
// See load_environment.
/// Returns the LLVM function declaration for an unboxed closure, creating it
/// if necessary. If the ID does not correspond to a closure ID, returns None.
-pub fn get_or_create_declaration_if_unboxed_closure<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
- closure_id: ast::DefId,
- substs: &Substs<'tcx>)
- -> Option<ValueRef> {
- let ccx = bcx.ccx();
+pub fn get_or_create_declaration_if_unboxed_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
+ closure_id: ast::DefId,
+ substs: &Substs<'tcx>)
+ -> Option<Datum<'tcx, Rvalue>> {
if !ccx.tcx().unboxed_closures.borrow().contains_key(&closure_id) {
// Not an unboxed closure.
return None
}
- let function_type = ty::node_id_to_type(bcx.tcx(), closure_id.node);
- let function_type = monomorphize::apply_param_substs(bcx.tcx(), substs, &function_type);
+ let function_type = ty::node_id_to_type(ccx.tcx(), closure_id.node);
+ let function_type = monomorphize::apply_param_substs(ccx.tcx(), substs, &function_type);
// Normalize type so differences in regions and typedefs don't cause
// duplicate declarations
- let function_type = ty::normalize_ty(bcx.tcx(), function_type);
+ let function_type = ty::normalize_ty(ccx.tcx(), function_type);
let params = match function_type.sty {
ty::ty_unboxed_closure(_, _, ref substs) => substs.types.clone(),
_ => unreachable!()
};
match ccx.unboxed_closure_vals().borrow().get(&mono_id) {
- Some(llfn) => {
+ Some(&llfn) => {
debug!("get_or_create_declaration_if_unboxed_closure(): found \
closure");
- return Some(*llfn)
+ return Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
}
None => {}
}
ccx.tn().type_to_string(val_ty(llfn)));
ccx.unboxed_closure_vals().borrow_mut().insert(mono_id, llfn);
- Some(llfn)
+ Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
}
pub fn trans_unboxed_closure<'blk, 'tcx>(
let closure_id = ast_util::local_def(id);
let llfn = get_or_create_declaration_if_unboxed_closure(
- bcx,
+ bcx.ccx(),
closure_id,
bcx.fcx.param_substs).unwrap();
trans_closure(bcx.ccx(),
decl,
body,
- llfn,
+ llfn.val,
bcx.fcx.param_substs,
id,
&[],
use middle::lang_items::LangItem;
use middle::mem_categorization as mc;
use middle::region;
-use middle::subst::{mod, Subst, Substs};
+use middle::subst::{self, Subst, Substs};
use trans::base;
use trans::build;
use trans::cleanup;
+use trans::consts;
use trans::datum;
use trans::debuginfo;
use trans::machine;
use trans::type_::Type;
use trans::type_of;
use middle::traits;
-use middle::ty::{mod, HasProjectionTypes, Ty};
+use middle::ty::{self, HasProjectionTypes, Ty};
use middle::ty_fold;
use middle::ty_fold::{TypeFolder, TypeFoldable};
use util::ppaux::Repr;
PathName(token::gensym(format!("{}:{}", name, num)[]))
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct tydesc_info<'tcx> {
pub ty: Ty<'tcx>,
pub tydesc: ValueRef,
*
*/
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct NodeInfo {
pub id: ast::NodeId,
pub span: Span,
// NB: Do not use `do_spill_noroot` to make this into a constant string, or
// you will be kicked off fast isel. See issue #4352 for an example of this.
pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
- unsafe {
- let len = s.get().len();
- let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s, false),
- Type::i8p(cx).to_ref());
- C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
- }
+ let len = s.get().len();
+ let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
+ C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
}
pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
llvm::LLVMSetGlobalConstant(g, True);
llvm::SetLinkage(g, llvm::InternalLinkage);
- let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
+ let cs = consts::ptrcast(g, Type::i8p(cx));
C_struct(cx, &[cs, C_uint(cx, len)], false)
}
}
}
// Key used to lookup values supplied for type parameters in an expr.
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum ExprOrMethodCall {
// Type parameters for a path like `None::<int>`
ExprId(ast::NodeId),
MethodCallKey(ty::MethodCall)
}
-pub fn node_id_substs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
- node: ExprOrMethodCall)
- -> subst::Substs<'tcx>
-{
- let tcx = bcx.tcx();
+pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
+ node: ExprOrMethodCall,
+ param_substs: &subst::Substs<'tcx>)
+ -> subst::Substs<'tcx> {
+ let tcx = ccx.tcx();
let substs = match node {
ExprId(id) => {
};
if substs.types.any(|t| ty::type_needs_infer(*t)) {
- bcx.sess().bug(
- format!("type parameters for node {} include inference types: \
- {}",
- node,
- substs.repr(bcx.tcx()))[]);
+ tcx.sess.bug(format!("type parameters for node {} include inference types: {}",
+ node, substs.repr(tcx))[]);
}
- let substs = substs.erase_regions();
- bcx.monomorphize(&substs)
+ monomorphize::apply_param_substs(tcx,
+ param_substs,
+ &substs.erase_regions())
}
pub fn langcall(bcx: Block,
use llvm::{ConstFCmp, ConstICmp, SetLinkage, PrivateLinkage, ValueRef, Bool, True, False};
use llvm::{IntEQ, IntNE, IntUGT, IntUGE, IntULT, IntULE, IntSGT, IntSGE, IntSLT, IntSLE,
RealOEQ, RealOGT, RealOGE, RealOLT, RealOLE, RealONE};
-use metadata::csearch;
use middle::{const_eval, def};
use trans::{adt, closure, consts, debuginfo, expr, inline, machine};
-use trans::base::{mod, push_ctxt};
+use trans::base::{self, push_ctxt};
use trans::common::*;
use trans::type_::Type;
use trans::type_of;
-use middle::ty::{mod, Ty};
+use middle::subst::Substs;
+use middle::ty::{self, Ty};
use util::ppaux::{Repr, ty_to_string};
use std::c_str::ToCStr;
}
}
-pub fn const_ptrcast(cx: &CrateContext, a: ValueRef, t: Type) -> ValueRef {
+pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
unsafe {
- let b = llvm::LLVMConstPointerCast(a, t.ptr_to().to_ref());
- assert!(cx.const_globals().borrow_mut().insert(b as int, a).is_none());
- b
+ llvm::LLVMConstPointerCast(val, ty.to_ref())
}
}
match ty.sty {
ty::ty_vec(unit_ty, Some(len)) => {
let llunitty = type_of::type_of(cx, unit_ty);
- let llptr = const_ptrcast(cx, llconst, llunitty);
+ let llptr = ptrcast(llconst, llunitty.ptr_to());
+ assert!(cx.const_globals().borrow_mut()
+ .insert(llptr as int, llconst).is_none());
assert_eq!(abi::FAT_PTR_ADDR, 0);
assert_eq!(abi::FAT_PTR_EXTRA, 1);
llconst = C_struct(cx, &[
}
}
(expr::cast_pointer, expr::cast_pointer) => {
- llvm::LLVMConstPointerCast(v, llty.to_ref())
+ ptrcast(v, llty)
}
(expr::cast_integral, expr::cast_pointer) => {
llvm::LLVMConstIntToPtr(v, llty.to_ref())
C_array(llunitty, vs[])
}
}
- ast::ExprPath(ref pth) => {
- // Assert that there are no type parameters in this path.
- assert!(pth.segments.iter().all(|seg| !seg.parameters.has_types()));
-
- let opt_def = cx.tcx().def_map.borrow().get(&e.id).cloned();
- match opt_def {
- Some(def::DefFn(def_id, _)) => {
- if !ast_util::is_local(def_id) {
- let ty = csearch::get_type(cx.tcx(), def_id).ty;
- base::trans_external_path(cx, def_id, ty)
- } else {
- assert!(ast_util::is_local(def_id));
- base::get_item_val(cx, def_id.node)
- }
+ ast::ExprPath(_) => {
+ let def = cx.tcx().def_map.borrow()[e.id];
+ match def {
+ def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => {
+ expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val
}
- Some(def::DefConst(def_id)) => {
+ def::DefConst(def_id) => {
get_const_val(cx, def_id)
}
- Some(def::DefVariant(enum_did, variant_did, _)) => {
- let ety = ty::expr_ty(cx.tcx(), e);
- let repr = adt::represent_type(cx, ety);
+ def::DefVariant(enum_did, variant_did, _) => {
let vinfo = ty::enum_variant_with_id(cx.tcx(),
enum_did,
variant_did);
- adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
+ if vinfo.args.len() > 0 {
+ // N-ary variant.
+ expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val
+ } else {
+ // Nullary variant.
+ let ety = ty::expr_ty(cx.tcx(), e);
+ let repr = adt::represent_type(cx, ety);
+ adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
+ }
}
- Some(def::DefStruct(_)) => {
+ def::DefStruct(_) => {
let ety = ty::expr_ty(cx.tcx(), e);
- let llty = type_of::type_of(cx, ety);
- C_null(llty)
+ if let ty::ty_bare_fn(..) = ety.sty {
+ // Tuple struct.
+ expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val
+ } else {
+ // Unit struct.
+ C_null(type_of::type_of(cx, ety))
+ }
}
_ => {
cx.sess().span_bug(e.span, "expected a const, fn, struct, \
use trans::debuginfo;
use trans::monomorphize::MonoId;
use trans::type_::{Type, TypeNames};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use session::config::NoDebugInfo;
use session::Session;
use util::ppaux::Repr;
use trans::expr;
use trans::tvec;
use trans::type_of;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::ppaux::{ty_to_string};
use std::fmt;
/// describes where the value is stored, what Rust type the value has,
/// whether it is addressed by reference, and so forth. Please refer
/// the section on datums in `doc.rs` for more details.
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct Datum<'tcx, K> {
/// The llvm value. This is either a pointer to the Rust value or
/// the value itself, depending on `kind` below.
pub datum: Datum<'tcx, K>,
}
-#[deriving(Show)]
+#[derive(Show)]
pub enum Expr {
/// a fresh value that was produced and which has no cleanup yet
/// because it has not yet "landed" into its permanent home
LvalueExpr,
}
-#[deriving(Clone, Copy, Show)]
+#[derive(Clone, Copy, Show)]
pub struct Lvalue;
-#[deriving(Show)]
+#[derive(Show)]
pub struct Rvalue {
pub mode: RvalueMode
}
fn drop(&mut self) { }
}
-#[deriving(Copy, PartialEq, Eq, Hash, Show)]
+#[derive(Copy, PartialEq, Eq, Hash, Show)]
pub enum RvalueMode {
/// `val` is a pointer to the actual value (and thus has type *T)
ByRef,
use llvm::{ModuleRef, ContextRef, ValueRef};
use llvm::debuginfo::*;
use metadata::csearch;
-use middle::subst::{mod, Substs};
-use trans::{mod, adt, machine, type_of};
+use middle::subst::{self, Substs};
+use trans::{self, adt, machine, type_of};
use trans::common::*;
use trans::_match::{BindingInfo, TrByCopy, TrByMove, TrByRef};
use trans::monomorphize;
use trans::type_::Type;
-use middle::ty::{mod, Ty, UnboxedClosureTyper};
+use middle::ty::{self, Ty, UnboxedClosureTyper};
use middle::pat_util;
-use session::config::{mod, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
+use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
use util::nodemap::{DefIdMap, NodeMap, FnvHashMap, FnvHashSet};
use util::ppaux;
use syntax::codemap::{Span, Pos};
use syntax::{ast, codemap, ast_util, ast_map, attr};
use syntax::ast_util::PostExpansionMethod;
-use syntax::parse::token::{mod, special_idents};
+use syntax::parse::token::{self, special_idents};
const DW_LANG_RUST: c_uint = 0x9000;
// Public Interface of debuginfo module
//=-----------------------------------------------------------------------------
-#[deriving(Copy, Show, Hash, Eq, PartialEq, Clone)]
+#[derive(Copy, Show, Hash, Eq, PartialEq, Clone)]
struct UniqueTypeId(ast::Name);
// The TypeMap is where the CrateDebugContext holds the type metadata nodes
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum EnumDiscriminantInfo {
RegularDiscriminant(DIType),
OptimizedDiscriminant,
}
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
enum DebugLocation {
KnownLocation { scope: DIScope, line: uint, col: uint },
UnknownLocation
use self::lazy_binop_ty::*;
use back::abi;
-use llvm::{mod, ValueRef};
+use llvm::{self, ValueRef};
use middle::def;
use middle::mem_categorization::Typer;
-use middle::subst::{mod, Substs};
+use middle::subst::{self, Substs};
use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
use trans::base::*;
use trans::build::*;
-use trans::cleanup::{mod, CleanupMethods};
+use trans::cleanup::{self, CleanupMethods};
use trans::common::*;
use trans::datum::*;
use trans::debuginfo;
use middle::ty::{struct_fields, tup_fields};
use middle::ty::{AdjustDerefRef, AdjustReifyFnPointer, AdjustAddEnv, AutoUnsafe};
use middle::ty::{AutoPtr};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::MethodCall;
use util::common::indenter;
use util::ppaux::Repr;
// These are passed around by the code generating functions to track the
// destination of a computation's value.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Dest {
SaveIn(ValueRef),
Ignore,
match def {
def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) |
def::DefStruct(_) | def::DefVariant(..) => {
- trans_def_fn_unadjusted(bcx, ref_expr, def)
+ let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
+ bcx.fcx.param_substs);
+ DatumBlock::new(bcx, datum.to_expr_datum())
}
def::DefStatic(did, _) => {
// There are two things that may happen here:
let variant_info = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
if variant_info.args.len() > 0u {
// N-ary variant.
- let llfn = callee::trans_fn_ref(bcx, vid, ExprId(ref_expr.id));
+ let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
+ ExprId(ref_expr.id),
+ bcx.fcx.param_substs).val;
Store(bcx, llfn, lldest);
return bcx;
} else {
}
}
-fn trans_def_fn_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
- ref_expr: &ast::Expr,
- def: def::Def)
- -> DatumBlock<'blk, 'tcx, Expr> {
+pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
+ ref_expr: &ast::Expr,
+ def: def::Def,
+ param_substs: &subst::Substs<'tcx>)
+ -> Datum<'tcx, Rvalue> {
let _icx = push_ctxt("trans_def_datum_unadjusted");
- let llfn = match def {
+ match def {
def::DefFn(did, _) |
def::DefStruct(did) | def::DefVariant(_, did, _) |
def::DefStaticMethod(did, def::FromImpl(_)) |
def::DefMethod(did, _, def::FromImpl(_)) => {
- callee::trans_fn_ref(bcx, did, ExprId(ref_expr.id))
+ callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
}
def::DefStaticMethod(impl_did, def::FromTrait(trait_did)) |
def::DefMethod(impl_did, _, def::FromTrait(trait_did)) => {
- meth::trans_static_method_callee(bcx, impl_did,
- trait_did, ref_expr.id)
+ meth::trans_static_method_callee(ccx, impl_did,
+ trait_did, ref_expr.id,
+ param_substs)
}
_ => {
- bcx.tcx().sess.span_bug(ref_expr.span, format!(
+ ccx.tcx().sess.span_bug(ref_expr.span, format!(
"trans_def_fn_unadjusted invoked on: {} for {}",
def,
- ref_expr.repr(bcx.tcx()))[]);
+ ref_expr.repr(ccx.tcx()))[]);
}
- };
-
- let fn_ty = expr_ty(bcx, ref_expr);
- DatumBlock::new(bcx, Datum::new(llfn, fn_ty, RvalueExpr(Rvalue::new(ByValue))))
+ }
}
/// Translates a reference to a local variable or argument. This always results in an lvalue datum.
} else { llsrc };
}
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum cast_kind {
cast_pointer,
cast_integral,
use trans::type_::Type;
use trans::type_of::*;
use trans::type_of;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::subst::{Substs};
use std::cmp;
use std::c_str::ToCStr;
use trans::callee;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
+use trans::consts;
use trans::common::*;
use trans::datum;
use trans::debuginfo;
use trans::tvec;
use trans::type_::Type;
use trans::type_of::{type_of, sizing_type_of, align_of};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::ppaux::{ty_to_short_str, Repr};
use util::ppaux;
// before being put into the tydesc because we only have a singleton
// tydesc type. Then we'll recast each function to its real type when
// calling it.
- let drop_glue = unsafe {
- llvm::LLVMConstPointerCast(get_drop_glue(ccx, ti.ty), glue_fn_ty.to_ref())
- };
+ let drop_glue = consts::ptrcast(get_drop_glue(ccx, ti.ty), glue_fn_ty);
ccx.stats().n_real_glues.set(ccx.stats().n_real_glues.get() + 1);
let tydesc = C_named_struct(ccx.tydesc_type(),
use trans::machine;
use trans::machine::llsize_of;
use trans::type_::Type;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use syntax::abi::RustIntrinsic;
use syntax::ast;
use syntax::parse::token;
use arena::TypedArena;
use back::abi;
use back::link;
-use llvm::{mod, ValueRef, get_param};
+use llvm::{self, ValueRef, get_param};
use metadata::csearch;
use middle::subst::{Subst, Substs};
use middle::subst::VecPerParamSpace;
use trans::machine;
use trans::type_::Type;
use trans::type_of::*;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::MethodCall;
use util::ppaux::Repr;
ty::MethodStaticUnboxedClosure(did) => {
Callee {
bcx: bcx,
- data: Fn(callee::trans_fn_ref(bcx,
+ data: Fn(callee::trans_fn_ref(bcx.ccx(),
did,
- MethodCallKey(method_call))),
+ MethodCallKey(method_call),
+ bcx.fcx.param_substs).val),
}
}
}
}
-pub fn trans_static_method_callee(bcx: Block,
- method_id: ast::DefId,
- trait_id: ast::DefId,
- expr_id: ast::NodeId)
- -> ValueRef
+pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
+ method_id: ast::DefId,
+ trait_id: ast::DefId,
+ expr_id: ast::NodeId,
+ param_substs: &subst::Substs<'tcx>)
+ -> Datum<'tcx, Rvalue>
{
let _icx = push_ctxt("meth::trans_static_method_callee");
- let ccx = bcx.ccx();
+ let tcx = ccx.tcx();
debug!("trans_static_method_callee(method_id={}, trait_id={}, \
expr_id={})",
method_id,
- ty::item_path_str(bcx.tcx(), trait_id),
+ ty::item_path_str(tcx, trait_id),
expr_id);
let mname = if method_id.krate == ast::LOCAL_CRATE {
- match bcx.tcx().map.get(method_id.node) {
+ match tcx.map.get(method_id.node) {
ast_map::NodeTraitItem(method) => {
let ident = match *method {
ast::RequiredMethod(ref m) => m.ident,
ast::ProvidedMethod(ref m) => m.pe_ident(),
ast::TypeTraitItem(_) => {
- bcx.tcx().sess.bug("trans_static_method_callee() on \
- an associated type?!")
+ tcx.sess.bug("trans_static_method_callee() on \
+ an associated type?!")
}
};
ident.name
_ => panic!("callee is not a trait method")
}
} else {
- csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name()
+ csearch::get_item_path(tcx, method_id).last().unwrap().name()
};
debug!("trans_static_method_callee: method_id={}, expr_id={}, \
name={}", method_id, expr_id, token::get_name(mname));
// Find the substitutions for the fn itself. This includes
// type parameters that belong to the trait but also some that
// belong to the method:
- let rcvr_substs = node_id_substs(bcx, ExprId(expr_id));
+ let rcvr_substs = node_id_substs(ccx, ExprId(expr_id), param_substs);
let subst::SeparateVecsPerParamSpace {
types: rcvr_type,
selfs: rcvr_self,
Substs::erased(VecPerParamSpace::new(rcvr_type,
rcvr_self,
Vec::new()));
- let trait_substs = bcx.tcx().mk_substs(trait_substs);
- debug!("trait_substs={}", trait_substs.repr(bcx.tcx()));
+ let trait_substs = tcx.mk_substs(trait_substs);
+ debug!("trait_substs={}", trait_substs.repr(tcx));
let trait_ref = ty::Binder(Rc::new(ty::TraitRef { def_id: trait_id,
substs: trait_substs }));
- let vtbl = fulfill_obligation(bcx.ccx(),
+ let vtbl = fulfill_obligation(ccx,
DUMMY_SP,
trait_ref);
rcvr_method));
let mth_id = method_with_name(ccx, impl_did, mname);
- let llfn = trans_fn_ref_with_substs(bcx, mth_id, ExprId(expr_id),
- callee_substs);
-
- let callee_ty = node_id_type(bcx, expr_id);
- let llty = type_of_fn_from_ty(ccx, callee_ty).ptr_to();
- PointerCast(bcx, llfn, llty)
+ trans_fn_ref_with_substs(ccx, mth_id, ExprId(expr_id),
+ param_substs,
+ callee_substs)
}
_ => {
- bcx.tcx().sess.bug(
- format!("static call to invalid vtable: {}",
- vtbl.repr(bcx.tcx()))[]);
+ tcx.sess.bug(format!("static call to invalid vtable: {}",
+ vtbl.repr(tcx))[]);
}
}
}
bcx, MethodCallKey(method_call), vtable_impl.substs);
// translate the function
- let llfn = trans_fn_ref_with_substs(bcx,
+ let llfn = trans_fn_ref_with_substs(bcx.ccx(),
mth_id,
MethodCallKey(method_call),
- callee_substs);
+ bcx.fcx.param_substs,
+ callee_substs).val;
Callee { bcx: bcx, data: Fn(llfn) }
}
traits::VtableUnboxedClosure(closure_def_id, substs) => {
// The substitutions should have no type parameters remaining
// after passing through fulfill_obligation
- let llfn = trans_fn_ref_with_substs(bcx,
+ let llfn = trans_fn_ref_with_substs(bcx.ccx(),
closure_def_id,
MethodCallKey(method_call),
- substs);
+ bcx.fcx.param_substs,
+ substs).val;
Callee {
bcx: bcx,
{
let ccx = bcx.ccx();
- let node_substs = node_id_substs(bcx, node);
+ let node_substs = node_id_substs(ccx, node, bcx.fcx.param_substs);
debug!("rcvr_substs={}", rcvr_substs.repr(ccx.tcx()));
debug!("node_substs={}", node_substs.repr(ccx.tcx()));
}
traits::VtableUnboxedClosure(closure_def_id, substs) => {
let llfn = trans_fn_ref_with_substs(
- bcx,
+ bcx.ccx(),
closure_def_id,
ExprId(0),
- substs.clone());
+ bcx.fcx.param_substs,
+ substs.clone()).val;
(vec!(llfn)).into_iter()
}
Some(C_null(Type::nil(ccx).ptr_to())).into_iter()
} else {
let fn_ref = trans_fn_ref_with_substs(
- bcx,
+ ccx,
m_id,
ExprId(0),
- substs.clone());
+ bcx.fcx.param_substs,
+ substs.clone()).val;
// currently, at least, by-value self is not object safe
assert!(m.explicit_self != ty::ByValueExplicitSelfCategory);
mod llrepr;
mod cleanup;
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct ModuleTranslation {
pub llcx: ContextRef,
pub llmod: ModuleRef,
use trans::base;
use trans::common::*;
use trans::foreign;
-use middle::ty::{mod, HasProjectionTypes, Ty};
+use middle::ty::{self, HasProjectionTypes, Ty};
use util::ppaux::Repr;
use syntax::abi;
fn_id: ast::DefId,
psubsts: &subst::Substs<'tcx>,
ref_id: Option<ast::NodeId>)
- -> (ValueRef, bool) {
+ -> (ValueRef, Ty<'tcx>, bool) {
debug!("monomorphic_fn(\
fn_id={}, \
real_substs={}, \
params: psubsts.types.clone()
};
+ let item_ty = ty::lookup_item_type(ccx.tcx(), fn_id).ty;
+ let mono_ty = item_ty.subst(ccx.tcx(), psubsts);
+
match ccx.monomorphized().borrow().get(&hash_id) {
Some(&val) => {
debug!("leaving monomorphic fn {}",
ty::item_path_str(ccx.tcx(), fn_id));
- return (val, false);
+ return (val, mono_ty, false);
}
None => ()
}
psubsts.repr(ccx.tcx()),
hash_id);
- let tpt = ty::lookup_item_type(ccx.tcx(), fn_id);
- let llitem_ty = tpt.ty;
let map_node = session::expect(
ccx.sess(),
if let ast_map::NodeForeignItem(_) = map_node {
if ccx.tcx().map.get_foreign_abi(fn_id.node) != abi::RustIntrinsic {
// Foreign externs don't have to be monomorphized.
- return (get_item_val(ccx, fn_id.node), true);
+ return (get_item_val(ccx, fn_id.node), mono_ty, true);
}
}
- debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx()));
+ debug!("monomorphic_fn about to subst into {}", item_ty.repr(ccx.tcx()));
- let mono_ty = llitem_ty.subst(ccx.tcx(), psubsts);
debug!("mono_ty = {} (post-substitution)", mono_ty.repr(ccx.tcx()));
let mono_ty = normalize_associated_type(ccx.tcx(), &mono_ty);
ccx.monomorphizing().borrow_mut().insert(fn_id, depth);
debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id));
- (lldecl, true)
+ (lldecl, mono_ty, true)
}
-#[deriving(PartialEq, Eq, Hash, Show)]
+#[derive(PartialEq, Eq, Hash, Show)]
pub struct MonoId<'tcx> {
pub def: ast::DefId,
pub params: subst::VecPerParamSpace<Ty<'tcx>>
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::common::*;
+use trans::consts;
use trans::datum::*;
use trans::expr::{Dest, Ignore, SaveIn};
use trans::expr;
use trans::machine::{nonzero_llsize_of, llsize_of_alloc};
use trans::type_::Type;
use trans::type_of;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::ppaux::ty_to_string;
use syntax::ast;
})
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct VecTypes<'tcx> {
pub unit_ty: Ty<'tcx>,
pub llunit_ty: Type,
match dest {
Ignore => bcx,
SaveIn(lldest) => {
- unsafe {
- let bytes = str_lit.get().len();
- let llbytes = C_uint(bcx.ccx(), bytes);
- let llcstr = C_cstr(bcx.ccx(), str_lit, false);
- let llcstr = llvm::LLVMConstPointerCast(llcstr, Type::i8p(bcx.ccx()).to_ref());
- Store(bcx, llcstr, GEPi(bcx, lldest, &[0u, abi::FAT_PTR_ADDR]));
- Store(bcx, llbytes, GEPi(bcx, lldest, &[0u, abi::FAT_PTR_EXTRA]));
- bcx
- }
+ let bytes = str_lit.get().len();
+ let llbytes = C_uint(bcx.ccx(), bytes);
+ let llcstr = C_cstr(bcx.ccx(), str_lit, false);
+ let llcstr = consts::ptrcast(llcstr, Type::i8p(bcx.ccx()));
+ Store(bcx, llcstr, GEPi(bcx, lldest, &[0u, abi::FAT_PTR_ADDR]));
+ Store(bcx, llbytes, GEPi(bcx, lldest, &[0u, abi::FAT_PTR_EXTRA]));
+ bcx
}
}
}
use libc::c_uint;
-#[deriving(Clone, Copy, PartialEq, Show)]
+#[derive(Clone, Copy, PartialEq, Show)]
#[repr(C)]
pub struct Type {
rf: TypeRef
use trans::common::*;
use trans::foreign;
use trans::machine;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use util::ppaux;
use util::ppaux::Repr;
}
// Want refinements! (Or case classes, I guess
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum named_ty {
a_struct,
an_enum,
use trans::common::Block;
use libc::c_uint;
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Value(pub ValueRef);
macro_rules! opt_val { ($e:expr) => (
}
/// Wrapper for LLVM UseRef
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Use(UseRef);
impl Use {
use middle::resolve_lifetime as rl;
use middle::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs};
use middle::subst::{VecPerParamSpace};
-use middle::ty::{mod, RegionEscape, Ty};
-use rscope::{mod, UnelidableRscope, RegionScope, SpecificRscope,
+use middle::ty::{self, RegionEscape, Ty};
+use rscope::{self, UnelidableRscope, RegionScope, SpecificRscope,
ShiftedRscope, BindingRscope};
use TypeAndSubsts;
use util::common::ErrorReported;
use util::nodemap::DefIdMap;
-use util::ppaux::{mod, Repr, UserString};
+use util::ppaux::{self, Repr, UserString};
use std::rc::Rc;
use std::iter::{repeat, AdditiveIterator};
use middle::infer;
use middle::pat_util::{PatIdMap, pat_id_map, pat_is_binding, pat_is_const};
use middle::subst::{Substs};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use check::{check_expr, check_expr_has_type, check_expr_with_expectation};
use check::{check_expr_coercable_to_type, demand, FnCtxt, Expectation};
use check::{instantiate_path, structurally_resolved_type, valid_range_bounds};
// except according to those terms.
use middle::infer::InferCtxt;
-use middle::traits::{mod, FulfillmentContext, Normalized, MiscObligation,
+use middle::traits::{self, FulfillmentContext, Normalized, MiscObligation,
SelectionContext, ObligationCause};
-use middle::ty::{mod, HasProjectionTypes};
+use middle::ty::{self, HasProjectionTypes};
use middle::ty_fold::{TypeFoldable, TypeFolder};
use syntax::ast;
use syntax::codemap::Span;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+use super::autoderef;
+use super::AutorefArgs;
+use super::check_argument_types;
+use super::check_expr;
+use super::check_method_argument_types;
+use super::err_args;
+use super::FnCtxt;
+use super::LvaluePreference;
+use super::method;
+use super::structurally_resolved_type;
+use super::TupleArgumentsFlag;
+use super::write_call;
+
+use middle::infer;
+use middle::ty::{mod, Ty};
use syntax::ast;
use syntax::codemap::Span;
+use syntax::parse::token;
+use syntax::ptr::P;
use CrateCtxt;
/// Check that it is legal to call methods of the trait corresponding
"add `#![feature(unboxed_closures)]` to the crate attributes to enable");
}
}
+
+pub fn check_call<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
+ call_expr: &ast::Expr,
+ callee_expr: &ast::Expr,
+ arg_exprs: &[P<ast::Expr>])
+{
+ check_expr(fcx, callee_expr);
+ let original_callee_ty = fcx.expr_ty(callee_expr);
+ let (callee_ty, _, result) =
+ autoderef(fcx,
+ callee_expr.span,
+ original_callee_ty,
+ Some(callee_expr.id),
+ LvaluePreference::NoPreference,
+ |adj_ty, idx| {
+ let autoderefref = ty::AutoDerefRef { autoderefs: idx, autoref: None };
+ try_overloaded_call_step(fcx, call_expr, callee_expr,
+ adj_ty, autoderefref)
+ });
+
+ match result {
+ None => {
+ // this will report an error since original_callee_ty is not a fn
+ confirm_builtin_call(fcx, call_expr, original_callee_ty, arg_exprs);
+ }
+
+ Some(CallStep::Builtin) => {
+ confirm_builtin_call(fcx, call_expr, callee_ty, arg_exprs);
+ }
+
+ Some(CallStep::Overloaded(method_callee)) => {
+ confirm_overloaded_call(fcx, call_expr, arg_exprs, method_callee);
+ }
+ }
+}
+
+enum CallStep<'tcx> {
+ Builtin,
+ Overloaded(ty::MethodCallee<'tcx>)
+}
+
+fn try_overloaded_call_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
+ call_expr: &ast::Expr,
+ callee_expr: &ast::Expr,
+ adjusted_ty: Ty<'tcx>,
+ autoderefref: ty::AutoDerefRef<'tcx>)
+ -> Option<CallStep<'tcx>>
+{
+ // If the callee is a bare function or a closure, then we're all set.
+ match structurally_resolved_type(fcx, callee_expr.span, adjusted_ty).sty {
+ ty::ty_bare_fn(..) | ty::ty_closure(_) => {
+ fcx.write_adjustment(callee_expr.id,
+ callee_expr.span,
+ ty::AdjustDerefRef(autoderefref));
+ return Some(CallStep::Builtin);
+ }
+
+ _ => {}
+ }
+
+ // Try the options that are least restrictive on the caller first.
+ for &(opt_trait_def_id, method_name) in [
+ (fcx.tcx().lang_items.fn_trait(), token::intern("call")),
+ (fcx.tcx().lang_items.fn_mut_trait(), token::intern("call_mut")),
+ (fcx.tcx().lang_items.fn_once_trait(), token::intern("call_once")),
+ ].iter() {
+ let trait_def_id = match opt_trait_def_id {
+ Some(def_id) => def_id,
+ None => continue,
+ };
+
+ match method::lookup_in_trait_adjusted(fcx,
+ call_expr.span,
+ Some(&*callee_expr),
+ method_name,
+ trait_def_id,
+ autoderefref.clone(),
+ adjusted_ty,
+ None) {
+ None => continue,
+ Some(method_callee) => {
+ return Some(CallStep::Overloaded(method_callee));
+ }
+ }
+ }
+
+ None
+}
+
+fn confirm_builtin_call<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
+ call_expr: &ast::Expr,
+ callee_ty: Ty<'tcx>,
+ arg_exprs: &[P<ast::Expr>])
+{
+ let error_fn_sig;
+
+ let fn_sig = match callee_ty.sty {
+ ty::ty_bare_fn(_, &ty::BareFnTy {ref sig, ..}) |
+ ty::ty_closure(box ty::ClosureTy {ref sig, ..}) => {
+ sig
+ }
+ _ => {
+ fcx.type_error_message(call_expr.span, |actual| {
+ format!("expected function, found `{}`", actual)
+ }, callee_ty, None);
+
+ // This is the "default" function signature, used in case of error.
+ // In that case, we check each argument against "error" in order to
+ // set up all the node type bindings.
+ error_fn_sig = ty::Binder(ty::FnSig {
+ inputs: err_args(fcx.tcx(), arg_exprs.len()),
+ output: ty::FnConverging(fcx.tcx().types.err),
+ variadic: false
+ });
+
+ &error_fn_sig
+ }
+ };
+
+ // Replace any late-bound regions that appear in the function
+ // signature with region variables. We also have to
+ // renormalize the associated types at this point, since they
+ // previously appeared within a `Binder<>` and hence would not
+ // have been normalized before.
+ let fn_sig =
+ fcx.infcx().replace_late_bound_regions_with_fresh_var(call_expr.span,
+ infer::FnCall,
+ fn_sig).0;
+ let fn_sig =
+ fcx.normalize_associated_types_in(call_expr.span, &fn_sig);
+
+ // Call the generic checker.
+ let arg_exprs: Vec<_> = arg_exprs.iter().collect(); // for some weird reason we take &[&P<...>].
+ check_argument_types(fcx,
+ call_expr.span,
+ fn_sig.inputs[],
+ arg_exprs.as_slice(),
+ AutorefArgs::No,
+ fn_sig.variadic,
+ TupleArgumentsFlag::DontTupleArguments);
+
+ write_call(fcx, call_expr, fn_sig.output);
+}
+
+fn confirm_overloaded_call<'a,'tcx>(fcx: &FnCtxt<'a, 'tcx>,
+ call_expr: &ast::Expr,
+ arg_exprs: &[P<ast::Expr>],
+ method_callee: ty::MethodCallee<'tcx>)
+{
+ let arg_exprs: Vec<_> = arg_exprs.iter().collect(); // for some weird reason we take &[&P<...>].
+ let output_type = check_method_argument_types(fcx,
+ call_expr.span,
+ method_callee.ty,
+ call_expr,
+ arg_exprs.as_slice(),
+ AutorefArgs::No,
+ TupleArgumentsFlag::TupleArguments);
+ let method_call = ty::MethodCall::expr(call_expr.id);
+ fcx.inh.method_map.borrow_mut().insert(method_call, method_callee);
+ write_call(fcx, call_expr, output_type);
+}
+
use middle::infer;
use middle::region::CodeExtent;
use middle::subst;
-use middle::ty::{mod, ToPolyTraitRef, Ty};
+use middle::ty::{self, ToPolyTraitRef, Ty};
use rscope::RegionScope;
use syntax::abi;
use syntax::ast;
use check::FnCtxt;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::infer;
use std::result::Result::{Err, Ok};
use super::probe;
-use check::{mod, FnCtxt, NoPreference, PreferMutLvalue, callee, demand};
+use check::{self, FnCtxt, NoPreference, PreferMutLvalue, callee, demand};
use middle::mem_categorization::Typer;
-use middle::subst::{mod};
+use middle::subst::{self};
use middle::traits;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::{MethodCall, MethodCallee, MethodObject, MethodOrigin,
MethodParam, MethodStatic, MethodTraitObject, MethodTypeParam};
use middle::ty_fold::TypeFoldable;
// A pared down enum describing just the places from which a method
// candidate can arise. Used for error reporting only.
-#[deriving(Copy, PartialOrd, Ord, PartialEq, Eq)]
+#[derive(Copy, PartialOrd, Ord, PartialEq, Eq)]
pub enum CandidateSource {
ImplSource(ast::DefId),
TraitSource(/* trait id */ ast::DefId),
use middle::subst;
use middle::subst::Subst;
use middle::traits;
-use middle::ty::{mod, Ty, ToPolyTraitRef};
+use middle::ty::{self, Ty, ToPolyTraitRef};
use middle::ty_fold::TypeFoldable;
use middle::infer;
use middle::infer::InferCtxt;
pub kind: PickKind<'tcx>,
}
-#[deriving(Clone,Show)]
+#[derive(Clone,Show)]
pub enum PickKind<'tcx> {
InherentImplPick(/* Impl */ ast::DefId),
ObjectPick(/* Trait */ ast::DefId, /* method_num */ uint, /* real_index */ uint),
// difference is that it doesn't embed any regions or other
// specifics. The "confirmation" step recreates those details as
// needed.
-#[deriving(Clone,Show)]
+#[derive(Clone,Show)]
pub enum PickAdjustment {
// Indicates that the source expression should be autoderef'd N times
//
use self::IsBinopAssignment::*;
use self::TupleArgumentsFlag::*;
-use astconv::{mod, ast_region_to_region, ast_ty_to_ty, AstConv};
+use astconv::{self, ast_region_to_region, ast_ty_to_ty, AstConv};
use check::_match::pat_ctxt;
use middle::{const_eval, def};
use middle::infer;
use middle::lang_items::IteratorItem;
use middle::mem_categorization as mc;
use middle::mem_categorization::McResult;
-use middle::pat_util::{mod, pat_id_map};
+use middle::pat_util::{self, pat_id_map};
use middle::region::CodeExtent;
-use middle::subst::{mod, Subst, Substs, VecPerParamSpace, ParamSpace};
+use middle::subst::{self, Subst, Substs, VecPerParamSpace, ParamSpace};
use middle::traits;
use middle::ty::{FnSig, VariantInfo, TypeScheme};
use middle::ty::{Disr, ParamTy, ParameterEnvironment};
-use middle::ty::{mod, HasProjectionTypes, RegionEscape, Ty};
+use middle::ty::{self, HasProjectionTypes, RegionEscape, Ty};
use middle::ty::liberate_late_bound_regions;
use middle::ty::{MethodCall, MethodCallee, MethodMap, ObjectCastMap};
use middle::ty_fold::{TypeFolder, TypeFoldable};
use middle::lang_items::TypeIdLangItem;
use lint;
use util::common::{block_query, indenter, loop_query};
-use util::ppaux::{mod, UserString, Repr};
+use util::ppaux::{self, UserString, Repr};
use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};
use std::cell::{Cell, Ref, RefCell};
use std::mem::replace;
use std::rc::Rc;
use std::iter::repeat;
-use syntax::{mod, abi, attr};
-use syntax::ast::{mod, ProvidedMethod, RequiredMethod, TypeTraitItem, DefId};
-use syntax::ast_util::{mod, local_def, PostExpansionMethod};
-use syntax::codemap::{mod, Span};
+use syntax::{self, abi, attr};
+use syntax::ast::{self, ProvidedMethod, RequiredMethod, TypeTraitItem, DefId};
+use syntax::ast_util::{self, local_def, PostExpansionMethod};
+use syntax::codemap::{self, Span};
use syntax::owned_slice::OwnedSlice;
use syntax::parse::token;
use syntax::print::pprust;
use syntax::ptr::P;
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
mod assoc;
pub mod _match;
/// When type-checking an expression, we propagate downward
/// whatever type hint we are able in the form of an `Expectation`.
-#[deriving(Copy)]
+#[derive(Copy)]
enum Expectation<'tcx> {
/// We know nothing about what type this expression should have.
NoExpectation,
}
}
-#[deriving(Copy, Clone)]
+#[derive(Copy, Clone)]
pub struct UnsafetyState {
pub def: ast::NodeId,
pub unsafety: ast::Unsafety,
/// Whether `check_binop` is part of an assignment or not.
/// Used to know whether we allow user overloads and to print
/// better messages on error.
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
enum IsBinopAssignment{
SimpleBinop,
BinopAssignment,
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct FnCtxt<'a, 'tcx: 'a> {
body_id: ast::NodeId,
}
}
-#[deriving(Copy, Show, PartialEq, Eq)]
+#[derive(Copy, Show, PartialEq, Eq)]
pub enum LvaluePreference {
PreferMutLvalue,
NoPreference
///
/// Note: this method does not modify the adjustments table. The caller is responsible for
/// inserting an AutoAdjustment record into the `fcx` using one of the suitable methods.
-pub fn autoderef<'a, 'tcx, T, F>(fcx: &FnCtxt<'a, 'tcx>, sp: Span,
+pub fn autoderef<'a, 'tcx, T, F>(fcx: &FnCtxt<'a, 'tcx>,
+ sp: Span,
base_ty: Ty<'tcx>,
expr_id: Option<ast::NodeId>,
mut lvalue_pref: LvaluePreference,
(fcx.tcx().types.err, 0, None)
}
-/// Attempts to resolve a call expression as an overloaded call.
-fn try_overloaded_call<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
- call_expression: &ast::Expr,
- callee: &ast::Expr,
- callee_type: Ty<'tcx>,
- args: &[&P<ast::Expr>])
- -> bool {
- // Bail out if the callee is a bare function or a closure. We check those
- // manually.
- match structurally_resolved_type(fcx, callee.span, callee_type).sty {
- ty::ty_bare_fn(..) | ty::ty_closure(_) => return false,
- _ => {}
- }
-
- // Try the options that are least restrictive on the caller first.
- for &(maybe_function_trait, method_name) in [
- (fcx.tcx().lang_items.fn_trait(), token::intern("call")),
- (fcx.tcx().lang_items.fn_mut_trait(), token::intern("call_mut")),
- (fcx.tcx().lang_items.fn_once_trait(), token::intern("call_once")),
- ].iter() {
- let function_trait = match maybe_function_trait {
- None => continue,
- Some(function_trait) => function_trait,
- };
- let method_callee =
- match method::lookup_in_trait(fcx,
- call_expression.span,
- Some(&*callee),
- method_name,
- function_trait,
- callee_type,
- None) {
- None => continue,
- Some(method_callee) => method_callee,
- };
- let method_call = MethodCall::expr(call_expression.id);
- let output_type = check_method_argument_types(fcx,
- call_expression.span,
- method_callee.ty,
- call_expression,
- args,
- AutorefArgs::No,
- TupleArguments);
- fcx.inh.method_map.borrow_mut().insert(method_call, method_callee);
- write_call(fcx, call_expression, output_type);
-
- return true
- }
-
- false
-}
-
fn try_overloaded_deref<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
method_call: Option<MethodCall>,
check_argument_types(fcx,
sp,
err_inputs[],
- callee_expr,
args_no_rcvr,
autoref_args,
false,
check_argument_types(fcx,
sp,
fty.sig.0.inputs.slice_from(1),
- callee_expr,
args_no_rcvr,
autoref_args,
fty.sig.0.variadic,
fn check_argument_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
sp: Span,
fn_inputs: &[Ty<'tcx>],
- _callee_expr: &ast::Expr,
args: &[&P<ast::Expr>],
autoref_args: AutorefArgs,
variadic: bool,
// Controls whether the arguments are automatically referenced. This is useful
// for overloaded binary and unary operators.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum AutorefArgs {
Yes,
No,
/// Instead of:
///
/// f((1, 2));
-#[deriving(Clone, Eq, PartialEq)]
+#[derive(Clone, Eq, PartialEq)]
enum TupleArgumentsFlag {
DontTupleArguments,
TupleArguments,
debug!(">> typechecking: expr={} expected={}",
expr.repr(fcx.tcx()), expected.repr(fcx.tcx()));
- // A generic function for doing all of the checking for call expressions
- fn check_call(fcx: &FnCtxt,
- call_expr: &ast::Expr,
- f: &ast::Expr,
- args: &[&P<ast::Expr>]) {
- // Store the type of `f` as the type of the callee
- let fn_ty = fcx.expr_ty(f);
-
- // Extract the function signature from `in_fty`.
- let fn_ty = structurally_resolved_type(fcx, f.span, fn_ty);
-
- // This is the "default" function signature, used in case of error.
- // In that case, we check each argument against "error" in order to
- // set up all the node type bindings.
- let error_fn_sig = ty::Binder(FnSig {
- inputs: err_args(fcx.tcx(), args.len()),
- output: ty::FnConverging(fcx.tcx().types.err),
- variadic: false
- });
-
- let fn_sig = match fn_ty.sty {
- ty::ty_bare_fn(_, &ty::BareFnTy {ref sig, ..}) |
- ty::ty_closure(box ty::ClosureTy {ref sig, ..}) => sig,
- _ => {
- fcx.type_error_message(call_expr.span, |actual| {
- format!("expected function, found `{}`", actual)
- }, fn_ty, None);
- &error_fn_sig
- }
- };
-
- // Replace any late-bound regions that appear in the function
- // signature with region variables. We also have to
- // renormalize the associated types at this point, since they
- // previously appeared within a `Binder<>` and hence would not
- // have been normalized before.
- let fn_sig =
- fcx.infcx().replace_late_bound_regions_with_fresh_var(call_expr.span,
- infer::FnCall,
- fn_sig).0;
- let fn_sig =
- fcx.normalize_associated_types_in(call_expr.span,
- &fn_sig);
-
- // Call the generic checker.
- check_argument_types(fcx,
- call_expr.span,
- fn_sig.inputs[],
- f,
- args,
- AutorefArgs::No,
- fn_sig.variadic,
- DontTupleArguments);
-
- write_call(fcx, call_expr, fn_sig.output);
- }
-
// Checks a method call.
fn check_method_call(fcx: &FnCtxt,
expr: &ast::Expr,
check_block_with_expected(fcx, &**b, expected);
fcx.write_ty(id, fcx.node_ty(b.id));
}
- ast::ExprCall(ref f, ref args) => {
- // Index expressions need to be handled separately, to inform them
- // that they appear in call position.
- check_expr(fcx, &**f);
- let f_ty = fcx.expr_ty(&**f);
-
- let args: Vec<_> = args.iter().map(|x| x).collect();
- if !try_overloaded_call(fcx, expr, &**f, f_ty, args[]) {
- check_call(fcx, expr, &**f, args[]);
- let args_err = args.iter().fold(false,
- |rest_err, a| {
- // is this not working?
- let a_ty = fcx.expr_ty(&***a);
- rest_err || ty::type_is_error(a_ty)});
- if ty::type_is_error(f_ty) || args_err {
- fcx.write_error(id);
- }
- }
+ ast::ExprCall(ref callee, ref args) => {
+ callee::check_call(fcx, expr, &**callee, args.as_slice());
}
ast::ExprMethodCall(ident, ref tps, ref args) => {
check_method_call(fcx, expr, ident, args[], tps[], lvalue_pref);
use middle::region::CodeExtent;
use middle::traits;
use middle::ty::{ReScope};
-use middle::ty::{mod, Ty, MethodCall};
+use middle::ty::{self, Ty, MethodCall};
use middle::infer;
use middle::pat_util;
use util::ppaux::{ty_to_string, Repr};
pub use self::WfConstraint::*;
use middle::subst::{ParamSpace, Subst, Substs};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty_fold::{TypeFolder};
use syntax::ast;
use middle::expr_use_visitor as euv;
use middle::mem_categorization as mc;
-use middle::ty::{mod};
+use middle::ty::{self};
use middle::infer::{InferCtxt, UpvarRegion};
use syntax::ast;
use syntax::codemap::Span;
-use syntax::visit::{mod, Visitor};
+use syntax::visit::{self, Visitor};
use util::ppaux::Repr;
///////////////////////////////////////////////////////////////////////////
// except according to those terms.
use check::{FnCtxt, structurally_resolved_type};
-use middle::traits::{mod, ObjectSafetyViolation, MethodViolationCode};
+use middle::traits::{self, ObjectSafetyViolation, MethodViolationCode};
use middle::traits::{Obligation, ObligationCause};
use middle::traits::report_fulfillment_errors;
-use middle::ty::{mod, Ty, AsPredicate};
+use middle::ty::{self, Ty, AsPredicate};
use middle::infer;
use syntax::ast;
use syntax::codemap::Span;
use middle::region;
use middle::subst;
use middle::traits;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use middle::ty::liberate_late_bound_regions;
use middle::ty_fold::{TypeFolder, TypeFoldable, super_fold_ty};
use util::ppaux::Repr;
self.fcx.tcx()
}
+ fn fold_binder<T>(&mut self, binder: &ty::Binder<T>) -> ty::Binder<T>
+ where T : TypeFoldable<'tcx> + Repr<'tcx>
+ {
+ self.binding_count += 1;
+ let value = liberate_late_bound_regions(self.fcx.tcx(), self.scope, binder);
+ debug!("BoundsChecker::fold_binder: late-bound regions replaced: {}",
+ value.repr(self.tcx()));
+ let value = value.fold_with(self);
+ self.binding_count -= 1;
+ ty::Binder(value)
+ }
+
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
debug!("BoundsChecker t={}",
t.repr(self.tcx()));
self.fold_substs(substs);
}
- ty::ty_bare_fn(_, &ty::BareFnTy{sig: ref fn_sig, ..}) |
- ty::ty_closure(box ty::ClosureTy{sig: ref fn_sig, ..}) => {
- self.binding_count += 1;
-
- let fn_sig = liberate_late_bound_regions(self.fcx.tcx(), self.scope, fn_sig);
-
- debug!("late-bound regions replaced: {}",
- fn_sig.repr(self.tcx()));
-
- self.fold_fn_sig(&fn_sig);
-
- self.binding_count -= 1;
- }
_ => {
super_fold_ty(self, t);
}
use astconv::AstConv;
use check::FnCtxt;
use middle::pat_util;
-use middle::ty::{mod, Ty, MethodCall, MethodCallee};
+use middle::ty::{self, Ty, MethodCall, MethodCallee};
use middle::ty_fold::{TypeFolder,TypeFoldable};
use middle::infer;
use write_substs_to_tcx;
///////////////////////////////////////////////////////////////////////////
// Resolution reason.
-#[deriving(Copy)]
+#[derive(Copy)]
enum ResolveReason {
ResolvingExpr(Span),
ResolvingLocal(Span),
use metadata::csearch::{each_impl, get_impl_trait};
use metadata::csearch;
-use middle::subst::{mod, Subst};
+use middle::subst::{self, Subst};
use middle::ty::RegionEscape;
use middle::ty::{ImplContainer, ImplOrTraitItemId, MethodTraitItemId};
use middle::ty::{ParameterEnvironment, TypeTraitItemId, lookup_item_type};
use middle::traits;
use middle::ty;
-use middle::infer::{mod, new_infer_ctxt};
+use middle::infer::{self, new_infer_ctxt};
use syntax::ast::{DefId};
use syntax::ast::{LOCAL_CRATE};
use syntax::ast;
as `ty_param()` instances.
*/
-use astconv::{mod, AstConv, ty_of_arg, ast_ty_to_ty, ast_region_to_region};
+use astconv::{self, AstConv, ty_of_arg, ast_ty_to_ty, ast_region_to_region};
use metadata::csearch;
use middle::lang_items::SizedTraitLangItem;
use middle::region;
use middle::subst;
use middle::subst::{Substs};
use middle::ty::{AsPredicate, ImplContainer, ImplOrTraitItemContainer, TraitContainer};
-use middle::ty::{mod, RegionEscape, Ty, TypeScheme};
-use middle::ty_fold::{mod, TypeFolder, TypeFoldable};
+use middle::ty::{self, RegionEscape, Ty, TypeScheme};
+use middle::ty_fold::{self, TypeFolder, TypeFoldable};
use middle::infer;
use rscope::*;
use {CrateCtxt, no_params, write_ty_to_tcx};
use middle::infer;
use middle::subst;
use middle::subst::VecPerParamSpace;
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use session::config;
use util::common::time;
use util::ppaux::Repr;
// A scope in which all regions must be explicitly named. This is used
// for types that appear in structs and so on.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct ExplicitRscope;
impl RegionScope for ExplicitRscope {
use middle::resolve_lifetime as rl;
use middle::subst;
use middle::subst::{ParamSpace, FnSpace, TypeSpace, SelfSpace, VecPerParamSpace};
-use middle::ty::{mod, Ty};
+use middle::ty::{self, Ty};
use std::fmt;
use std::rc::Rc;
use std::iter::repeat;
type VarianceTermPtr<'a> = &'a VarianceTerm<'a>;
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
struct InferredIndex(uint);
-#[deriving(Copy)]
+#[derive(Copy)]
enum VarianceTerm<'a> {
ConstantTerm(ty::Variance),
TransformTerm(VarianceTermPtr<'a>, VarianceTermPtr<'a>),
inferred_infos: Vec<InferredInfo<'a>> ,
}
-#[deriving(Copy, Show, PartialEq)]
+#[derive(Copy, Show, PartialEq)]
enum ParamKind {
TypeParam,
RegionParam
/// Declares that the variable `decl_id` appears in a location with
/// variance `variance`.
-#[deriving(Copy)]
+#[derive(Copy)]
struct Constraint<'a> {
inferred: InferredIndex,
variance: &'a VarianceTerm<'a>,
use syntax::attr;
use syntax::attr::{AttributeMethods, AttrMetaMethods};
use syntax::codemap::{DUMMY_SP, Pos, Spanned};
-use syntax::parse::token::{mod, InternedString, special_idents};
+use syntax::parse::token::{self, InternedString, special_idents};
use syntax::ptr::P;
use rustc_trans::back::link;
use rustc::metadata::csearch;
use rustc::metadata::decoder;
use rustc::middle::def;
-use rustc::middle::subst::{mod, ParamSpace, VecPerParamSpace};
+use rustc::middle::subst::{self, ParamSpace, VecPerParamSpace};
use rustc::middle::ty;
use rustc::middle::stability;
use rustc::session::config;
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Crate {
pub name: String,
pub src: FsPath,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct ExternalCrate {
pub name: String,
pub attrs: Vec<Attribute>,
/// Anything with a source location and set of attributes and, optionally, a
/// name. That is, anything that can be documented. This doesn't correspond
/// directly to the AST's concept of an item; it's a strict superset.
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Item {
/// Stringified span
pub source: Span,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum ItemEnum {
StructItem(Struct),
EnumItem(Enum),
AssociatedTypeItem(TyParam),
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Module {
pub items: Vec<Item>,
pub is_crate: bool,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub enum Attribute {
Word(String),
List(String, Vec<Attribute> ),
fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct TyParam {
pub name: String,
pub did: ast::DefId,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub enum TyParamBound {
RegionBound(Lifetime),
TraitBound(PolyTrait, ast::TraitBoundModifier)
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct Lifetime(String);
impl Lifetime {
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub enum WherePredicate {
BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
}
// maybe use a Generic enum and use ~[Generic]?
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct Generics {
pub lifetimes: Vec<Lifetime>,
pub type_params: Vec<TyParam>,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Method {
pub generics: Generics,
pub self_: SelfTy,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct TyMethod {
pub unsafety: ast::Unsafety,
pub decl: FnDecl,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub enum SelfTy {
SelfStatic,
SelfValue,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Function {
pub decl: FnDecl,
pub generics: Generics,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct ClosureDecl {
pub lifetimes: Vec<Lifetime>,
pub decl: FnDecl,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct FnDecl {
pub inputs: Arguments,
pub output: FunctionRetTy,
pub attrs: Vec<Attribute>,
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct Arguments {
pub values: Vec<Argument>,
}
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct Argument {
pub type_: Type,
pub name: String,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub enum FunctionRetTy {
Return(Type),
NoReturn
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Trait {
pub unsafety: ast::Unsafety,
pub items: Vec<TraitMethod>,
/// An item belonging to a trait, whether a method or associated. Could be named
/// TraitItem except that's already taken by an exported enum variant.
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum TraitMethod {
RequiredMethod(Item),
ProvidedMethod(Item),
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum ImplMethod {
MethodImplItem(Item),
TypeImplItem(Item),
}
/// A trait reference, which may have higher ranked lifetimes.
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct PolyTrait {
pub trait_: Type,
pub lifetimes: Vec<Lifetime>
/// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
/// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
/// it does not preserve mutability or boxes.
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub enum Type {
/// structs/enums/traits (anything that'd be an ast::TyPath)
ResolvedPath {
PolyTraitRef(Vec<TyParamBound>),
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy)]
pub enum PrimitiveType {
Int, I8, I16, I32, I64,
Uint, U8, U16, U32, U64,
PrimitiveTuple,
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
pub enum TypeKind {
TypeEnum,
TypeFunction,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum StructField {
HiddenStructField, // inserted later by strip passes
TypedStructField(Type),
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Struct {
pub struct_type: doctree::StructType,
pub generics: Generics,
/// This is a more limited form of the standard Struct, different in that
/// it lacks the things most items have (name, id, parameterization). Found
/// only as a variant in an enum.
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct VariantStruct {
pub struct_type: doctree::StructType,
pub fields: Vec<Item>,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Enum {
pub variants: Vec<Item>,
pub generics: Generics,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Variant {
pub kind: VariantKind,
}
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum VariantKind {
CLikeVariant,
TupleVariant(Vec<Type>),
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, Show)]
+#[derive(Clone, RustcEncodable, RustcDecodable, Show)]
pub struct Span {
pub filename: String,
pub loline: uint,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct Path {
pub global: bool,
pub segments: Vec<PathSegment>,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub enum PathParameters {
AngleBracketed {
lifetimes: Vec<Lifetime>,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct PathSegment {
pub name: String,
pub params: PathParameters
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Typedef {
pub type_: Type,
pub generics: Generics,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub struct BareFunctionDecl {
pub unsafety: ast::Unsafety,
pub generics: Generics,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, Show)]
+#[derive(Clone, RustcEncodable, RustcDecodable, Show)]
pub struct Static {
pub type_: Type,
pub mutability: Mutability,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, Show)]
+#[derive(Clone, RustcEncodable, RustcDecodable, Show)]
pub struct Constant {
pub type_: Type,
pub expr: String,
}
}
-#[deriving(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
+#[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
pub enum Mutability {
Mutable,
Immutable,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Impl {
pub generics: Generics,
pub trait_: Option<Type>,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct ViewItem {
pub inner: ViewItemInner,
}
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum ViewItemInner {
ExternCrate(String, Option<String>, ast::NodeId),
Import(ViewPath)
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum ViewPath {
// use source as str;
SimpleImport(String, ImportSource),
ImportList(ImportSource, Vec<ViewListIdent>),
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct ImportSource {
pub path: Path,
pub did: Option<ast::DefId>,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct ViewListIdent {
pub name: String,
pub source: Option<ast::DefId>,
})
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Macro {
pub source: String,
}
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable)]
+#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Stability {
pub level: attr::StabilityLevel,
pub text: String
pub use self::MaybeTyped::*;
use rustc_driver::driver;
-use rustc::session::{mod, config};
+use rustc::session::{self, config};
use rustc::session::search_paths::SearchPaths;
use rustc::middle::{privacy, ty};
use rustc::lint;
}
}
-#[deriving(Show, Clone, RustcEncodable, RustcDecodable, Copy)]
+#[derive(Show, Clone, RustcEncodable, RustcDecodable, Copy)]
pub enum StructType {
/// A normal struct
Plain,
pub stab: Option<attr::Stability>,
}
-#[deriving(Show)]
+#[derive(Show)]
pub struct Static {
pub type_: P<ast::Ty>,
pub mutability: ast::Mutability,
use std::{io, str};
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct ExternalHtml{
pub in_header: String,
pub before_content: String,
/// Helper to render an optional visibility with a space after it (if the
/// visibility is preset)
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct VisSpace(pub Option<ast::Visibility>);
/// Similarly to VisSpace, this structure is used to render a function style with a
/// space after it.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct UnsafetySpace(pub ast::Unsafety);
/// Wrapper struct for properly emitting a method declaration.
pub struct Method<'a>(pub &'a clean::SelfTy, pub &'a clean::FnDecl);
/// Similar to VisSpace, but used for mutability
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct MutableSpace(pub clean::Mutability);
/// Similar to VisSpace, but used for mutability
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct RawMutableSpace(pub clean::Mutability);
/// Wrapper struct for properly emitting the stability level.
pub struct Stability<'a>(pub &'a Option<clean::Stability>);
/// discriminants. JavaScript then is used to decode them into the original value.
/// Consequently, every change to this type should be synchronized to
/// the `itemTypes` mapping table in `static/main.js`.
-#[deriving(Copy, PartialEq, Clone)]
+#[derive(Copy, PartialEq, Clone)]
pub enum ItemType {
Module = 0,
Struct = 1,
use externalfiles::ExternalHtml;
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Layout {
pub logo: String,
pub favicon: String,
}
}
-#[deriving(Eq, PartialEq, Clone, Show)]
+#[derive(Eq, PartialEq, Clone, Show)]
struct LangString {
should_fail: bool,
no_run: bool,
pub use self::ExternalLocation::*;
use std::cell::RefCell;
-use std::cmp::Ordering::{mod, Less, Greater, Equal};
+use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{HashMap, HashSet};
use std::default::Default;
/// It is intended that this context is a lightweight object which can be fairly
/// easily cloned because it is cloned per work-job (about once per item in the
/// rustdoc tree).
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Context {
/// Current hierarchy of components leading down to what's currently being
/// rendered
}
/// Metadata about implementations for a type.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Impl {
pub impl_: clean::Impl,
pub dox: Option<String>,
/// to be a fairly large and expensive structure to clone. Instead this adheres
/// to `Send` so it may be stored in a `Arc` instance and shared among the various
/// rendering tasks.
-#[deriving(Default)]
+#[derive(Default)]
pub struct Cache {
/// Mapping of typaram ids to the name of the type parameter. This is used
/// when pretty-printing a type (so pretty printing doesn't have to
// Helper structs for rendering items/sidebars and carrying along contextual
// information
-#[deriving(Copy)]
+#[derive(Copy)]
struct Item<'a> {
cx: &'a Context,
item: &'a clean::Item,
use std::string::String;
/// A (recursive) table of contents
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
pub struct Toc {
/// The levels are strictly decreasing, i.e.
///
}
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
pub struct TocEntry {
level: u32,
sec_number: String,
}
/// Progressive construction of a table of contents.
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
pub struct TocBuilder {
top_level: Toc,
/// The current hierarchy of parent headings, the levels are
use std::rc::Rc;
use externalfiles::ExternalHtml;
use serialize::Decodable;
-use serialize::json::{mod, Json};
+use serialize::json::{self, Json};
use rustc::session::search_paths::SearchPaths;
// reexported from `clean` so it can be easily updated with the mod itself
//! module's count includes its children's.
use std::cmp::Ordering;
-use std::num::Zero;
use std::ops::Add;
use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked};
use html::render::cache;
-#[deriving(Zero, RustcEncodable, RustcDecodable, PartialEq, Eq)]
+#[derive(RustcEncodable, RustcDecodable, PartialEq, Eq)]
/// The counts for each stability level.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Counts {
pub deprecated: uint,
pub experimental: uint,
}
}
-#[deriving(RustcEncodable, RustcDecodable, PartialEq, Eq)]
+#[derive(RustcEncodable, RustcDecodable, PartialEq, Eq)]
/// A summarized module, which includes total counts and summarized children
/// modules.
pub struct ModuleSummary {
use std::collections::{HashSet, HashMap};
use testing;
-use rustc::session::{mod, config};
+use rustc::session::{self, config};
use rustc::session::search_paths::{SearchPaths, PathKind};
use rustc_driver::driver;
use syntax::ast;
use std::error;
/// Available encoding character sets
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum CharacterSet {
/// The standard character set (uses `+` and `/`)
Standard,
}
/// Available newline types
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Newline {
/// A linefeed (i.e. Unix-style newline)
LF,
}
/// Contains configuration parameters for `to_base64`.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Config {
/// Character set to use
pub char_set: CharacterSet,
}
/// Errors that can occur when decoding a base64 encoded string
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum FromBase64Error {
/// The input contained a character not part of the base64 format
InvalidBase64Byte(u8, uint),
for _ in range(0u, 1000) {
let times = thread_rng().gen_range(1u, 100);
- let v = Vec::from_fn(times, |_| random::<u8>());
+ let v = thread_rng().gen_iter::<u8>().take(times).collect::<Vec<_>>();
assert_eq!(v.to_base64(STANDARD)
.from_base64()
.unwrap(),
}
/// Errors that can occur when decoding a hex encoded string
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum FromHexError {
/// The input contained a character not part of the hex format
InvalidHexCharacter(char, uint),
//! To be able to encode a piece of data, it must implement the `serialize::RustcEncodable` trait.
//! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait.
//! The Rust compiler provides an annotation to automatically generate the code for these traits:
-//! `#[deriving(RustcDecodable, RustcEncodable)]`
+//! `#[derive(RustcDecodable, RustcEncodable)]`
//!
//! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
//! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
//! use serialize::json;
//!
//! // Automatically generate `Decodable` and `Encodable` trait implementations
-//! #[deriving(RustcDecodable, RustcEncodable)]
+//! #[derive(RustcDecodable, RustcEncodable)]
//! pub struct TestStruct {
//! data_int: u8,
//! data_str: String,
//! ```notrust
//! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
//! extern crate serialize;
-//! use serialize::json::{mod, ToJson, Json};
+//! use serialize::json::{self, ToJson, Json};
//!
//! // A custom data structure
//! struct ComplexNum {
//! }
//!
//! // Only generate `RustcEncodable` trait implementation
-//! #[deriving(Encodable)]
+//! #[derive(Encodable)]
//! pub struct ComplexNumRecord {
//! uid: u8,
//! dsc: String,
//! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment
//! extern crate serialize;
//! use std::collections::BTreeMap;
-//! use serialize::json::{mod, Json, ToJson};
+//! use serialize::json::{self, Json, ToJson};
//!
//! // Only generate `Decodable` trait implementation
-//! #[deriving(Decodable)]
+//! #[derive(Decodable)]
//! pub struct TestStruct {
//! data_int: u8,
//! data_str: String,
use Encodable;
/// Represents a json value
-#[deriving(Clone, PartialEq, PartialOrd)]
+#[derive(Clone, PartialEq, PartialOrd)]
pub enum Json {
I64(i64),
U64(u64),
pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option<uint> }
/// The errors that can arise while parsing a JSON stream.
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
NotUtf8,
}
-#[deriving(Clone, Copy, PartialEq, Show)]
+#[derive(Clone, Copy, PartialEq, Show)]
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, uint, uint),
// Builder and Parser have the same errors.
pub type BuilderError = ParserError;
-#[deriving(Clone, PartialEq, Show)]
+#[derive(Clone, PartialEq, Show)]
pub enum DecoderError {
ParseError(ParserError),
ExpectedError(string::String, string::String),
}
/// The output of the streaming parser.
-#[deriving(PartialEq, Clone, Show)]
+#[derive(PartialEq, Clone, Show)]
pub enum JsonEvent {
ObjectStart,
ObjectEnd,
Error(ParserError),
}
-#[deriving(PartialEq, Show)]
+#[derive(PartialEq, Show)]
enum ParserState {
// Parse a value in an array, true means first element.
ParseArray(bool),
/// StackElements compose a Stack.
/// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the
/// StackElements compositing the stack that represents foo.bar[3].x
-#[deriving(PartialEq, Clone, Show)]
+#[derive(PartialEq, Clone, Show)]
pub enum StackElement<'l> {
Index(u32),
Key(&'l str),
// Internally, Key elements are stored as indices in a buffer to avoid
// allocating a string for every member of an object.
-#[deriving(PartialEq, Clone, Show)]
+#[derive(PartialEq, Clone, Show)]
enum InternalStackElement {
InternalIndex(u32),
InternalKey(u16, u16), // start, size
Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))),
// re: #12967.. a type w/ numeric keys (ie HashMap<uint, V> etc)
// is going to have a string here, as per JSON spec.
- Json::String(s) => match std::str::from_str(s.as_slice()) {
+ Json::String(s) => match s.parse() {
Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_string(), s)),
},
use std::num::Float;
use std::string;
- #[deriving(RustcDecodable, Eq, PartialEq, Show)]
+ #[derive(RustcDecodable, Eq, PartialEq, Show)]
struct OptionData {
opt: Option<uint>,
}
ExpectedError("Number".to_string(), "false".to_string()));
}
- #[deriving(PartialEq, RustcEncodable, RustcDecodable, Show)]
+ #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
enum Animal {
Dog,
Frog(string::String, int)
}
- #[deriving(PartialEq, RustcEncodable, RustcDecodable, Show)]
+ #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
struct Inner {
a: (),
b: uint,
c: Vec<string::String>,
}
- #[deriving(PartialEq, RustcEncodable, RustcDecodable, Show)]
+ #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)]
struct Outer {
inner: Vec<Inner>,
}
);
}
- #[deriving(RustcDecodable)]
+ #[derive(RustcDecodable)]
struct FloatStruct {
f: f64,
a: Vec<f64>
Err(SyntaxError(EOFWhileParsingObject, 3u, 8u)));
}
- #[deriving(RustcDecodable)]
+ #[derive(RustcDecodable)]
#[allow(dead_code)]
struct DecodeStruct {
x: f64,
z: string::String,
w: Vec<DecodeStruct>
}
- #[deriving(RustcDecodable)]
+ #[derive(RustcDecodable)]
enum DecodeEnum {
A(f64),
B(string::String)
//! Operations on ASCII strings and characters
#![unstable = "unsure about placement and naming"]
-#![allow(deprecated)]
use core::kinds::Sized;
use iter::IteratorExt;
($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
$($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+
}) => {
- #[deriving(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
+ #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
$(#[$attr])*
pub struct $BitFlags {
bits: $T,
use hash;
use mem;
use ptr;
-use slice::{mod, IntSliceExt};
+use slice::{self, IntSliceExt};
use str;
use string::String;
use core::kinds::marker;
self.buf
}
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub unsafe fn unwrap(self) -> *const libc::c_char { self.into_inner() }
-
/// Return the number of bytes in the CString (not including the NUL
/// terminator).
#[inline]
///
/// Use with the `std::iter` module.
#[allow(raw_pointer_deriving)]
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct CChars<'a> {
ptr: *const libc::c_char,
marker: marker::ContravariantLifetime<'a>,
self.base
}
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub unsafe fn unwrap(self) -> *mut T { self.into_inner() }
-
/// Returns the number of items in this vector.
pub fn len(&self) -> uint { self.len }
use borrow::BorrowFrom;
use clone::Clone;
-use cmp::{max, Eq, Equiv, PartialEq};
+use cmp::{max, Eq, PartialEq};
use default::Default;
-use fmt::{mod, Show};
+use fmt::{self, Show};
use hash::{Hash, Hasher, RandomSipHasher};
-use iter::{mod, Iterator, IteratorExt, FromIterator, Extend, Map};
+use iter::{self, Iterator, IteratorExt, FromIterator, Extend, Map};
use kinds::Sized;
-use mem::{mod, replace};
+use mem::{self, replace};
use num::{Int, UnsignedInt};
use ops::{Deref, FnMut, Index, IndexMut};
use option::Option;
use result::Result::{Ok, Err};
use super::table::{
- mod,
+ self,
Bucket,
EmptyBucket,
FullBucket,
/// This behavior is characterized by the following condition:
///
/// - if size > 0.909 * capacity: grow the map
-#[deriving(Clone)]
+#[derive(Clone)]
struct DefaultResizePolicy;
impl DefaultResizePolicy {
/// overridden with one of the constructors.
///
/// It is required that the keys implement the `Eq` and `Hash` traits, although
-/// this can frequently be achieved by using `#[deriving(Eq, Hash)]`.
+/// this can frequently be achieved by using `#[derive(Eq, Hash)]`.
///
/// Relevant papers/articles:
///
/// ```
/// use std::collections::HashMap;
///
-/// #[deriving(Hash, Eq, PartialEq, Show)]
+/// #[derive(Hash, Eq, PartialEq, Show)]
/// struct Viking {
/// name: String,
/// country: String,
/// println!("{} has {} hp", viking, health);
/// }
/// ```
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct HashMap<K, V, H = RandomSipHasher> {
// All hashes are keyed on these values, to prevent hash collision attacks.
table::make_hash(&self.hasher, x)
}
- #[allow(deprecated)]
- fn search_equiv<'a, Sized? Q: Hash<S> + Equiv<K>>(&'a self, q: &Q)
- -> Option<FullBucketImm<'a, K, V>> {
- let hash = self.make_hash(q);
- search_hashed(&self.table, hash, |k| q.equiv(k)).into_option()
- }
-
- #[allow(deprecated)]
- fn search_equiv_mut<'a, Sized? Q: Hash<S> + Equiv<K>>(&'a mut self, q: &Q)
- -> Option<FullBucketMut<'a, K, V>> {
- let hash = self.make_hash(q);
- search_hashed(&mut self.table, hash, |k| q.equiv(k)).into_option()
- }
-
/// Search for a key, yielding the index if it's found in the hashtable.
/// If you already have the hash for the key lying around, use
/// search_hashed.
}
}
- /// Deprecated: use `contains_key` and `BorrowFrom` instead.
- #[deprecated = "use contains_key and BorrowFrom instead"]
- pub fn contains_key_equiv<Sized? Q: Hash<S> + Equiv<K>>(&self, key: &Q) -> bool {
- self.search_equiv(key).is_some()
- }
-
- /// Deprecated: use `get` and `BorrowFrom` instead.
- #[deprecated = "use get and BorrowFrom instead"]
- pub fn find_equiv<'a, Sized? Q: Hash<S> + Equiv<K>>(&'a self, k: &Q) -> Option<&'a V> {
- self.search_equiv(k).map(|bucket| bucket.into_refs().1)
- }
-
- /// Deprecated: use `remove` and `BorrowFrom` instead.
- #[deprecated = "use remove and BorrowFrom instead"]
- pub fn pop_equiv<Sized? Q:Hash<S> + Equiv<K>>(&mut self, k: &Q) -> Option<V> {
- if self.table.size() == 0 {
- return None
- }
-
- self.reserve(1);
-
- self.search_equiv_mut(k).map(|bucket| pop_internal(bucket).1)
- }
-
/// An iterator visiting all keys in arbitrary order.
/// Iterator element type is `&'a K`.
///
self.drain();
}
- /// Deprecated: Renamed to `get`.
- #[deprecated = "Renamed to `get`"]
- pub fn find(&self, k: &K) -> Option<&V> {
- self.get(k)
- }
-
/// Returns a reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the map's key type, but
self.search(k).is_some()
}
- /// Deprecated: Renamed to `get_mut`.
- #[deprecated = "Renamed to `get_mut`"]
- pub fn find_mut(&mut self, k: &K) -> Option<&mut V> {
- self.get_mut(k)
- }
-
/// Returns a mutable reference to the value corresponding to the key.
///
/// The key may be any borrowed form of the map's key type, but
self.search_mut(k).map(|bucket| bucket.into_mut_refs().1)
}
- /// Deprecated: Renamed to `insert`.
- #[deprecated = "Renamed to `insert`"]
- pub fn swap(&mut self, k: K, v: V) -> Option<V> {
- self.insert(k, v)
- }
-
/// Inserts a key-value pair from the map. If the key already had a value
/// present in the map, that value is returned. Otherwise, `None` is returned.
///
retval
}
- /// Deprecated: Renamed to `remove`.
- #[deprecated = "Renamed to `remove`"]
- pub fn pop(&mut self, k: &K) -> Option<V> {
- self.remove(k)
- }
-
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
///
}
}
-impl<K: Eq + Hash<S>, V: Clone, S, H: Hasher<S>> HashMap<K, V, H> {
- /// Deprecated: Use `map.get(k).cloned()`.
- ///
- /// Return a copy of the value corresponding to the key.
- #[deprecated = "Use `map.get(k).cloned()`"]
- pub fn find_copy(&self, k: &K) -> Option<V> {
- self.get(k).cloned()
- }
-
- /// Deprecated: Use `map[k].clone()`.
- ///
- /// Return a copy of the value corresponding to the key.
- #[deprecated = "Use `map[k].clone()`"]
- pub fn get_copy(&self, k: &K) -> V {
- self[*k].clone()
- }
-}
-
#[stable]
impl<K: Eq + Hash<S>, V: PartialEq, S, H: Hasher<S>> PartialEq for HashMap<K, V, H> {
fn eq(&self, other: &HashMap<K, V, H>) -> bool {
inner: table::Iter<'a, K, V>
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for Iter<'a, K, V> {
fn clone(&self) -> Iter<'a, K, V> {
Iter {
inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for Keys<'a, K, V> {
fn clone(&self) -> Keys<'a, K, V> {
Keys {
inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for Values<'a, K, V> {
fn clone(&self) -> Values<'a, K, V> {
Values {
mod test_map {
use prelude::v1::*;
- use cmp::Equiv;
use super::HashMap;
use super::Entry::{Occupied, Vacant};
- use hash;
- use iter::{range_inclusive, range_step_inclusive};
+ use iter::{range_inclusive, range_step_inclusive, repeat};
use cell::RefCell;
use rand::{weak_rng, Rng};
- struct KindaIntLike(int);
-
- #[allow(deprecated)]
- impl Equiv<int> for KindaIntLike {
- fn equiv(&self, other: &int) -> bool {
- let KindaIntLike(this) = *self;
- this == *other
- }
- }
- impl<S: hash::Writer> hash::Hash<S> for KindaIntLike {
- fn hash(&self, state: &mut S) {
- let KindaIntLike(this) = *self;
- this.hash(state)
- }
- }
-
#[test]
fn test_create_capacity_zero() {
let mut m = HashMap::with_capacity(0);
thread_local! { static DROP_VECTOR: RefCell<Vec<int>> = RefCell::new(Vec::new()) }
- #[deriving(Hash, PartialEq, Eq)]
+ #[derive(Hash, PartialEq, Eq)]
struct Dropable {
k: uint
}
#[test]
fn test_drops() {
DROP_VECTOR.with(|slot| {
- *slot.borrow_mut() = Vec::from_elem(200, 0i);
+ *slot.borrow_mut() = repeat(0i).take(200).collect();
});
{
#[test]
fn test_move_iter_drops() {
DROP_VECTOR.with(|v| {
- *v.borrow_mut() = Vec::from_elem(200, 0i);
+ *v.borrow_mut() = repeat(0).take(200).collect();
});
let hm = {
assert_eq!(m.remove(&1), None);
}
- #[test]
- #[allow(deprecated)]
- fn test_pop_equiv() {
- let mut m = HashMap::new();
- m.insert(1i, 2i);
- assert_eq!(m.pop_equiv(&KindaIntLike(1)), Some(2));
- assert_eq!(m.pop_equiv(&KindaIntLike(1)), None);
- }
-
#[test]
fn test_iterate() {
let mut m = HashMap::with_capacity(4);
}
}
- #[test]
- #[allow(deprecated)]
- fn test_find_copy() {
- let mut m = HashMap::new();
- assert!(m.get(&1i).is_none());
-
- for i in range(1i, 10000) {
- m.insert(i, i + 7);
- match m.find_copy(&i) {
- None => panic!(),
- Some(v) => assert_eq!(v, i + 7)
- }
- for j in range(1i, i/100) {
- match m.find_copy(&j) {
- None => panic!(),
- Some(v) => assert_eq!(v, j + 7)
- }
- }
- }
- }
-
#[test]
fn test_eq() {
let mut m1 = HashMap::new();
use borrow::BorrowFrom;
use clone::Clone;
-use cmp::{Eq, Equiv, PartialEq};
+use cmp::{Eq, PartialEq};
use core::kinds::Sized;
use default::Default;
use fmt::Show;
use hash::{Hash, Hasher, RandomSipHasher};
use iter::{Iterator, IteratorExt, IteratorCloneExt, FromIterator, Map, Chain, Extend};
use ops::{BitOr, BitAnd, BitXor, Sub};
-use option::Option::{Some, None, mod};
+use option::Option::{Some, None, self};
use result::Result::{Ok, Err};
-use super::map::{mod, HashMap, Keys, INITIAL_CAPACITY};
+use super::map::{self, HashMap, Keys, INITIAL_CAPACITY};
// Future Optimization (FIXME!)
// =============================
///
/// ```
/// use std::collections::HashSet;
-/// #[deriving(Hash, Eq, PartialEq, Show)]
+/// #[derive(Hash, Eq, PartialEq, Show)]
/// struct Viking<'a> {
/// name: &'a str,
/// power: uint,
/// println!("{}", x);
/// }
/// ```
-#[deriving(Clone)]
+#[derive(Clone)]
#[stable]
pub struct HashSet<T, H = RandomSipHasher> {
map: HashMap<T, (), H>
self.map.shrink_to_fit()
}
- /// Deprecated: use `contains` and `BorrowFrom`.
- #[deprecated = "use contains and BorrowFrom"]
- #[allow(deprecated)]
- pub fn contains_equiv<Sized? Q: Hash<S> + Equiv<T>>(&self, value: &Q) -> bool {
- self.map.contains_key_equiv(value)
- }
-
/// An iterator visiting all elements in arbitrary order.
/// Iterator element type is &'a T.
///
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
/// A hash that is not zero, since we use a hash of zero to represent empty
/// buckets.
-#[deriving(PartialEq, Copy)]
+#[derive(PartialEq, Copy)]
pub struct SafeHash {
hash: u64,
}
/// This function wraps up `hash_keyed` to be the only way outside this
/// module to generate a SafeHash.
pub fn make_hash<Sized? T: Hash<S>, S, H: Hasher<S>>(hasher: &H, t: &T) -> SafeHash {
- match hasher.hash(t) {
- // This constant is exceedingly likely to hash to the same
- // bucket, but it won't be counted as empty! Just so we can maintain
- // our precious uniform distribution of initial indexes.
- EMPTY_BUCKET => SafeHash { hash: 0x8000_0000_0000_0000 },
- h => SafeHash { hash: h },
- }
+ // We need to avoid 0u64 in order to prevent collisions with
+ // EMPTY_HASH. We can maintain our precious uniform distribution
+ // of initial indexes by unconditionally setting the MSB,
+ // effectively reducing 64-bits hashes to 63 bits.
+ SafeHash { hash: 0x8000_0000_0000_0000 | hasher.hash(t) }
}
// `replace` casts a `*u64` to a `*SafeHash`. Since we statically
marker: marker::ContravariantLifetime<'a>,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for RawBuckets<'a, K, V> {
fn clone(&self) -> RawBuckets<'a, K, V> {
RawBuckets {
elems_left: uint,
}
-// FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for Iter<'a, K, V> {
fn clone(&self) -> Iter<'a, K, V> {
Iter {
pub use core_collections::{BinaryHeap, Bitv, BitvSet, BTreeMap, BTreeSet};
pub use core_collections::{DList, RingBuf, VecMap};
-/// Deprecated: Moved to collect-rs: https://github.com/Gankro/collect-rs/
-#[deprecated = "Moved to collect-rs: https://github.com/Gankro/collect-rs/"]
-pub use core_collections::EnumSet;
-
pub use core_collections::{binary_heap, bitv, bitv_set, btree_map, btree_set};
pub use core_collections::{dlist, ring_buf, vec_map};
-/// Deprecated: Moved to collect-rs: https://github.com/Gankro/collect-rs/
-#[deprecated = "Moved to collect-rs: https://github.com/Gankro/collect-rs/"]
-pub use core_collections::enum_set;
-
pub use self::hash_map::HashMap;
pub use self::hash_set::HashSet;
dlclose(handle as *mut libc::c_void); ()
}
- #[deriving(Copy)]
+ #[derive(Copy)]
pub enum Rtld {
Lazy = 1,
Now = 2,
use prelude::v1::*;
-use any::{Any, AnyRefExt};
+use any::Any;
use cell::RefCell;
use io::IoResult;
use rt::{backtrace, unwind};
//! Generic hashing support.
//!
//! This module provides a generic way to compute the hash of a value. The
-//! simplest way to make a type hashable is to use `#[deriving(Hash)]`:
+//! simplest way to make a type hashable is to use `#[derive(Hash)]`:
//!
//! # Example
//!
//! use std::hash;
//! use std::hash::Hash;
//!
-//! #[deriving(Hash)]
+//! #[derive(Hash)]
//! struct Person {
//! id: uint,
//! name: String,
/// `RandomSipHasher` computes the SipHash algorithm from a stream of bytes
/// initialized with random keys.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct RandomSipHasher {
hasher: sip::SipHasher,
}
///
/// Note that any leftover data in the internal buffer is lost.
pub fn into_inner(self) -> R { self.inner }
-
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> R { self.into_inner() }
}
impl<R: Reader> Buffer for BufferedReader<R> {
self.flush_buf().unwrap();
self.inner.take().unwrap()
}
-
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> W { self.into_inner() }
}
impl<W: Writer> Writer for BufferedWriter<W> {
///
/// The internal buffer is flushed before returning the writer.
pub fn into_inner(self) -> W { self.inner.into_inner() }
-
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> W { self.into_inner() }
}
impl<W: Writer> Writer for LineBufferedWriter<W> {
let InternalBufferedWriter(w) = self.inner.inner;
w.into_inner()
}
-
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> S { self.into_inner() }
}
impl<S: Stream> Buffer for BufferedStream<S> {
/// A type, free to create, primarily intended for benchmarking creation of
/// wrappers that, just for construction, don't need a Reader/Writer that
/// does anything useful. Is equivalent to `/dev/null` in semantics.
- #[deriving(Clone,PartialEq,PartialOrd)]
+ #[derive(Clone,PartialEq,PartialOrd)]
pub struct NullStream;
impl Reader for NullStream {
({
use super::u64_from_be_bytes;
- let data = Vec::from_fn($stride*100+$start_index, |i| i as u8);
+ let data = range(0u8, $stride*100+$start_index).collect::<Vec<_>>();
let mut sum = 0u64;
$b.iter(|| {
let mut i = $start_index;
}
/// An iterator that walks over a directory
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Directories {
stack: Vec<Path>,
}
//! Readers and Writers for in-memory buffers
-#![allow(deprecated)]
-
use cmp::min;
use option::Option::None;
use result::Result::{Err, Ok};
use io;
use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
-use slice::{mod, AsSlice, SliceExt};
+use slice::{self, AsSlice, SliceExt};
use vec::Vec;
const BUF_CAPACITY: uint = 128;
/// assert_eq!(w.into_inner(), vec!(0, 1, 2));
/// ```
#[deprecated = "use the Vec<u8> Writer implementation directly"]
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct MemWriter {
buf: Vec<u8>,
}
+#[allow(deprecated)]
impl MemWriter {
/// Create a new `MemWriter`.
#[inline]
/// Unwraps this `MemWriter`, returning the underlying buffer
#[inline]
pub fn into_inner(self) -> Vec<u8> { self.buf }
-
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> Vec<u8> { self.into_inner() }
}
impl Writer for MemWriter {
/// Unwraps this `MemReader`, returning the underlying buffer
#[inline]
pub fn into_inner(self) -> Vec<u8> { self.buf }
-
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> Vec<u8> { self.into_inner() }
}
impl Reader for MemReader {
extern crate "test" as test_crate;
use prelude::v1::*;
- use super::*;
use io::{SeekSet, SeekCur, SeekEnd};
use io;
+ use iter::repeat;
use self::test_crate::Bencher;
+ use super::*;
#[test]
fn test_vec_writer() {
}
fn do_bench_mem_writer(b: &mut Bencher, times: uint, len: uint) {
- let src: Vec<u8> = Vec::from_elem(len, 5);
+ let src: Vec<u8> = repeat(5).take(len).collect();
b.bytes = (times * len) as u64;
b.iter(|| {
wr.write(src.as_slice()).unwrap();
}
- let v = wr.unwrap();
+ let v = wr.into_inner();
assert_eq!(v.len(), times * len);
assert!(v.iter().all(|x| *x == 5));
});
pub use self::net::ip::IpAddr;
pub use self::net::tcp::TcpListener;
pub use self::net::tcp::TcpStream;
-pub use self::net::udp::UdpStream;
pub use self::pipe::PipeStream;
pub use self::process::{Process, Command};
pub use self::tempfile::TempDir;
/// # FIXME
///
/// Is something like this sufficient? It's kind of archaic
-#[deriving(PartialEq, Eq, Clone)]
+#[derive(PartialEq, Eq, Clone)]
pub struct IoError {
/// An enumeration which can be matched against for determining the flavor
/// of error.
}
/// A list specifying general categories of I/O error.
-#[deriving(Copy, PartialEq, Eq, Clone, Show)]
+#[derive(Copy, PartialEq, Eq, Clone, Show)]
pub enum IoErrorKind {
/// Any I/O error not part of this list.
OtherIoError,
}
}
-/// A reader which can be converted to a RefReader.
-#[deprecated = "use ByRefReader instead"]
-pub trait AsRefReader {
- /// Creates a wrapper around a mutable reference to the reader.
- ///
- /// This is useful to allow applying adaptors while still
- /// retaining ownership of the original value.
- fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self>;
-}
-
-#[allow(deprecated)]
-impl<T: Reader> AsRefReader for T {
- fn by_ref<'a>(&'a mut self) -> RefReader<'a, T> {
- RefReader { inner: self }
- }
-}
-
/// A reader which can be converted to a RefReader.
pub trait ByRefReader {
/// Creates a wrapper around a mutable reference to the reader.
}
}
-/// A writer which can be converted to a RefWriter.
-#[deprecated = "use ByRefWriter instead"]
-pub trait AsRefWriter {
- /// Creates a wrapper around a mutable reference to the writer.
- ///
- /// This is useful to allow applying wrappers while still
- /// retaining ownership of the original value.
- #[inline]
- fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self>;
-}
-
-#[allow(deprecated)]
-impl<T: Writer> AsRefWriter for T {
- fn by_ref<'a>(&'a mut self) -> RefWriter<'a, T> {
- RefWriter { inner: self }
- }
-}
-
/// A writer which can be converted to a RefWriter.
pub trait ByRefWriter {
/// Creates a wrapper around a mutable reference to the writer.
/// When seeking, the resulting cursor is offset from a base by the offset given
/// to the `seek` function. The base used is specified by this enumeration.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum SeekStyle {
/// Seek from the beginning of the stream
SeekSet,
/// A mode specifies how a file should be opened or created. These modes are
/// passed to `File::open_mode` and are used to control where the file is
/// positioned when it is initially opened.
-#[deriving(Copy, Clone, PartialEq, Eq)]
+#[derive(Copy, Clone, PartialEq, Eq)]
pub enum FileMode {
/// Opens a file positioned at the beginning.
Open,
/// Access permissions with which the file should be opened. `File`s
/// opened with `Read` will return an error if written to.
-#[deriving(Copy, Clone, PartialEq, Eq)]
+#[derive(Copy, Clone, PartialEq, Eq)]
pub enum FileAccess {
/// Read-only access, requests to write will result in an error
Read,
}
/// Different kinds of files which can be identified by a call to stat
-#[deriving(Copy, PartialEq, Show, Hash, Clone)]
+#[derive(Copy, PartialEq, Show, Hash, Clone)]
pub enum FileType {
/// This is a normal file, corresponding to `S_IFREG`
RegularFile,
/// println!("byte size: {}", info.size);
/// # }
/// ```
-#[deriving(Copy, Hash)]
+#[derive(Copy, Hash)]
pub struct FileStat {
/// The size of the file, in bytes
pub size: u64,
/// structure. This information is not necessarily platform independent, and may
/// have different meanings or no meaning at all on some platforms.
#[unstable]
-#[deriving(Copy, Hash)]
+#[derive(Copy, Hash)]
pub struct UnstableFileStat {
/// The ID of the device containing the file.
pub device: u64,
#[doc = "All possible permissions enabled."]
const ALL_PERMISSIONS = USER_RWX.bits | GROUP_RWX.bits | OTHER_RWX.bits,
-
- // Deprecated names
- #[allow(non_upper_case_globals)]
- #[deprecated = "use USER_READ instead"]
- const UserRead = USER_READ.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use USER_WRITE instead"]
- const UserWrite = USER_WRITE.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use USER_EXECUTE instead"]
- const UserExecute = USER_EXECUTE.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use GROUP_READ instead"]
- const GroupRead = GROUP_READ.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use GROUP_WRITE instead"]
- const GroupWrite = GROUP_WRITE.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use GROUP_EXECUTE instead"]
- const GroupExecute = GROUP_EXECUTE.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use OTHER_READ instead"]
- const OtherRead = OTHER_READ.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use OTHER_WRITE instead"]
- const OtherWrite = OTHER_WRITE.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use OTHER_EXECUTE instead"]
- const OtherExecute = OTHER_EXECUTE.bits,
-
- #[allow(non_upper_case_globals)]
- #[deprecated = "use USER_RWX instead"]
- const UserRWX = USER_RWX.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use GROUP_RWX instead"]
- const GroupRWX = GROUP_RWX.bits,
- #[allow(non_upper_case_globals)]
- #[deprecated = "use OTHER_RWX instead"]
- const OtherRWX = OTHER_RWX.bits,
-
- #[doc = "Deprecated: use `USER_FILE` instead."]
- #[allow(non_upper_case_globals)]
- #[deprecated = "use USER_FILE instead"]
- const UserFile = USER_FILE.bits,
-
- #[doc = "Deprecated: use `USER_DIR` instead."]
- #[allow(non_upper_case_globals)]
- #[deprecated = "use USER_DIR instead"]
- const UserDir = USER_DIR.bits,
- #[doc = "Deprecated: use `USER_EXEC` instead."]
- #[allow(non_upper_case_globals)]
- #[deprecated = "use USER_EXEC instead"]
- const UserExec = USER_EXEC.bits,
-
- #[doc = "Deprecated: use `ALL_PERMISSIONS` instead"]
- #[allow(non_upper_case_globals)]
- #[deprecated = "use ALL_PERMISSIONS instead"]
- const AllPermissions = ALL_PERMISSIONS.bits,
}
}
use prelude::v1::{Ok, Vec, Buffer, SliceExt};
use uint;
- #[deriving(Clone, PartialEq, Show)]
+ #[derive(Clone, PartialEq, Show)]
enum BadReaderBehavior {
GoodBehavior(uint),
BadBehavior(uint)
use vec::Vec;
/// Hints to the types of sockets that are desired when looking up hosts
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum SocketType {
Stream, Datagram, Raw
}
/// to manipulate how a query is performed.
///
/// The meaning of each of these flags can be found with `man -s 3 getaddrinfo`
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Flag {
AddrConfig,
All,
/// A transport protocol associated with either a hint or a return value of
/// `lookup`
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Protocol {
TCP, UDP
}
///
/// For details on these fields, see their corresponding definitions via
/// `man -s 3 getaddrinfo`
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Hint {
pub family: uint,
pub socktype: Option<SocketType>,
pub flags: uint,
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Info {
pub address: SocketAddr,
pub family: uint,
pub use self::IpAddr::*;
use fmt;
-use io::{mod, IoResult, IoError};
+use io::{self, IoResult, IoError};
use io::net;
use iter::{Iterator, IteratorExt};
use ops::FnOnce;
pub type Port = u16;
-#[deriving(Copy, PartialEq, Eq, Clone, Hash)]
+#[derive(Copy, PartialEq, Eq, Clone, Hash)]
pub enum IpAddr {
Ipv4Addr(u8, u8, u8, u8),
Ipv6Addr(u16, u16, u16, u16, u16, u16, u16, u16)
}
}
-#[deriving(Copy, PartialEq, Eq, Clone, Hash)]
+#[derive(Copy, PartialEq, Eq, Clone, Hash)]
pub struct SocketAddr {
pub ip: IpAddr,
pub port: Port,
use clone::Clone;
use io::net::ip::{SocketAddr, IpAddr, ToSocketAddr};
-use io::{Reader, Writer, IoResult};
-use ops::FnOnce;
+use io::IoResult;
use option::Option;
-use result::Result::{Ok, Err};
use sys::udp::UdpSocket as UdpSocketImp;
use sys_common;
super::with_addresses(addr, |addr| self.inner.send_to(buf, addr))
}
- /// Creates a `UdpStream`, which allows use of the `Reader` and `Writer`
- /// traits to receive and send data from the same address. This transfers
- /// ownership of the socket to the stream.
- ///
- /// Note that this call does not perform any actual network communication,
- /// because UDP is a datagram protocol.
- #[deprecated = "`UdpStream` has been deprecated"]
- #[allow(deprecated)]
- pub fn connect(self, other: SocketAddr) -> UdpStream {
- UdpStream {
- socket: self,
- connected_to: other,
- }
- }
-
/// Returns the socket address that this socket was created from.
pub fn socket_name(&mut self) -> IoResult<SocketAddr> {
self.inner.socket_name()
}
}
-/// A type that allows convenient usage of a UDP stream connected to one
-/// address via the `Reader` and `Writer` traits.
-///
-/// # Note
-///
-/// This structure has been deprecated because `Reader` is a stream-oriented API but UDP
-/// is a packet-oriented protocol. Every `Reader` method will read a whole packet and
-/// throw all superfluous bytes away so that they are no longer available for further
-/// method calls.
-#[deprecated]
-pub struct UdpStream {
- socket: UdpSocket,
- connected_to: SocketAddr
-}
-
-impl UdpStream {
- /// Allows access to the underlying UDP socket owned by this stream. This
- /// is useful to, for example, use the socket to send data to hosts other
- /// than the one that this stream is connected to.
- pub fn as_socket<T, F>(&mut self, f: F) -> T where
- F: FnOnce(&mut UdpSocket) -> T,
- {
- f(&mut self.socket)
- }
-
- /// Consumes this UDP stream and returns out the underlying socket.
- pub fn disconnect(self) -> UdpSocket {
- self.socket
- }
-}
-
-impl Reader for UdpStream {
- /// Returns the next non-empty message from the specified address.
- fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
- let peer = self.connected_to;
- self.as_socket(|sock| {
- loop {
- let (nread, src) = try!(sock.recv_from(buf));
- if nread > 0 && src == peer {
- return Ok(nread);
- }
- }
- })
- }
-}
-
-impl Writer for UdpStream {
- fn write(&mut self, buf: &[u8]) -> IoResult<()> {
- let connected_to = self.connected_to;
- self.as_socket(|sock| sock.send_to(buf, connected_to))
- }
-}
-
#[cfg(test)]
#[allow(experimental)]
mod test {
}
}
- #[test]
- #[allow(deprecated)]
- fn stream_smoke_test_ip4() {
- let server_ip = next_test_ip4();
- let client_ip = next_test_ip4();
- let dummy_ip = next_test_ip4();
- let (tx1, rx1) = channel();
- let (tx2, rx2) = channel();
-
- let _t = Thread::spawn(move|| {
- let send_as = |&:ip, val: &[u8]| {
- match UdpSocket::bind(ip) {
- Ok(client) => {
- let client = box client;
- let mut stream = client.connect(server_ip);
- stream.write(val).unwrap();
- }
- Err(..) => panic!()
- }
- };
- rx1.recv().unwrap();
- send_as(dummy_ip, &[98]);
- send_as(client_ip, &[99]);
- tx2.send(()).unwrap();
- });
-
- match UdpSocket::bind(server_ip) {
- Ok(server) => {
- let server = box server;
- let mut stream = server.connect(client_ip);
- tx1.send(()).unwrap();
- let mut buf = [0];
- match stream.read(&mut buf) {
- Ok(nread) => {
- assert_eq!(nread, 1);
- assert_eq!(buf[0], 99);
- }
- Err(..) => panic!(),
- }
- }
- Err(..) => panic!()
- }
- rx2.recv().unwrap();
- }
-
- #[test]
- #[allow(deprecated)]
- fn stream_smoke_test_ip6() {
- let server_ip = next_test_ip6();
- let client_ip = next_test_ip6();
- let (tx1, rx1) = channel();
- let (tx2, rx2) = channel();
-
- let _t = Thread::spawn(move|| {
- match UdpSocket::bind(client_ip) {
- Ok(client) => {
- let client = box client;
- let mut stream = client.connect(server_ip);
- rx1.recv().unwrap();
- stream.write(&[99]).unwrap();
- }
- Err(..) => panic!()
- }
- tx2.send(()).unwrap();
- });
-
- match UdpSocket::bind(server_ip) {
- Ok(server) => {
- let server = box server;
- let mut stream = server.connect(client_ip);
- tx1.send(()).unwrap();
- let mut buf = [0];
- match stream.read(&mut buf) {
- Ok(nread) => {
- assert_eq!(nread, 1);
- assert_eq!(buf[0], 99);
- }
- Err(..) => panic!()
- }
- }
- Err(..) => panic!()
- }
- rx2.recv().unwrap();
- }
-
pub fn socket_name(addr: SocketAddr) {
let server = UdpSocket::bind(addr);
/// A representation of environment variable name
/// It compares case-insensitive on Windows and case-sensitive everywhere else.
#[cfg(not(windows))]
-#[deriving(PartialEq, Eq, Hash, Clone, Show)]
+#[derive(PartialEq, Eq, Hash, Clone, Show)]
struct EnvKey(CString);
#[doc(hidden)]
#[cfg(windows)]
-#[deriving(Eq, Clone, Show)]
+#[derive(Eq, Clone, Show)]
struct EnvKey(CString);
#[cfg(windows)]
///
/// let output = process.stdout.as_mut().unwrap().read_to_end();
/// ```
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Command {
// The internal data for the builder. Documented by the builder
// methods below, and serialized into rt::rtio::ProcessConfig.
}
/// The output of a finished process.
-#[deriving(PartialEq, Eq, Clone)]
+#[derive(PartialEq, Eq, Clone)]
pub struct ProcessOutput {
/// The status (exit code) of the process.
pub status: ProcessExit,
}
/// Describes what to do with a standard io stream for a child process.
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub enum StdioContainer {
/// This stream will be ignored. This is the equivalent of attaching the
/// stream to `/dev/null`
/// Describes the result of a process after it has terminated.
/// Note that Windows have no signals, so the result is usually ExitStatus.
-#[deriving(PartialEq, Eq, Clone, Copy)]
+#[derive(PartialEq, Eq, Clone, Copy)]
pub enum ProcessExit {
/// Normal termination with an exit status.
ExitStatus(int),
unsafe impl Sync for RaceBox {}
/// A synchronized wrapper around a buffered reader from stdin
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct StdinReader {
inner: Arc<Mutex<RaceBox>>,
}
use os;
use path::{Path, GenericPath};
use result::Result::{Ok, Err};
-use sync::atomic;
+use sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering};
/// A wrapper for a path to temporary directory implementing automatic
/// scope-based deletion.
return TempDir::new_in(&abs_tmpdir, suffix);
}
- static CNT: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT;
+ static CNT: AtomicUint = ATOMIC_UINT_INIT;
let mut attempts = 0u;
loop {
let filename =
format!("rs-{}-{}-{}",
unsafe { libc::getpid() },
- CNT.fetch_add(1, atomic::SeqCst),
+ CNT.fetch_add(1, Ordering::SeqCst),
suffix);
let p = tmpdir.join(filename);
match fs::mkdir(&p, io::USER_RWX) {
tmpdir.path.take().unwrap()
}
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> Path { self.into_inner() }
-
/// Access the wrapped `std::path::Path` to the temporary directory.
pub fn path<'a>(&'a self) -> &'a Path {
self.path.as_ref().unwrap()
use libc;
use os;
use std::io::net::ip::*;
-use sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Relaxed};
+use sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUint = ATOMIC_UINT_INIT;
- base_port() + NEXT_OFFSET.fetch_add(1, Relaxed) as u16
+ base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
/// Get a temporary path which could be the location of a unix socket
let string = format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
- COUNT.fetch_add(1, Relaxed));
+ COUNT.fetch_add(1, Ordering::Relaxed));
if cfg!(unix) {
os::tmpdir().join(string)
} else {
/// Consumes the `LimitReader`, returning the underlying `Reader`.
pub fn into_inner(self) -> R { self.inner }
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner"]
- pub fn unwrap(self) -> R { self.into_inner() }
-
/// Returns the number of bytes that can be read before the `LimitReader`
/// will return EOF.
///
}
/// A `Writer` which ignores bytes written to it, like /dev/null.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct NullWriter;
impl Writer for NullWriter {
}
/// A `Reader` which returns an infinite stream of 0 bytes, like /dev/zero.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct ZeroReader;
impl Reader for ZeroReader {
}
/// A `Reader` which is always at EOF, like /dev/null.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct NullReader;
impl Reader for NullReader {
/// A `Reader` which chains input from multiple `Reader`s, reading each to
/// completion before moving onto the next.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct ChainedReader<I, R> {
readers: I,
cur_reader: Option<R>,
let TeeReader { reader, writer } = self;
(reader, writer)
}
-
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner"]
- pub fn unwrap(self) -> (R, W) { self.into_inner() }
}
impl<R: Reader, W: Writer> Reader for TeeReader<R, W> {
}
/// An adaptor converting an `Iterator<u8>` to a `Reader`.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct IterReader<T> {
iter: T,
}
/* Threads and communication */
-pub mod task;
pub mod thread;
pub mod sync;
#[cfg(test)] use ops::{Add, Sub, Mul, Div, Rem};
#[cfg(test)] use kinds::Copy;
-pub use core::num::{Num, div_rem, Zero, zero, One, one};
-pub use core::num::{Unsigned, pow, Bounded};
-pub use core::num::{Primitive, Int, SignedInt, UnsignedInt};
+pub use core::num::{Int, SignedInt, UnsignedInt};
pub use core::num::{cast, FromPrimitive, NumCast, ToPrimitive};
-pub use core::num::{next_power_of_two, is_power_of_two};
-pub use core::num::{checked_next_power_of_two};
pub use core::num::{from_int, from_i8, from_i16, from_i32, from_i64};
pub use core::num::{from_uint, from_u8, from_u16, from_u32, from_u64};
pub use core::num::{from_f32, from_f64};
// DEPRECATED
-#[deprecated = "Use `FloatMath::abs_sub`"]
-pub fn abs_sub<T: FloatMath>(x: T, y: T) -> T {
- x.abs_sub(y)
-}
-
/// Helper function for testing numeric operations
#[cfg(test)]
pub fn test_num<T>(ten: T, two: T) where
test_checked_next_power_of_two! { test_checked_next_power_of_two_u64, u64 }
test_checked_next_power_of_two! { test_checked_next_power_of_two_uint, uint }
- #[deriving(PartialEq, Show)]
+ #[derive(PartialEq, Show)]
struct Value { x: int }
impl ToPrimitive for Value {
#[bench]
fn bench_pow_function(b: &mut Bencher) {
- let v = Vec::from_fn(1024u, |n| n);
+ let v = range(0, 1024u).collect::<Vec<_>>();
b.iter(|| {v.iter().fold(0u, |old, new| old.pow(*new));});
}
}
use self::SignificantDigits::*;
use self::SignFormat::*;
-use char::{mod, Char};
-use num::{mod, Int, Float, ToPrimitive};
+use char::{self, Char};
+use num::{self, Int, Float, ToPrimitive};
use num::FpCategory as Fp;
use ops::FnMut;
use slice::SliceExt;
use vec::Vec;
/// A flag that specifies whether to use exponential (scientific) notation.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum ExponentFormat {
/// Do not use exponential notation.
ExpNone,
/// The number of digits used for emitting the fractional part of a number, if
/// any.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum SignificantDigits {
/// All calculable digits will be printed.
///
}
/// How to emit the sign of a number.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum SignFormat {
/// No sign will be printed. The exponent sign will also be emitted.
SignNone,
pub use core::u16::{BITS, BYTES, MIN, MAX};
-use ops::FnOnce;
-
uint_module! { u16 }
pub use core::u32::{BITS, BYTES, MIN, MAX};
-use ops::FnOnce;
-
uint_module! { u32 }
pub use core::u64::{BITS, BYTES, MIN, MAX};
-use ops::FnOnce;
-
uint_module! { u64 }
pub use core::u8::{BITS, BYTES, MIN, MAX};
-use ops::FnOnce;
-
uint_module! { u8 }
pub use core::uint::{BITS, BYTES, MIN, MAX};
-use ops::FnOnce;
-
uint_module! { uint }
// String conversion functions and impl num -> str
-/// Convert to a string as a byte slice in a given base.
-///
-/// Use in place of x.to_string() when you do not need to store the string permanently
-///
-/// # Examples
-///
-/// ```
-/// #![allow(deprecated)]
-///
-/// std::uint::to_str_bytes(123, 10, |v| {
-/// assert!(v == "123".as_bytes());
-/// });
-/// ```
-#[inline]
-#[deprecated = "just use .to_string(), or a BufWriter with write! if you mustn't allocate"]
-pub fn to_str_bytes<U, F>(n: $T, radix: uint, f: F) -> U where
- F: FnOnce(&[u8]) -> U,
-{
- use io::{Writer, Seek};
- // The radix can be as low as 2, so we need at least 64 characters for a
- // base 2 number, and then we need another for a possible '-' character.
- let mut buf = [0u8; 65];
- let amt = {
- let mut wr = ::io::BufWriter::new(&mut buf);
- (write!(&mut wr, "{}", ::fmt::radix(n, radix as u8))).unwrap();
- wr.tell().unwrap() as uint
- };
- f(buf[..amt])
-}
-
#[cfg(test)]
mod tests {
use prelude::v1::*;
use num::FromStrRadix;
- use str::from_str;
+
+ fn from_str<T: ::str::FromStr>(t: &str) -> Option<T> {
+ ::str::FromStr::from_str(t)
+ }
#[test]
pub fn test_from_str() {
use slice::{AsSlice, SliceExt};
use str::{Str, StrExt};
use string::{String, ToString};
-use sync::atomic::{AtomicInt, ATOMIC_INT_INIT, SeqCst};
+use sync::atomic::{AtomicInt, ATOMIC_INT_INIT, Ordering};
use vec::Vec;
#[cfg(unix)] use c_str::ToCStr;
}
/// A low-level OS in-memory pipe.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Pipe {
/// A file descriptor representing the reading end of the pipe. Data written
/// on the `out` file descriptor can be read from this file descriptor.
///
/// Note that this is not synchronized against modifications of other threads.
pub fn set_exit_status(code: int) {
- EXIT_STATUS.store(code, SeqCst)
+ EXIT_STATUS.store(code, Ordering::SeqCst)
}
/// Fetches the process's current exit code. This defaults to 0 and can change
/// by calling `set_exit_status`.
pub fn get_exit_status() -> int {
- EXIT_STATUS.load(SeqCst)
+ EXIT_STATUS.load(Ordering::SeqCst)
}
#[cfg(target_os = "macos")]
impl Copy for MapOption {}
/// Possible errors when creating a map.
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum MapError {
/// # The following are POSIX-specific
///
use option::Option;
use option::Option::{None, Some};
use str;
-use str::{CowString, MaybeOwned, Str, StrExt};
-use string::String;
-use slice::{AsSlice, SliceExt};
+use str::StrExt;
+use string::{String, CowString};
+use slice::SliceExt;
use vec::Vec;
/// Typedef for POSIX file paths.
}
}
-#[allow(deprecated)]
-impl<'a> BytesContainer for str::MaybeOwned<'a> {
- #[inline]
- fn container_as_bytes<'b>(&'b self) -> &'b [u8] {
- self.as_slice().as_bytes()
- }
- #[inline]
- fn container_as_str<'b>(&'b self) -> Option<&'b str> {
- Some(self.as_slice())
- }
- #[inline]
- fn is_str(_: Option<&str::MaybeOwned>) -> bool { true }
-}
-
impl<'a, Sized? T: BytesContainer> BytesContainer for &'a T {
#[inline]
fn container_as_bytes(&self) -> &[u8] {
Map<&'a [u8], Option<&'a str>, Components<'a>, fn(&[u8]) -> Option<&str>>;
/// Represents a POSIX file path
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Path {
repr: Vec<u8>, // assumed to never be empty or contain NULs
sepidx: Option<uint> // index of the final separator in repr
use clone::Clone;
use iter::IteratorExt;
- use option::Option::{mod, Some, None};
+ use option::Option::{self, Some, None};
use path::GenericPath;
use slice::{AsSlice, SliceExt};
- use str::{mod, Str, StrExt};
+ use str::{self, Str, StrExt};
use string::ToString;
use vec::Vec;
//
// The only error condition imposed here is valid utf-8. All other invalid paths are simply
// preserved by the data structure; let the Windows API error out on them.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Path {
repr: String, // assumed to never be empty
prefix: Option<PathPrefix>,
}
/// Prefix types for Path
-#[deriving(Copy, PartialEq, Clone, Show)]
+#[derive(Copy, PartialEq, Clone, Show)]
pub enum PathPrefix {
/// Prefix `\\?\`, uint is the length of the following component
VerbatimPrefix(uint),
use clone::Clone;
use iter::IteratorExt;
- use option::Option::{mod, Some, None};
+ use option::Option::{self, Some, None};
use path::GenericPath;
use slice::{AsSlice, SliceExt};
use str::Str;
#[stable] #[doc(no_inline)] pub use iter::ExactSizeIterator;
#[stable] #[doc(no_inline)] pub use iter::{Iterator, IteratorExt, Extend};
#[stable] #[doc(no_inline)] pub use iter::{IteratorCloneExt, IteratorOrdExt};
-#[stable] #[doc(no_inline)] pub use option::Option::{mod, Some, None};
+#[stable] #[doc(no_inline)] pub use option::Option::{self, Some, None};
#[stable] #[doc(no_inline)] pub use ptr::{PtrExt, MutPtrExt};
-#[stable] #[doc(no_inline)] pub use result::Result::{mod, Ok, Err};
+#[stable] #[doc(no_inline)] pub use result::Result::{self, Ok, Err};
#[stable] #[doc(no_inline)] pub use slice::AsSlice;
#[stable] #[doc(no_inline)] pub use slice::{SliceExt, SliceConcatExt};
#[stable] #[doc(no_inline)] pub use str::{Str, StrExt};
/// The standard RNG. This is designed to be efficient on the current
/// platform.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct StdRng {
rng: IsaacWordRng,
}
mod test {
use prelude::v1::*;
use super::{Rng, thread_rng, random, SeedableRng, StdRng, sample};
- use iter::order;
+ use iter::{order, repeat};
struct ConstRng { i: u64 }
impl Rng for ConstRng {
let lengths = [0, 1, 2, 3, 4, 5, 6, 7,
80, 81, 82, 83, 84, 85, 86, 87];
for &n in lengths.iter() {
- let mut v = Vec::from_elem(n, 0u8);
+ let mut v = repeat(0u8).take(n).collect::<Vec<_>>();
r.fill_bytes(v.as_mut_slice());
// use this to get nicer error messages.
target_arch = "arm",
target_arch = "aarch64")))]
fn is_getrandom_available() -> bool {
- use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Relaxed};
+ use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
static GETRANDOM_CHECKED: AtomicBool = ATOMIC_BOOL_INIT;
static GETRANDOM_AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT;
- if !GETRANDOM_CHECKED.load(Relaxed) {
+ if !GETRANDOM_CHECKED.load(Ordering::Relaxed) {
let mut buf: [u8; 0] = [];
let result = getrandom(&mut buf);
let available = if result == -1 {
} else {
true
};
- GETRANDOM_AVAILABLE.store(available, Relaxed);
- GETRANDOM_CHECKED.store(true, Relaxed);
+ GETRANDOM_AVAILABLE.store(available, Ordering::Relaxed);
+ GETRANDOM_CHECKED.store(true, Ordering::Relaxed);
available
} else {
- GETRANDOM_AVAILABLE.load(Relaxed)
+ GETRANDOM_AVAILABLE.load(Ordering::Relaxed)
}
}
use prelude::v1::*;
use os;
-use sync::atomic;
+use sync::atomic::{mod, Ordering};
pub use sys::backtrace::write;
// whether the magical environment variable is present to see if it's turned on.
pub fn log_enabled() -> bool {
static ENABLED: atomic::AtomicInt = atomic::ATOMIC_INT_INIT;
- match ENABLED.load(atomic::SeqCst) {
+ match ENABLED.load(Ordering::SeqCst) {
1 => return false,
2 => return true,
_ => {}
Some(..) => 2,
None => 1,
};
- ENABLED.store(val, atomic::SeqCst);
+ ENABLED.store(val, Ordering::SeqCst);
val == 2
}
#[cfg(any(not(target_arch = "arm"), target_os = "ios"))]
#[repr(C)]
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum _Unwind_Action {
_UA_SEARCH_PHASE = 1,
_UA_CLEANUP_PHASE = 2,
use mem;
use os;
use rt;
- use sys_common::thread_info::{mod, NewThread};
+ use sys_common::thread_info::{self, NewThread};
use sys_common;
use thread::Thread;
use intrinsics;
use libc::c_void;
use mem;
-use sync::atomic;
+use sync::atomic::{mod, Ordering};
use sync::{Once, ONCE_INIT};
use rt::libunwind as uw;
pub struct DISPATCHER_CONTEXT;
#[repr(C)]
- #[deriving(Copy)]
+ #[derive(Copy)]
pub enum EXCEPTION_DISPOSITION {
ExceptionContinueExecution,
ExceptionContinueSearch,
// callback. Additionally, CALLBACK_CNT may briefly be higher than
// MAX_CALLBACKS, so we're sure to clamp it as necessary.
let callbacks = {
- let amt = CALLBACK_CNT.load(atomic::SeqCst);
+ let amt = CALLBACK_CNT.load(Ordering::SeqCst);
CALLBACKS[..cmp::min(amt, MAX_CALLBACKS)]
};
for cb in callbacks.iter() {
- match cb.load(atomic::SeqCst) {
+ match cb.load(Ordering::SeqCst) {
0 => {}
n => {
let f: Callback = unsafe { mem::transmute(n) };
/// currently possible to unregister a callback once it has been registered.
#[experimental]
pub unsafe fn register(f: Callback) -> bool {
- match CALLBACK_CNT.fetch_add(1, atomic::SeqCst) {
+ match CALLBACK_CNT.fetch_add(1, Ordering::SeqCst) {
// The invocation code has knowledge of this window where the count has
// been incremented, but the callback has not been stored. We're
// guaranteed that the slot we're storing into is 0.
n if n < MAX_CALLBACKS => {
- let prev = CALLBACKS[n].swap(mem::transmute(f), atomic::SeqCst);
+ let prev = CALLBACKS[n].swap(mem::transmute(f), Ordering::SeqCst);
rtassert!(prev == 0);
true
}
// If we accidentally bumped the count too high, pull it back.
_ => {
- CALLBACK_CNT.store(MAX_CALLBACKS, atomic::SeqCst);
+ CALLBACK_CNT.store(MAX_CALLBACKS, Ordering::SeqCst);
false
}
}
use cmp;
use fmt;
use intrinsics;
-use libc::{mod, uintptr_t};
+use libc::{self, uintptr_t};
use os;
use slice;
use str;
-use sync::atomic;
+use sync::atomic::{mod, Ordering};
/// Dynamically inquire about whether we're running under V.
/// You should usually not use this unless your test definitely
pub fn min_stack() -> uint {
static MIN: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT;
- match MIN.load(atomic::SeqCst) {
+ match MIN.load(Ordering::SeqCst) {
0 => {}
n => return n - 1,
}
let amt = amt.unwrap_or(2 * 1024 * 1024);
// 0 is our sentinel value, so ensure that we'll never see 0 after
// initialization has run
- MIN.store(amt + 1, atomic::SeqCst);
+ MIN.store(amt + 1, Ordering::SeqCst);
return amt;
}
+++ /dev/null
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! Atomic types
-//!
-//! Atomic types provide primitive shared-memory communication between
-//! threads, and are the building blocks of other concurrent
-//! types.
-//!
-//! This module defines atomic versions of a select number of primitive
-//! types, including `AtomicBool`, `AtomicInt`, `AtomicUint`, and `AtomicOption`.
-//! Atomic types present operations that, when used correctly, synchronize
-//! updates between threads.
-//!
-//! Each method takes an `Ordering` which represents the strength of
-//! the memory barrier for that operation. These orderings are the
-//! same as [C++11 atomic orderings][1].
-//!
-//! [1]: http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync
-//!
-//! Atomic variables are safe to share between threads (they implement `Sync`)
-//! but they do not themselves provide the mechanism for sharing. The most
-//! common way to share an atomic variable is to put it into an `Arc` (an
-//! atomically-reference-counted shared pointer).
-//!
-//! Most atomic types may be stored in static variables, initialized using
-//! the provided static initializers like `INIT_ATOMIC_BOOL`. Atomic statics
-//! are often used for lazy global initialization.
-//!
-//!
-//! # Examples
-//!
-//! A simple spinlock:
-//!
-//! ```
-//! use std::sync::Arc;
-//! use std::sync::atomic::{AtomicUint, SeqCst};
-//! use std::thread::Thread;
-//!
-//! fn main() {
-//! let spinlock = Arc::new(AtomicUint::new(1));
-//!
-//! let spinlock_clone = spinlock.clone();
-//! Thread::spawn(move|| {
-//! spinlock_clone.store(0, SeqCst);
-//! }).detach();
-//!
-//! // Wait for the other task to release the lock
-//! while spinlock.load(SeqCst) != 0 {}
-//! }
-//! ```
-//!
-//! Transferring a heap object with `AtomicOption`:
-//!
-//! ```
-//! use std::sync::Arc;
-//! use std::sync::atomic::{AtomicOption, SeqCst};
-//! use std::thread::Thread;
-//!
-//! fn main() {
-//! struct BigObject;
-//!
-//! let shared_big_object = Arc::new(AtomicOption::empty());
-//!
-//! let shared_big_object_clone = shared_big_object.clone();
-//! Thread::spawn(move|| {
-//! let unwrapped_big_object = shared_big_object_clone.take(SeqCst);
-//! if unwrapped_big_object.is_some() {
-//! println!("got a big object from another task");
-//! } else {
-//! println!("other task hasn't sent big object yet");
-//! }
-//! }).detach();
-//!
-//! shared_big_object.swap(box BigObject, SeqCst);
-//! }
-//! ```
-//!
-//! Keep a global count of live tasks:
-//!
-//! ```
-//! use std::sync::atomic::{AtomicUint, SeqCst, ATOMIC_UINT_INIT};
-//!
-//! static GLOBAL_TASK_COUNT: AtomicUint = ATOMIC_UINT_INIT;
-//!
-//! let old_task_count = GLOBAL_TASK_COUNT.fetch_add(1, SeqCst);
-//! println!("live tasks: {}", old_task_count + 1);
-//! ```
-
-#![stable]
-
-use alloc::boxed::Box;
-use core::mem;
-use core::prelude::{Send, Drop, None, Option, Some};
-
-pub use core::atomic::{AtomicBool, AtomicInt, AtomicUint, AtomicPtr};
-pub use core::atomic::{INIT_ATOMIC_BOOL, INIT_ATOMIC_INT, INIT_ATOMIC_UINT};
-pub use core::atomic::{ATOMIC_BOOL_INIT, ATOMIC_INT_INIT, ATOMIC_UINT_INIT};
-pub use core::atomic::fence;
-pub use core::atomic::Ordering::{mod, Relaxed, Release, Acquire, AcqRel, SeqCst};
-
-/// An atomic, nullable unique pointer
-///
-/// This can be used as the concurrency primitive for operations that transfer
-/// owned heap objects across tasks.
-#[unsafe_no_drop_flag]
-#[deprecated = "no longer used; will eventually be replaced by a higher-level\
- concept like MVar"]
-pub struct AtomicOption<T> {
- p: AtomicUint,
-}
-
-#[allow(deprecated)]
-impl<T: Send> AtomicOption<T> {
- /// Create a new `AtomicOption`
- pub fn new(p: Box<T>) -> AtomicOption<T> {
- unsafe { AtomicOption { p: AtomicUint::new(mem::transmute(p)) } }
- }
-
- /// Create a new `AtomicOption` that doesn't contain a value
- pub fn empty() -> AtomicOption<T> { AtomicOption { p: AtomicUint::new(0) } }
-
- /// Store a value, returning the old value
- #[inline]
- pub fn swap(&self, val: Box<T>, order: Ordering) -> Option<Box<T>> {
- let val = unsafe { mem::transmute(val) };
-
- match self.p.swap(val, order) {
- 0 => None,
- n => Some(unsafe { mem::transmute(n) }),
- }
- }
-
- /// Remove the value, leaving the `AtomicOption` empty.
- #[inline]
- pub fn take(&self, order: Ordering) -> Option<Box<T>> {
- unsafe { self.swap(mem::transmute(0u), order) }
- }
-
- /// Replace an empty value with a non-empty value.
- ///
- /// Succeeds if the option is `None` and returns `None` if so. If
- /// the option was already `Some`, returns `Some` of the rejected
- /// value.
- #[inline]
- pub fn fill(&self, val: Box<T>, order: Ordering) -> Option<Box<T>> {
- unsafe {
- let val = mem::transmute(val);
- let expected = mem::transmute(0u);
- let oldval = self.p.compare_and_swap(expected, val, order);
- if oldval == expected {
- None
- } else {
- Some(mem::transmute(val))
- }
- }
- }
-
- /// Returns `true` if the `AtomicOption` is empty.
- ///
- /// Be careful: The caller must have some external method of ensuring the
- /// result does not get invalidated by another task after this returns.
- #[inline]
- pub fn is_empty(&self, order: Ordering) -> bool {
- self.p.load(order) as uint == 0
- }
-}
-
-#[unsafe_destructor]
-impl<T: Send> Drop for AtomicOption<T> {
- fn drop(&mut self) {
- let _ = self.take(SeqCst);
- }
-}
-
-#[cfg(test)]
-mod test {
- use prelude::v1::*;
- use super::*;
-
- #[test]
- fn option_empty() {
- let option: AtomicOption<()> = AtomicOption::empty();
- assert!(option.is_empty(SeqCst));
- }
-
- #[test]
- fn option_swap() {
- let p = AtomicOption::new(box 1i);
- let a = box 2i;
-
- let b = p.swap(a, SeqCst);
-
- assert!(b == Some(box 1));
- assert!(p.take(SeqCst) == Some(box 2));
- }
-
- #[test]
- fn option_take() {
- let p = AtomicOption::new(box 1i);
-
- assert!(p.take(SeqCst) == Some(box 1));
- assert!(p.take(SeqCst) == None);
-
- let p2 = box 2i;
- p.swap(p2, SeqCst);
-
- assert!(p.take(SeqCst) == Some(box 2));
- }
-
- #[test]
- fn option_fill() {
- let p = AtomicOption::new(box 1i);
- assert!(p.fill(box 2i, SeqCst).is_some()); // should fail; shouldn't leak!
- assert!(p.take(SeqCst) == Some(box 1));
-
- assert!(p.fill(box 2i, SeqCst).is_none()); // shouldn't fail
- assert!(p.take(SeqCst) == Some(box 2));
- }
-}
use prelude::v1::*;
-use sync::atomic::{mod, AtomicUint};
-use sync::poison::{mod, LockResult};
+use sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};
+use sync::poison::{self, LockResult};
use sys_common::condvar as sys;
use sys_common::mutex as sys_mutex;
use time::Duration;
#[unstable = "may be merged with Condvar in the future"]
pub const CONDVAR_INIT: StaticCondvar = StaticCondvar {
inner: sys::CONDVAR_INIT,
- mutex: atomic::ATOMIC_UINT_INIT,
+ mutex: ATOMIC_UINT_INIT,
};
impl Condvar {
fn verify(&self, mutex: &sys_mutex::Mutex) {
let addr = mutex as *const _ as uint;
- match self.mutex.compare_and_swap(0, addr, atomic::SeqCst) {
+ match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
// If we got out 0, then we have successfully bound the mutex to
// this cvar.
0 => {}
}
}
- /// Deprecated, use into_inner() instead
- #[deprecated = "renamed to into_inner()"]
- pub fn unwrap(self) -> A { self.into_inner() }
-
pub fn get_ref<'a>(&'a mut self) -> &'a A {
/*!
* Executes the future's closure and then returns a reference
#![experimental]
pub use alloc::arc::{Arc, Weak};
+pub use core::atomic;
pub use self::mutex::{Mutex, MutexGuard, StaticMutex};
pub use self::mutex::MUTEX_INIT;
pub use self::future::Future;
pub use self::task_pool::TaskPool;
-pub mod atomic;
pub mod mpsc;
mod barrier;
unsafe impl Send for Inner {}
unsafe impl Sync for Inner {}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct SignalToken {
inner: Arc<Inner>,
}
/// A `send` operation can only fail if the receiving end of a channel is
/// disconnected, implying that the data could never be received. The error
/// contains the data being sent as a payload so it can be recovered.
-#[deriving(PartialEq, Eq)]
+#[derive(PartialEq, Eq)]
#[stable]
pub struct SendError<T>(pub T);
///
/// The `recv` operation can only fail if the sending half of a channel is
/// disconnected, implying that no further messages will ever be received.
-#[deriving(PartialEq, Eq, Clone, Copy)]
+#[derive(PartialEq, Eq, Clone, Copy)]
#[stable]
pub struct RecvError;
/// This enumeration is the list of the possible reasons that try_recv could not
/// return data when called.
-#[deriving(PartialEq, Clone, Copy)]
+#[derive(PartialEq, Clone, Copy)]
#[stable]
pub enum TryRecvError {
/// This channel is currently empty, but the sender(s) have not yet
/// This enumeration is the list of the possible error outcomes for the
/// `SyncSender::try_send` method.
-#[deriving(PartialEq, Clone)]
+#[derive(PartialEq, Clone)]
#[stable]
pub enum TrySendError<T> {
/// The data could not be sent on the channel because it would require that
use core::mem;
use core::cell::UnsafeCell;
-use sync::atomic::{AtomicPtr, Release, Acquire, AcqRel, Relaxed};
+use sync::atomic::{AtomicPtr, Ordering};
/// A result of the `pop` function.
pub enum PopResult<T> {
pub fn push(&self, t: T) {
unsafe {
let n = Node::new(Some(t));
- let prev = self.head.swap(n, AcqRel);
- (*prev).next.store(n, Release);
+ let prev = self.head.swap(n, Ordering::AcqRel);
+ (*prev).next.store(n, Ordering::Release);
}
}
pub fn pop(&self) -> PopResult<T> {
unsafe {
let tail = *self.tail.get();
- let next = (*tail).next.load(Acquire);
+ let next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
*self.tail.get() = next;
return Data(ret);
}
- if self.head.load(Acquire) == tail {Empty} else {Inconsistent}
+ if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent}
}
}
}
unsafe {
let mut cur = *self.tail.get();
while !cur.is_null() {
- let next = (*cur).next.load(Relaxed);
+ let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = mem::transmute(cur);
cur = next;
}
use core::prelude::*;
use sync::mpsc::Receiver;
-use sync::mpsc::blocking::{mod, SignalToken};
+use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
-use sync::atomic;
+use sync::atomic::{AtomicUint, Ordering};
// Various states you can find a port in.
const EMPTY: uint = 0; // initial state: no data, no blocked reciever
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
- state: atomic::AtomicUint,
+ state: AtomicUint,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
Packet {
data: None,
upgrade: NothingSent,
- state: atomic::AtomicUint::new(EMPTY),
+ state: AtomicUint::new(EMPTY),
}
}
self.data = Some(t);
self.upgrade = SendUsed;
- match self.state.swap(DATA, atomic::SeqCst) {
+ match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
- if self.state.load(atomic::SeqCst) == EMPTY {
+ if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_uint() };
// race with senders to enter the blocking state
- if self.state.compare_and_swap(EMPTY, ptr, atomic::SeqCst) == EMPTY {
+ if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
- debug_assert!(self.state.load(atomic::SeqCst) != EMPTY);
+ debug_assert!(self.state.load(Ordering::SeqCst) != EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_uint(ptr) });
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
- match self.state.load(atomic::SeqCst) {
+ match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
- self.state.compare_and_swap(DATA, EMPTY, atomic::SeqCst);
+ self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
};
self.upgrade = GoUp(up);
- match self.state.swap(DISCONNECTED, atomic::SeqCst) {
+ match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
}
pub fn drop_chan(&mut self) {
- match self.state.swap(DISCONNECTED, atomic::SeqCst) {
+ match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
}
pub fn drop_port(&mut self) {
- match self.state.swap(DISCONNECTED, atomic::SeqCst) {
+ match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
- match self.state.load(atomic::SeqCst) {
+ match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_uint() };
- match self.state.compare_and_swap(EMPTY, ptr, atomic::SeqCst) {
+ match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
- let state = match self.state.load(atomic::SeqCst) {
+ let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
- ptr => self.state.compare_and_swap(ptr, EMPTY, atomic::SeqCst)
+ ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
- assert_eq!(self.state.load(atomic::SeqCst), DISCONNECTED);
+ assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}
use core::uint;
use sync::mpsc::{Receiver, RecvError};
-use sync::mpsc::blocking::{mod, SignalToken};
+use sync::mpsc::blocking::{self, SignalToken};
/// The "receiver set" of the select interface. This structure is used to manage
/// a set of receivers which are being selected over.
struct Packets { cur: *mut Handle<'static, ()> }
#[doc(hidden)]
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
pub enum StartResult {
Installed,
Abort,
use core::cmp;
use core::int;
-use sync::{atomic, Mutex, MutexGuard};
+use sync::atomic::{AtomicUint, AtomicInt, AtomicBool, Ordering};
+use sync::mpsc::blocking::{self, SignalToken};
use sync::mpsc::mpsc_queue as mpsc;
-use sync::mpsc::blocking::{mod, SignalToken};
-use sync::mpsc::select::StartResult;
use sync::mpsc::select::StartResult::*;
+use sync::mpsc::select::StartResult;
+use sync::{Mutex, MutexGuard};
use thread::Thread;
const DISCONNECTED: int = int::MIN;
pub struct Packet<T> {
queue: mpsc::Queue<T>,
- cnt: atomic::AtomicInt, // How many items are on this channel
+ cnt: AtomicInt, // How many items are on this channel
steals: int, // How many times has a port received without blocking?
- to_wake: atomic::AtomicUint, // SignalToken for wake up
+ to_wake: AtomicUint, // SignalToken for wake up
// The number of channels which are currently using this packet.
- channels: atomic::AtomicInt,
+ channels: AtomicInt,
// See the discussion in Port::drop and the channel send methods for what
// these are used for
- port_dropped: atomic::AtomicBool,
- sender_drain: atomic::AtomicInt,
+ port_dropped: AtomicBool,
+ sender_drain: AtomicInt,
// this lock protects various portions of this implementation during
// select()
pub fn new() -> Packet<T> {
let p = Packet {
queue: mpsc::Queue::new(),
- cnt: atomic::AtomicInt::new(0),
+ cnt: AtomicInt::new(0),
steals: 0,
- to_wake: atomic::AtomicUint::new(0),
- channels: atomic::AtomicInt::new(2),
- port_dropped: atomic::AtomicBool::new(false),
- sender_drain: atomic::AtomicInt::new(0),
+ to_wake: AtomicUint::new(0),
+ channels: AtomicInt::new(2),
+ port_dropped: AtomicBool::new(false),
+ sender_drain: AtomicInt::new(0),
select_lock: Mutex::new(()),
};
return p;
token: Option<SignalToken>,
guard: MutexGuard<()>) {
token.map(|token| {
- assert_eq!(self.cnt.load(atomic::SeqCst), 0);
- assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
- self.to_wake.store(unsafe { token.cast_to_uint() }, atomic::SeqCst);
- self.cnt.store(-1, atomic::SeqCst);
+ assert_eq!(self.cnt.load(Ordering::SeqCst), 0);
+ assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
+ self.to_wake.store(unsafe { token.cast_to_uint() }, Ordering::SeqCst);
+ self.cnt.store(-1, Ordering::SeqCst);
// This store is a little sketchy. What's happening here is that
// we're transferring a blocker from a oneshot or stream channel to
pub fn send(&mut self, t: T) -> Result<(), T> {
// See Port::drop for what's going on
- if self.port_dropped.load(atomic::SeqCst) { return Err(t) }
+ if self.port_dropped.load(Ordering::SeqCst) { return Err(t) }
// Note that the multiple sender case is a little trickier
// semantically than the single sender case. The logic for
// preflight check serves as the definitive "this will never be
// received". Once we get beyond this check, we have permanently
// entered the realm of "this may be received"
- if self.cnt.load(atomic::SeqCst) < DISCONNECTED + FUDGE {
+ if self.cnt.load(Ordering::SeqCst) < DISCONNECTED + FUDGE {
return Err(t)
}
self.queue.push(t);
- match self.cnt.fetch_add(1, atomic::SeqCst) {
+ match self.cnt.fetch_add(1, Ordering::SeqCst) {
-1 => {
self.take_to_wake().signal();
}
n if n < DISCONNECTED + FUDGE => {
// see the comment in 'try' for a shared channel for why this
// window of "not disconnected" is ok.
- self.cnt.store(DISCONNECTED, atomic::SeqCst);
+ self.cnt.store(DISCONNECTED, Ordering::SeqCst);
- if self.sender_drain.fetch_add(1, atomic::SeqCst) == 0 {
+ if self.sender_drain.fetch_add(1, Ordering::SeqCst) == 0 {
loop {
// drain the queue, for info on the thread yield see the
// discussion in try_recv
}
// maybe we're done, if we're not the last ones
// here, then we need to go try again.
- if self.sender_drain.fetch_sub(1, atomic::SeqCst) == 1 {
+ if self.sender_drain.fetch_sub(1, Ordering::SeqCst) == 1 {
break
}
}
// Essentially the exact same thing as the stream decrement function.
// Returns true if blocking should proceed.
fn decrement(&mut self, token: SignalToken) -> StartResult {
- assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
+ assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
let ptr = unsafe { token.cast_to_uint() };
- self.to_wake.store(ptr, atomic::SeqCst);
+ self.to_wake.store(ptr, Ordering::SeqCst);
let steals = self.steals;
self.steals = 0;
- match self.cnt.fetch_sub(1 + steals, atomic::SeqCst) {
- DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); }
+ match self.cnt.fetch_sub(1 + steals, Ordering::SeqCst) {
+ DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); }
// If we factor in our steals and notice that the channel has no
// data, we successfully sleep
n => {
}
}
- self.to_wake.store(0, atomic::SeqCst);
+ self.to_wake.store(0, Ordering::SeqCst);
drop(unsafe { SignalToken::cast_from_uint(ptr) });
Abort
}
// might decrement steals.
Some(data) => {
if self.steals > MAX_STEALS {
- match self.cnt.swap(0, atomic::SeqCst) {
+ match self.cnt.swap(0, Ordering::SeqCst) {
DISCONNECTED => {
- self.cnt.store(DISCONNECTED, atomic::SeqCst);
+ self.cnt.store(DISCONNECTED, Ordering::SeqCst);
}
n => {
let m = cmp::min(n, self.steals);
// See the discussion in the stream implementation for why we try
// again.
None => {
- match self.cnt.load(atomic::SeqCst) {
+ match self.cnt.load(Ordering::SeqCst) {
n if n != DISCONNECTED => Err(Empty),
_ => {
match self.queue.pop() {
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&mut self) {
- self.channels.fetch_add(1, atomic::SeqCst);
+ self.channels.fetch_add(1, Ordering::SeqCst);
}
// Decrement the reference count on a channel. This is called whenever a
// Chan is dropped and may end up waking up a receiver. It's the receiver's
// responsibility on the other end to figure out that we've disconnected.
pub fn drop_chan(&mut self) {
- match self.channels.fetch_sub(1, atomic::SeqCst) {
+ match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
n if n > 1 => return,
n => panic!("bad number of channels left {}", n),
}
- match self.cnt.swap(DISCONNECTED, atomic::SeqCst) {
+ match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) {
-1 => { self.take_to_wake().signal(); }
DISCONNECTED => {}
n => { assert!(n >= 0); }
// See the long discussion inside of stream.rs for why the queue is drained,
// and why it is done in this fashion.
pub fn drop_port(&mut self) {
- self.port_dropped.store(true, atomic::SeqCst);
+ self.port_dropped.store(true, Ordering::SeqCst);
let mut steals = self.steals;
while {
- let cnt = self.cnt.compare_and_swap(steals, DISCONNECTED, atomic::SeqCst);
+ let cnt = self.cnt.compare_and_swap(steals, DISCONNECTED, Ordering::SeqCst);
cnt != DISCONNECTED && cnt != steals
} {
// See the discussion in 'try_recv' for why we yield
// Consumes ownership of the 'to_wake' field.
fn take_to_wake(&mut self) -> SignalToken {
- let ptr = self.to_wake.load(atomic::SeqCst);
- self.to_wake.store(0, atomic::SeqCst);
+ let ptr = self.to_wake.load(Ordering::SeqCst);
+ self.to_wake.store(0, Ordering::SeqCst);
assert!(ptr != 0);
unsafe { SignalToken::cast_from_uint(ptr) }
}
// This is different than the stream version because there's no need to peek
// at the queue, we can just look at the local count.
pub fn can_recv(&mut self) -> bool {
- let cnt = self.cnt.load(atomic::SeqCst);
+ let cnt = self.cnt.load(Ordering::SeqCst);
cnt == DISCONNECTED || cnt - self.steals > 0
}
// increment the count on the channel (used for selection)
fn bump(&mut self, amt: int) -> int {
- match self.cnt.fetch_add(amt, atomic::SeqCst) {
+ match self.cnt.fetch_add(amt, Ordering::SeqCst) {
DISCONNECTED => {
- self.cnt.store(DISCONNECTED, atomic::SeqCst);
+ self.cnt.store(DISCONNECTED, Ordering::SeqCst);
DISCONNECTED
}
n => n
// the channel count and figure out what we should do to make it
// positive.
let steals = {
- let cnt = self.cnt.load(atomic::SeqCst);
+ let cnt = self.cnt.load(Ordering::SeqCst);
if cnt < 0 && cnt != DISCONNECTED {-cnt} else {0}
};
let prev = self.bump(steals + 1);
if prev == DISCONNECTED {
- assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
+ assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
true
} else {
let cur = prev + steals + 1;
if prev < 0 {
drop(self.take_to_wake());
} else {
- while self.to_wake.load(atomic::SeqCst) != 0 {
+ while self.to_wake.load(Ordering::SeqCst) != 0 {
Thread::yield_now();
}
}
// disconnection, but also a proper fence before the read of
// `to_wake`, so this assert cannot be removed with also removing
// the `to_wake` assert.
- assert_eq!(self.cnt.load(atomic::SeqCst), DISCONNECTED);
- assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
- assert_eq!(self.channels.load(atomic::SeqCst), 0);
+ assert_eq!(self.cnt.load(Ordering::SeqCst), DISCONNECTED);
+ assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
+ assert_eq!(self.channels.load(Ordering::SeqCst), 0);
}
}
use core::mem;
use core::cell::UnsafeCell;
-use sync::atomic::{AtomicPtr, Relaxed, AtomicUint, Acquire, Release};
+use sync::atomic::{AtomicPtr, AtomicUint, Ordering};
// Node within the linked list queue of messages to send
struct Node<T> {
pub unsafe fn new(bound: uint) -> Queue<T> {
let n1 = Node::new();
let n2 = Node::new();
- (*n1).next.store(n2, Relaxed);
+ (*n1).next.store(n2, Ordering::Relaxed);
Queue {
tail: UnsafeCell::new(n2),
tail_prev: AtomicPtr::new(n1),
let n = self.alloc();
assert!((*n).value.is_none());
(*n).value = Some(t);
- (*n).next.store(0 as *mut Node<T>, Relaxed);
- (**self.head.get()).next.store(n, Release);
+ (*n).next.store(0 as *mut Node<T>, Ordering::Relaxed);
+ (**self.head.get()).next.store(n, Ordering::Release);
*self.head.get() = n;
}
}
// only one subtracting from the cache).
if *self.first.get() != *self.tail_copy.get() {
if self.cache_bound > 0 {
- let b = self.cache_subtractions.load(Relaxed);
- self.cache_subtractions.store(b + 1, Relaxed);
+ let b = self.cache_subtractions.load(Ordering::Relaxed);
+ self.cache_subtractions.store(b + 1, Ordering::Relaxed);
}
let ret = *self.first.get();
- *self.first.get() = (*ret).next.load(Relaxed);
+ *self.first.get() = (*ret).next.load(Ordering::Relaxed);
return ret;
}
// If the above fails, then update our copy of the tail and try
// again.
- *self.tail_copy.get() = self.tail_prev.load(Acquire);
+ *self.tail_copy.get() = self.tail_prev.load(Ordering::Acquire);
if *self.first.get() != *self.tail_copy.get() {
if self.cache_bound > 0 {
- let b = self.cache_subtractions.load(Relaxed);
- self.cache_subtractions.store(b + 1, Relaxed);
+ let b = self.cache_subtractions.load(Ordering::Relaxed);
+ self.cache_subtractions.store(b + 1, Ordering::Relaxed);
}
let ret = *self.first.get();
- *self.first.get() = (*ret).next.load(Relaxed);
+ *self.first.get() = (*ret).next.load(Ordering::Relaxed);
return ret;
}
// If all of that fails, then we have to allocate a new node
// tail's next field and see if we can use it. If we do a pop, then
// the current tail node is a candidate for going into the cache.
let tail = *self.tail.get();
- let next = (*tail).next.load(Acquire);
+ let next = (*tail).next.load(Ordering::Acquire);
if next.is_null() { return None }
assert!((*next).value.is_some());
let ret = (*next).value.take();
*self.tail.get() = next;
if self.cache_bound == 0 {
- self.tail_prev.store(tail, Release);
+ self.tail_prev.store(tail, Ordering::Release);
} else {
// FIXME: this is dubious with overflow.
- let additions = self.cache_additions.load(Relaxed);
- let subtractions = self.cache_subtractions.load(Relaxed);
+ let additions = self.cache_additions.load(Ordering::Relaxed);
+ let subtractions = self.cache_subtractions.load(Ordering::Relaxed);
let size = additions - subtractions;
if size < self.cache_bound {
- self.tail_prev.store(tail, Release);
- self.cache_additions.store(additions + 1, Relaxed);
+ self.tail_prev.store(tail, Ordering::Release);
+ self.cache_additions.store(additions + 1, Ordering::Relaxed);
} else {
- (*self.tail_prev.load(Relaxed)).next.store(next, Relaxed);
+ (*self.tail_prev.load(Ordering::Relaxed))
+ .next.store(next, Ordering::Relaxed);
// We have successfully erased all references to 'tail', so
// now we can safely drop it.
let _: Box<Node<T>> = mem::transmute(tail);
// stripped out.
unsafe {
let tail = *self.tail.get();
- let next = (*tail).next.load(Acquire);
+ let next = (*tail).next.load(Ordering::Acquire);
if next.is_null() { return None }
return (*next).value.as_mut();
}
unsafe {
let mut cur = *self.first.get();
while !cur.is_null() {
- let next = (*cur).next.load(Relaxed);
+ let next = (*cur).next.load(Ordering::Relaxed);
let _n: Box<Node<T>> = mem::transmute(cur);
cur = next;
}
use core::int;
use thread::Thread;
-use sync::mpsc::blocking::{mod, SignalToken};
-use sync::mpsc::spsc_queue as spsc;
+use sync::atomic::{AtomicInt, AtomicUint, Ordering, AtomicBool};
use sync::mpsc::Receiver;
-use sync::atomic;
+use sync::mpsc::blocking::{self, SignalToken};
+use sync::mpsc::spsc_queue as spsc;
const DISCONNECTED: int = int::MIN;
#[cfg(test)]
pub struct Packet<T> {
queue: spsc::Queue<Message<T>>, // internal queue for all message
- cnt: atomic::AtomicInt, // How many items are on this channel
+ cnt: AtomicInt, // How many items are on this channel
steals: int, // How many times has a port received without blocking?
- to_wake: atomic::AtomicUint, // SignalToken for the blocked thread to wake up
+ to_wake: AtomicUint, // SignalToken for the blocked thread to wake up
- port_dropped: atomic::AtomicBool, // flag if the channel has been destroyed.
+ port_dropped: AtomicBool, // flag if the channel has been destroyed.
}
pub enum Failure<T> {
Packet {
queue: unsafe { spsc::Queue::new(128) },
- cnt: atomic::AtomicInt::new(0),
+ cnt: AtomicInt::new(0),
steals: 0,
- to_wake: atomic::AtomicUint::new(0),
+ to_wake: AtomicUint::new(0),
- port_dropped: atomic::AtomicBool::new(false),
+ port_dropped: AtomicBool::new(false),
}
}
// If the other port has deterministically gone away, then definitely
// must return the data back up the stack. Otherwise, the data is
// considered as being sent.
- if self.port_dropped.load(atomic::SeqCst) { return Err(t) }
+ if self.port_dropped.load(Ordering::SeqCst) { return Err(t) }
match self.do_send(Data(t)) {
UpSuccess | UpDisconnected => {},
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
// If the port has gone away, then there's no need to proceed any
// further.
- if self.port_dropped.load(atomic::SeqCst) { return UpDisconnected }
+ if self.port_dropped.load(Ordering::SeqCst) { return UpDisconnected }
self.do_send(GoUp(up))
}
fn do_send(&mut self, t: Message<T>) -> UpgradeResult {
self.queue.push(t);
- match self.cnt.fetch_add(1, atomic::SeqCst) {
+ match self.cnt.fetch_add(1, Ordering::SeqCst) {
// As described in the mod's doc comment, -1 == wakeup
-1 => UpWoke(self.take_to_wake()),
// As as described before, SPSC queues must be >= -2
// will never remove this data. We can only have at most one item to
// drain (the port drains the rest).
DISCONNECTED => {
- self.cnt.store(DISCONNECTED, atomic::SeqCst);
+ self.cnt.store(DISCONNECTED, Ordering::SeqCst);
let first = self.queue.pop();
let second = self.queue.pop();
assert!(second.is_none());
// Consumes ownership of the 'to_wake' field.
fn take_to_wake(&mut self) -> SignalToken {
- let ptr = self.to_wake.load(atomic::SeqCst);
- self.to_wake.store(0, atomic::SeqCst);
+ let ptr = self.to_wake.load(Ordering::SeqCst);
+ self.to_wake.store(0, Ordering::SeqCst);
assert!(ptr != 0);
unsafe { SignalToken::cast_from_uint(ptr) }
}
// back if it shouldn't sleep. Note that this is the location where we take
// steals into account.
fn decrement(&mut self, token: SignalToken) -> Result<(), SignalToken> {
- assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
+ assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
let ptr = unsafe { token.cast_to_uint() };
- self.to_wake.store(ptr, atomic::SeqCst);
+ self.to_wake.store(ptr, Ordering::SeqCst);
let steals = self.steals;
self.steals = 0;
- match self.cnt.fetch_sub(1 + steals, atomic::SeqCst) {
- DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); }
+ match self.cnt.fetch_sub(1 + steals, Ordering::SeqCst) {
+ DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); }
// If we factor in our steals and notice that the channel has no
// data, we successfully sleep
n => {
}
}
- self.to_wake.store(0, atomic::SeqCst);
+ self.to_wake.store(0, Ordering::SeqCst);
Err(unsafe { SignalToken::cast_from_uint(ptr) })
}
// adding back in whatever we couldn't factor into steals.
Some(data) => {
if self.steals > MAX_STEALS {
- match self.cnt.swap(0, atomic::SeqCst) {
+ match self.cnt.swap(0, Ordering::SeqCst) {
DISCONNECTED => {
- self.cnt.store(DISCONNECTED, atomic::SeqCst);
+ self.cnt.store(DISCONNECTED, Ordering::SeqCst);
}
n => {
let m = cmp::min(n, self.steals);
}
None => {
- match self.cnt.load(atomic::SeqCst) {
+ match self.cnt.load(Ordering::SeqCst) {
n if n != DISCONNECTED => Err(Empty),
// This is a little bit of a tricky case. We failed to pop
pub fn drop_chan(&mut self) {
// Dropping a channel is pretty simple, we just flag it as disconnected
// and then wakeup a blocker if there is one.
- match self.cnt.swap(DISCONNECTED, atomic::SeqCst) {
+ match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) {
-1 => { self.take_to_wake().signal(); }
DISCONNECTED => {}
n => { assert!(n >= 0); }
// sends are gated on this flag, so we're immediately guaranteed that
// there are a bounded number of active sends that we'll have to deal
// with.
- self.port_dropped.store(true, atomic::SeqCst);
+ self.port_dropped.store(true, Ordering::SeqCst);
// Now that we're guaranteed to deal with a bounded number of senders,
// we need to drain the queue. This draining process happens atomically
let mut steals = self.steals;
while {
let cnt = self.cnt.compare_and_swap(
- steals, DISCONNECTED, atomic::SeqCst);
+ steals, DISCONNECTED, Ordering::SeqCst);
cnt != DISCONNECTED && cnt != steals
} {
loop {
// increment the count on the channel (used for selection)
fn bump(&mut self, amt: int) -> int {
- match self.cnt.fetch_add(amt, atomic::SeqCst) {
+ match self.cnt.fetch_add(amt, Ordering::SeqCst) {
DISCONNECTED => {
- self.cnt.store(DISCONNECTED, atomic::SeqCst);
+ self.cnt.store(DISCONNECTED, Ordering::SeqCst);
DISCONNECTED
}
n => n
// of time until the data is actually sent.
if was_upgrade {
assert_eq!(self.steals, 0);
- assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
+ assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
return Ok(true)
}
// If we were previously disconnected, then we know for sure that there
// is no task in to_wake, so just keep going
let has_data = if prev == DISCONNECTED {
- assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
+ assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
true // there is data, that data is that we're disconnected
} else {
let cur = prev + steals + 1;
if prev < 0 {
drop(self.take_to_wake());
} else {
- while self.to_wake.load(atomic::SeqCst) != 0 {
+ while self.to_wake.load(Ordering::SeqCst) != 0 {
Thread::yield_now();
}
}
// disconnection, but also a proper fence before the read of
// `to_wake`, so this assert cannot be removed with also removing
// the `to_wake` assert.
- assert_eq!(self.cnt.load(atomic::SeqCst), DISCONNECTED);
- assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
+ assert_eq!(self.cnt.load(Ordering::SeqCst), DISCONNECTED);
+ assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
}
}
use vec::Vec;
use core::mem;
-use sync::{atomic, Mutex, MutexGuard};
-use sync::mpsc::blocking::{mod, WaitToken, SignalToken};
-use sync::mpsc::select::StartResult::{mod, Installed, Abort};
+use sync::atomic::{Ordering, AtomicUint};
+use sync::mpsc::blocking::{self, WaitToken, SignalToken};
+use sync::mpsc::select::StartResult::{self, Installed, Abort};
+use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
- channels: atomic::AtomicUint,
+ channels: AtomicUint,
lock: Mutex<State<T>>,
}
size: uint,
}
-#[deriving(Show)]
+#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
- channels: atomic::AtomicUint::new(1),
+ channels: AtomicUint::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
- self.channels.fetch_add(1, atomic::SeqCst);
+ self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
- match self.channels.fetch_sub(1, atomic::SeqCst) {
+ match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
- assert_eq!(self.channels.load(atomic::SeqCst), 0);
+ assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
use cell::UnsafeCell;
use kinds::marker;
use ops::{Deref, DerefMut};
-use sync::poison::{mod, TryLockError, TryLockResult, LockResult};
+use sync::poison::{self, TryLockError, TryLockResult, LockResult};
use sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
use kinds::Sync;
use mem::drop;
use ops::FnOnce;
-use sync::atomic;
+use sync::atomic::{AtomicInt, Ordering, ATOMIC_INT_INIT};
use sync::{StaticMutex, MUTEX_INIT};
/// A synchronization primitive which can be used to run a one-time global
#[stable]
pub struct Once {
mutex: StaticMutex,
- cnt: atomic::AtomicInt,
- lock_cnt: atomic::AtomicInt,
+ cnt: AtomicInt,
+ lock_cnt: AtomicInt,
}
unsafe impl Sync for Once {}
#[stable]
pub const ONCE_INIT: Once = Once {
mutex: MUTEX_INIT,
- cnt: atomic::ATOMIC_INT_INIT,
- lock_cnt: atomic::ATOMIC_INT_INIT,
+ cnt: ATOMIC_INT_INIT,
+ lock_cnt: ATOMIC_INT_INIT,
};
impl Once {
#[stable]
pub fn call_once<F>(&'static self, f: F) where F: FnOnce() {
// Optimize common path: load is much cheaper than fetch_add.
- if self.cnt.load(atomic::SeqCst) < 0 {
+ if self.cnt.load(Ordering::SeqCst) < 0 {
return
}
// calling `call_once` will return immediately before the initialization
// has completed.
- let prev = self.cnt.fetch_add(1, atomic::SeqCst);
+ let prev = self.cnt.fetch_add(1, Ordering::SeqCst);
if prev < 0 {
// Make sure we never overflow, we'll never have int::MIN
// simultaneous calls to `call_once` to make this value go back to 0
- self.cnt.store(int::MIN, atomic::SeqCst);
+ self.cnt.store(int::MIN, Ordering::SeqCst);
return
}
// otherwise we run the job and record how many people will try to grab
// this lock
let guard = self.mutex.lock();
- if self.cnt.load(atomic::SeqCst) > 0 {
+ if self.cnt.load(Ordering::SeqCst) > 0 {
f();
- let prev = self.cnt.swap(int::MIN, atomic::SeqCst);
- self.lock_cnt.store(prev, atomic::SeqCst);
+ let prev = self.cnt.swap(int::MIN, Ordering::SeqCst);
+ self.lock_cnt.store(prev, Ordering::SeqCst);
}
drop(guard);
// Last one out cleans up after everyone else, no leaks!
- if self.lock_cnt.fetch_add(-1, atomic::SeqCst) == 1 {
+ if self.lock_cnt.fetch_add(-1, Ordering::SeqCst) == 1 {
unsafe { self.mutex.destroy() }
}
}
use cell::UnsafeCell;
use kinds::marker;
use ops::{Deref, DerefMut};
-use sync::poison::{mod, LockResult, TryLockError, TryLockResult};
+use sync::poison::{self, LockResult, TryLockError, TryLockResult};
use sys_common::rwlock as sys;
/// A reader-writer lock
mod tests {
use prelude::v1::*;
- use rand::{mod, Rng};
+ use rand::{self, Rng};
use sync::mpsc::channel;
use thread::Thread;
use sync::{Arc, RWLock, StaticRWLock, RWLOCK_INIT};
// except according to those terms.
use time::Duration;
-use sys_common::mutex::{mod, Mutex};
+use sys_common::mutex::{self, Mutex};
use sys::condvar as imp;
/// An OS-based condition variable.
#![allow(missing_docs)]
#![allow(dead_code)]
-use io::{mod, IoError, IoResult};
+use io::{self, IoError, IoResult};
use prelude::v1::*;
use sys::{last_error, retry};
use c_str::CString;
use io::net::addrinfo;
use io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr};
use io::{IoResult, IoError};
-use libc::{mod, c_char, c_int};
+use libc::{self, c_char, c_int};
use c_str::CString;
use mem;
use num::Int;
-use ptr::{mod, null, null_mut};
-use sys::{mod, retry, c, sock_t, last_error, last_net_error, last_gai_error, close_sock,
+use ptr::{self, null, null_mut};
+use sys::{self, retry, c, sock_t, last_error, last_net_error, last_gai_error, close_sock,
wrlen, msglen_t, os, wouldblock, set_nonblocking, timer, ms_to_timeval,
decode_error_detailed};
use sync::{Arc, Mutex, MutexGuard};
-use sys_common::{mod, keep_going, short_write, timeout};
+use sys_common::{self, keep_going, short_write, timeout};
use cmp;
use io;
// FIXME: move uses of Arc and deadline tracking to std::io
-#[deriving(Show)]
+#[derive(Show)]
pub enum SocketStatus {
Readable,
Writable,
use prelude::v1::*;
-use sync::atomic::{mod, AtomicUint};
+use sync::atomic::{self, AtomicUint, Ordering};
use sync::{Mutex, Once, ONCE_INIT};
use sys::thread_local as imp;
/// Note that this does *not* run the user-provided destructor if one was
/// specified at definition time. Doing so must be done manually.
pub unsafe fn destroy(&self) {
- match self.inner.key.swap(0, atomic::SeqCst) {
+ match self.inner.key.swap(0, Ordering::SeqCst) {
0 => {}
n => { imp::destroy(n as imp::Key) }
}
#[inline]
unsafe fn key(&self) -> imp::Key {
- match self.inner.key.load(atomic::Relaxed) {
+ match self.inner.key.load(Ordering::Relaxed) {
0 => self.lazy_init() as imp::Key,
n => n as imp::Key
}
key2
};
assert!(key != 0);
- match self.inner.key.compare_and_swap(0, key as uint, atomic::SeqCst) {
+ match self.inner.key.compare_and_swap(0, key as uint, Ordering::SeqCst) {
// The CAS succeeded, so we've created the actual key
0 => key as uint,
// If someone beat us to the punch, use their key instead
use io::{IoResult, Writer};
use libc;
use mem;
-use option::Option::{mod, Some, None};
+use option::Option::{self, Some, None};
use result::Result::{Ok, Err};
use sync::{StaticMutex, MUTEX_INIT};
use cell::UnsafeCell;
use libc;
-use sys::mutex::{mod, Mutex};
+use sys::mutex::{self, Mutex};
use sys::sync as ffi;
use time::Duration;
use io::{IoResult, FileStat, SeekStyle};
use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
use io;
-use libc::{mod, c_int, c_void};
+use libc::{self, c_int, c_void};
use mem;
use sys::retry;
use sys_common::{keep_going, eof, mkerr_libc};
use num;
use num::{Int, SignedInt};
use prelude::v1::*;
-use io::{mod, IoResult, IoError};
+use io::{self, IoResult, IoError};
use sys_common::mkerr_libc;
macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
use error::{FromError, Error};
use fmt;
use io::{IoError, IoResult};
-use libc::{mod, c_int, c_char, c_void};
+use libc::{self, c_int, c_char, c_void};
use os;
use path::{BytesContainer};
use ptr;
-use sync::atomic::{AtomicInt, SeqCst};
use sys::fs::FileDesc;
use os::TMPBUF_SZ;
use libc;
use c_str::CString;
use mem;
-use sync::{atomic, Arc, Mutex};
-use io::{mod, IoResult, IoError};
+use sync::{Arc, Mutex};
+use sync::atomic::{AtomicBool, Ordering};
+use io::{self, IoResult, IoError};
-use sys::{mod, timer, retry, c, set_nonblocking, wouldblock};
+use sys::{self, timer, retry, c, set_nonblocking, wouldblock};
use sys::fs::{fd_t, FileDesc};
use sys_common::net::*;
use sys_common::net::SocketStatus::*;
listener: self,
reader: reader,
writer: writer,
- closed: atomic::AtomicBool::new(false),
+ closed: AtomicBool::new(false),
}),
deadline: 0,
})
listener: UnixListener,
reader: FileDesc,
writer: FileDesc,
- closed: atomic::AtomicBool,
+ closed: AtomicBool,
}
impl UnixAcceptor {
pub fn accept(&mut self) -> IoResult<UnixStream> {
let deadline = if self.deadline == 0 {None} else {Some(self.deadline)};
- while !self.inner.closed.load(atomic::SeqCst) {
+ while !self.inner.closed.load(Ordering::SeqCst) {
unsafe {
let mut storage: libc::sockaddr_storage = mem::zeroed();
let storagep = &mut storage as *mut libc::sockaddr_storage;
}
pub fn close_accept(&mut self) -> IoResult<()> {
- self.inner.closed.store(true, atomic::SeqCst);
+ self.inner.closed.store(true, Ordering::SeqCst);
let fd = FileDesc::new(self.inner.writer.fd(), false);
match fd.write(&[0]) {
Ok(..) => Ok(()),
use collections;
use hash::Hash;
use io::process::{ProcessExit, ExitStatus, ExitSignal};
-use io::{mod, IoResult, IoError, EndOfFile};
-use libc::{mod, pid_t, c_void, c_int};
+use io::{self, IoResult, IoError, EndOfFile};
+use libc::{self, pid_t, c_void, c_int};
use mem;
use os;
use path::BytesContainer;
use ptr;
use sync::mpsc::{channel, Sender, Receiver};
use sys::fs::FileDesc;
-use sys::{mod, retry, c, wouldblock, set_nonblocking, ms_to_timeval};
+use sys::{self, retry, c, wouldblock, set_nonblocking, ms_to_timeval};
use sys_common::helper_thread::Helper;
use sys_common::{AsInner, mkerr_libc, timeout};
use mem;
use ptr;
use super::{last_error, last_net_error, retry, sock_t};
-use sync::{Arc, atomic};
+use sync::Arc;
+use sync::atomic::{AtomicBool, Ordering};
use sys::fs::FileDesc;
use sys::{set_nonblocking, wouldblock};
use sys;
listener: self,
reader: reader,
writer: writer,
- closed: atomic::AtomicBool::new(false),
+ closed: AtomicBool::new(false),
}),
deadline: 0,
})
listener: TcpListener,
reader: FileDesc,
writer: FileDesc,
- closed: atomic::AtomicBool,
+ closed: AtomicBool,
}
unsafe impl Sync for AcceptorInner {}
// self-pipe is never written to unless close_accept() is called.
let deadline = if self.deadline == 0 {None} else {Some(self.deadline)};
- while !self.inner.closed.load(atomic::SeqCst) {
+ while !self.inner.closed.load(Ordering::SeqCst) {
match retry(|| unsafe {
libc::accept(self.fd(), ptr::null_mut(), ptr::null_mut())
}) {
}
pub fn close_accept(&mut self) -> IoResult<()> {
- self.inner.closed.store(true, atomic::SeqCst);
+ self.inner.closed.store(true, Ordering::SeqCst);
let fd = FileDesc::new(self.inner.writer.fd(), false);
match fd.write(&[0]) {
Ok(..) => Ok(()),
use mem;
use os;
use ptr;
-use sync::atomic;
+use sync::atomic::{mod, Ordering};
use sync::mpsc::{channel, Sender, Receiver, TryRecvError};
use sys::c;
use sys::fs::FileDesc;
HELPER.boot(|| {}, helper);
static ID: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT;
- let id = ID.fetch_add(1, atomic::Relaxed);
+ let id = ID.fetch_add(1, Ordering::Relaxed);
Ok(Timer {
id: id,
inner: Some(box Inner {
use prelude::v1::*;
use sys::fs::FileDesc;
-use libc::{mod, c_int};
-use io::{mod, IoResult, IoError};
+use libc::{self, c_int};
+use io::{self, IoResult, IoError};
use sys_common;
pub struct TTY {
// except according to those terms.
use cell::UnsafeCell;
-use libc::{mod, DWORD};
+use libc::{self, DWORD};
use os;
-use sys::mutex::{mod, Mutex};
+use sys::mutex::{self, Mutex};
use sys::sync as ffi;
use time::Duration;
//! Blocking Windows-based file I/O
use alloc::arc::Arc;
-use libc::{mod, c_int};
+use libc::{self, c_int};
use c_str::CString;
use mem;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use libc::{mod, BOOL, LPCSTR, HANDLE, LPSECURITY_ATTRIBUTES, CloseHandle};
+use libc::{self, BOOL, LPCSTR, HANDLE, LPSECURITY_ATTRIBUTES, CloseHandle};
use ptr;
pub type signal = HANDLE;
use num;
use mem;
-use io::{mod, IoResult, IoError};
+use io::{self, IoResult, IoError};
use sync::{Once, ONCE_INIT};
macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
use prelude::v1::*;
-use sync::atomic;
-use alloc::{mod, heap};
+use sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering};
+use alloc::{self, heap};
use libc::DWORD;
use sys::sync as ffi;
const SPIN_COUNT: DWORD = 4000;
-pub struct Mutex { inner: atomic::AtomicUint }
+pub struct Mutex { inner: AtomicUint }
-pub const MUTEX_INIT: Mutex = Mutex { inner: atomic::ATOMIC_UINT_INIT };
+pub const MUTEX_INIT: Mutex = Mutex { inner: ATOMIC_UINT_INIT };
unsafe impl Sync for Mutex {}
impl Mutex {
#[inline]
pub unsafe fn new() -> Mutex {
- Mutex { inner: atomic::AtomicUint::new(init_lock() as uint) }
+ Mutex { inner: AtomicUint::new(init_lock() as uint) }
}
#[inline]
pub unsafe fn lock(&self) {
ffi::LeaveCriticalSection(self.get())
}
pub unsafe fn destroy(&self) {
- let lock = self.inner.swap(0, atomic::SeqCst);
+ let lock = self.inner.swap(0, Ordering::SeqCst);
if lock != 0 { free_lock(lock as ffi::LPCRITICAL_SECTION) }
}
unsafe fn get(&self) -> ffi::LPCRITICAL_SECTION {
- match self.inner.load(atomic::SeqCst) {
+ match self.inner.load(Ordering::SeqCst) {
0 => {}
n => return n as ffi::LPCRITICAL_SECTION
}
let lock = init_lock();
- match self.inner.compare_and_swap(0, lock as uint, atomic::SeqCst) {
+ match self.inner.compare_and_swap(0, lock as uint, Ordering::SeqCst) {
0 => return lock as ffi::LPCRITICAL_SECTION,
_ => {}
}
free_lock(lock);
- return self.inner.load(atomic::SeqCst) as ffi::LPCRITICAL_SECTION;
+ return self.inner.load(Ordering::SeqCst) as ffi::LPCRITICAL_SECTION;
}
}
use c_str::CString;
use mem;
use ptr;
-use sync::{atomic, Arc, Mutex};
-use io::{mod, IoError, IoResult};
+use sync::{Arc, Mutex};
+use sync::atomic::{AtomicBool, Ordering};
+use io::{self, IoError, IoResult};
-use sys_common::{mod, eof};
+use sys_common::{self, eof};
use super::{c, os, timer, to_utf16, decode_error_detailed};
struct Inner {
handle: libc::HANDLE,
lock: Mutex<()>,
- read_closed: atomic::AtomicBool,
- write_closed: atomic::AtomicBool,
+ read_closed: AtomicBool,
+ write_closed: AtomicBool,
}
impl Inner {
Inner {
handle: handle,
lock: Mutex::new(()),
- read_closed: atomic::AtomicBool::new(false),
- write_closed: atomic::AtomicBool::new(false),
+ read_closed: AtomicBool::new(false),
+ write_closed: AtomicBool::new(false),
}
}
}
pub fn handle(&self) -> libc::HANDLE { self.inner.handle }
fn read_closed(&self) -> bool {
- self.inner.read_closed.load(atomic::SeqCst)
+ self.inner.read_closed.load(Ordering::SeqCst)
}
fn write_closed(&self) -> bool {
- self.inner.write_closed.load(atomic::SeqCst)
+ self.inner.write_closed.load(Ordering::SeqCst)
}
fn cancel_io(&self) -> IoResult<()> {
// and 2 with a lock with respect to close_read(), we're guaranteed that
// no thread will erroneously sit in a read forever.
let _guard = unsafe { self.inner.lock.lock() };
- self.inner.read_closed.store(true, atomic::SeqCst);
+ self.inner.read_closed.store(true, Ordering::SeqCst);
self.cancel_io()
}
pub fn close_write(&mut self) -> IoResult<()> {
// see comments in close_read() for why this lock is necessary
let _guard = unsafe { self.inner.lock.lock() };
- self.inner.write_closed.store(true, atomic::SeqCst);
+ self.inner.write_closed.store(true, Ordering::SeqCst);
self.cancel_io()
}
deadline: 0,
inner: Arc::new(AcceptorState {
abort: try!(Event::new(true, false)),
- closed: atomic::AtomicBool::new(false),
+ closed: AtomicBool::new(false),
}),
})
}
struct AcceptorState {
abort: Event,
- closed: atomic::AtomicBool,
+ closed: AtomicBool,
}
unsafe impl Send for AcceptorState {}
// If we've had an artificial call to close_accept, be sure to never
// proceed in accepting new clients in the future
- if self.inner.closed.load(atomic::SeqCst) { return Err(eof()) }
+ if self.inner.closed.load(Ordering::SeqCst) { return Err(eof()) }
let name = try!(to_utf16(self.listener.name.as_str()));
}
pub fn close_accept(&mut self) -> IoResult<()> {
- self.inner.closed.store(true, atomic::SeqCst);
+ self.inner.closed.store(true, Ordering::SeqCst);
let ret = unsafe {
c::SetEvent(self.inner.abort.handle())
};
use io::{IoResult, IoError};
use sys::fs;
-use sys::{mod, retry, c, wouldblock, set_nonblocking, ms_to_timeval, timer};
+use sys::{self, retry, c, wouldblock, set_nonblocking, ms_to_timeval, timer};
use sys::fs::FileDesc;
use sys_common::helper_thread::Helper;
use sys_common::{AsInner, mkerr_libc, timeout};
use ptr;
use prelude::v1::*;
use super::{last_error, last_net_error, retry, sock_t};
-use sync::{Arc, atomic};
+use sync::Arc;
+use sync::atomic::{AtomicBool, Ordering};
use sys::fs::FileDesc;
-use sys::{mod, c, set_nonblocking, wouldblock, timer};
-use sys_common::{mod, timeout, eof, net};
+use sys::{self, c, set_nonblocking, wouldblock, timer};
+use sys_common::{self, timeout, eof, net};
pub use sys_common::net::TcpStream;
listener: self,
abort: try!(Event::new()),
accept: accept,
- closed: atomic::AtomicBool::new(false),
+ closed: AtomicBool::new(false),
}),
deadline: 0,
})
listener: TcpListener,
abort: Event,
accept: Event,
- closed: atomic::AtomicBool,
+ closed: AtomicBool,
}
unsafe impl Send for AcceptorInner {}
// stolen, so we do all of this in a loop as well.
let events = [self.inner.abort.handle(), self.inner.accept.handle()];
- while !self.inner.closed.load(atomic::SeqCst) {
+ while !self.inner.closed.load(Ordering::SeqCst) {
let ms = if self.deadline == 0 {
c::WSA_INFINITE as u64
} else {
}
pub fn close_accept(&mut self) -> IoResult<()> {
- self.inner.closed.store(true, atomic::SeqCst);
+ self.inner.closed.store(true, Ordering::SeqCst);
let ret = unsafe { c::WSASetEvent(self.inner.abort.handle()) };
if ret == libc::TRUE {
Ok(())
use prelude::v1::*;
-use io::{mod, IoError, IoResult, MemReader};
+use io::{self, IoError, IoResult, MemReader};
use iter::repeat;
use libc::types::os::arch::extra::LPCVOID;
use libc::{c_int, HANDLE, LPDWORD, DWORD, LPVOID};
+++ /dev/null
-// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! Deprecated in favor of `thread`.
-
-#![deprecated = "use std::thread instead"]
-
-use any::Any;
-use boxed::Box;
-use thread;
-use kinds::Send;
-use result::Result;
-use ops::FnOnce;
-
-/// Deprecate: use `std::thread::Builder` instead.
-#[deprecated = "use std::thread::Builder instead"]
-pub type TaskBuilder = thread::Builder;
-
-/// Deprecated: use `std::thread::Thread::spawn` and `detach` instead.
-#[deprecated = "use std::thread::Thread::spawn and detach instead"]
-pub fn spawn<F>(f: F) where F: FnOnce(), F: Send {
- thread::Thread::spawn(f).detach();
-}
-
-/// Deprecated: use `std::thread::Thread::spawn` and `join` instead.
-#[deprecated = "use std::thread::Thread::spawn and join instead"]
-pub fn try<T, F>(f: F) -> Result<T, Box<Any + Send>> where
- T: Send, F: FnOnce() -> T, F: Send
-{
- thread::Thread::spawn(f).join()
-}
-
-/// Deprecated: use `std::thread::Thread::yield_now instead`.
-#[deprecated = "use std::thread::Thread::yield_now instead"]
-pub fn deschedule() {
- thread::Thread::yield_now()
-}
//! * It can be implemented highly efficiently on many platforms.
use any::Any;
-use borrow::IntoCow;
use boxed::Box;
use cell::UnsafeCell;
use clone::Clone;
use kinds::{Send, Sync};
use ops::{Drop, FnOnce};
-use option::Option::{mod, Some, None};
+use option::Option::{self, Some, None};
use result::Result::{Err, Ok};
use sync::{Mutex, Condvar, Arc};
use str::Str;
use string::String;
-use rt::{mod, unwind};
+use rt::{self, unwind};
use io::{Writer, stdio};
use thunk::Thunk;
self
}
- /// Deprecated: use `name` instead
- #[deprecated = "use name instead"]
- pub fn named<T: IntoCow<'static, String, str>>(self, name: T) -> Builder {
- self.name(name.into_cow().into_owned())
- }
-
/// Set the size of the stack for the new thread.
pub fn stack_size(mut self, size: uint) -> Builder {
self.stack_size = Some(size);
unsafe impl Sync for Inner {}
-#[deriving(Clone)]
+#[derive(Clone)]
/// A handle to a thread.
pub struct Thread {
inner: Arc<Inner>,
mod test {
use prelude::v1::*;
- use any::{Any, AnyRefExt};
+ use any::Any;
use sync::mpsc::{channel, Sender};
use boxed::BoxAny;
use result;
/// Indicator of the state of a thread local storage key.
#[unstable = "state querying was recently added"]
-#[deriving(Eq, PartialEq, Copy)]
+#[derive(Eq, PartialEq, Copy)]
pub enum State {
/// All keys are in this state whenever a thread starts. Keys will
/// transition to the `Valid` state once the first call to `with` happens
/// ISO 8601 time duration with nanosecond precision.
/// This also allows for the negative duration; see individual methods for details.
-#[deriving(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Duration {
secs: i64,
nanos: i32, // Always 0 <= nanos < NANOS_PER_SEC
//!
//! # Examples
//!
-//! Using fields:
-//!
-//! ```
-//! #[allow(deprecated)]
-//! # fn main() {
-//! let pair = ("pi", 3.14f64);
-//! assert_eq!(pair.0, "pi");
-//! assert_eq!(pair.1, 3.14f64);
-//! # }
-//! ```
-//!
//! Using traits implemented for tuples:
//!
//! ```
use std::fmt;
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Os {
OsWindows,
OsMacos,
OsDragonfly,
}
-#[deriving(PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Clone, Copy)]
+#[derive(PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Clone, Copy)]
pub enum Abi {
// NB: This ordering MUST match the AbiDatas array below.
// (This is ensured by the test indices_are_correct().)
}
#[allow(non_camel_case_types)]
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum Architecture {
X86,
X86_64,
Mipsel
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct AbiData {
abi: Abi,
name: &'static str,
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum AbiArchitecture {
/// Not a real ABI (e.g., intrinsic)
RustArch,
/// table) and a SyntaxContext to track renaming and
/// macro expansion per Flatt et al., "Macros
/// That Work Together"
-#[deriving(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
+#[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)]
pub struct Ident {
pub name: Name,
pub ctxt: SyntaxContext
/// A name is a part of an identifier, representing a string or gensym. It's
/// the result of interning.
-#[deriving(Eq, Ord, PartialEq, PartialOrd, Hash,
+#[derive(Eq, Ord, PartialEq, PartialOrd, Hash,
RustcEncodable, RustcDecodable, Clone, Copy)]
pub struct Name(pub u32);
/// Function name (not all functions have names)
pub type FnIdent = Option<Ident>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,
Show, Copy)]
pub struct Lifetime {
pub id: NodeId,
pub name: Name
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct LifetimeDef {
pub lifetime: Lifetime,
pub bounds: Vec<Lifetime>
/// A "Path" is essentially Rust's notion of a name; for instance:
/// std::cmp::PartialEq . It's represented as a sequence of identifiers,
/// along with a bunch of supporting information.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Path {
pub span: Span,
/// A `::foo` path, is relative to the crate root rather than current
/// A segment of a path: an identifier, an optional lifetime, and a set of
/// types.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct PathSegment {
/// The identifier portion of this path segment.
pub identifier: Ident,
pub parameters: PathParameters,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum PathParameters {
AngleBracketedParameters(AngleBracketedParameterData),
ParenthesizedParameters(ParenthesizedParameterData),
}
/// A path like `Foo<'a, T>`
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct AngleBracketedParameterData {
/// The lifetime parameters for this path segment.
pub lifetimes: Vec<Lifetime>,
}
/// A path like `Foo(A,B) -> C`
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct ParenthesizedParameterData {
/// `(A,B)`
pub inputs: Vec<P<Ty>>,
pub type NodeId = u32;
-#[deriving(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
+#[derive(Clone, Eq, Ord, PartialOrd, PartialEq, RustcEncodable,
RustcDecodable, Hash, Show, Copy)]
pub struct DefId {
pub krate: CrateNum,
/// typeck::collect::compute_bounds matches these against
/// the "special" built-in traits (see middle::lang_items) and
/// detects Copy, Send and Sync.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum TyParamBound {
TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
RegionTyParamBound(Lifetime)
/// A modifier on a bound, currently this is only used for `?Sized`, where the
/// modifier is `Maybe`. Negative bounds should also be handled here.
-#[deriving(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum TraitBoundModifier {
None,
Maybe,
pub type TyParamBounds = OwnedSlice<TyParamBound>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct TyParam {
pub ident: Ident,
pub id: NodeId,
/// Represents lifetimes and type parameters attached to a declaration
/// of a function, enum, trait, etc.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Generics {
pub lifetimes: Vec<LifetimeDef>,
pub ty_params: OwnedSlice<TyParam>,
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct WhereClause {
pub id: NodeId,
pub predicates: Vec<WherePredicate>,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum WherePredicate {
BoundPredicate(WhereBoundPredicate),
RegionPredicate(WhereRegionPredicate),
EqPredicate(WhereEqPredicate)
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct WhereBoundPredicate {
pub span: Span,
pub bounded_ty: P<Ty>,
pub bounds: OwnedSlice<TyParamBound>,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct WhereRegionPredicate {
pub span: Span,
pub lifetime: Lifetime,
pub bounds: Vec<Lifetime>,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct WhereEqPredicate {
pub id: NodeId,
pub span: Span,
/// used to drive conditional compilation
pub type CrateConfig = Vec<P<MetaItem>> ;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Crate {
pub module: Mod,
pub attrs: Vec<Attribute>,
pub type MetaItem = Spanned<MetaItem_>;
-#[deriving(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum MetaItem_ {
MetaWord(InternedString),
MetaList(InternedString, Vec<P<MetaItem>>),
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Block {
pub view_items: Vec<ViewItem>,
pub stmts: Vec<P<Stmt>>,
pub span: Span,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Pat {
pub id: NodeId,
pub node: Pat_,
pub span: Span,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct FieldPat {
pub ident: Ident,
pub pat: P<Pat>,
pub is_shorthand: bool,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum BindingMode {
BindByRef(Mutability),
BindByValue(Mutability),
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum PatWildKind {
/// Represents the wildcard pattern `_`
PatWildSingle,
PatWildMulti,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Pat_ {
/// Represents a wildcard pattern (either `_` or `..`)
PatWild(PatWildKind),
PatMac(Mac),
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum Mutability {
MutMutable,
MutImmutable,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum BinOp {
BiAdd,
BiSub,
BiGt,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum UnOp {
UnUniq,
UnDeref,
pub type Stmt = Spanned<Stmt_>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Stmt_ {
/// Could be an item or a local (let) binding:
StmtDecl(P<Decl>, NodeId),
StmtMac(P<Mac>, MacStmtStyle),
}
-#[deriving(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum MacStmtStyle {
/// The macro statement had a trailing semicolon, e.g. `foo! { ... };`
/// `foo!(...);`, `foo![...];`
/// Where a local declaration came from: either a true `let ... =
/// ...;`, or one desugared from the pattern of a for loop.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum LocalSource {
LocalLet,
LocalFor,
// FIXME (pending discussion of #1697, #2178...): local should really be
// a refinement on pat.
/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Local {
pub pat: P<Pat>,
pub ty: Option<P<Ty>>,
pub type Decl = Spanned<Decl_>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Decl_ {
/// A local (let) binding:
DeclLocal(P<Local>),
}
/// represents one arm of a 'match'
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Arm {
pub attrs: Vec<Attribute>,
pub pats: Vec<P<Pat>>,
pub body: P<Expr>,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Field {
pub ident: SpannedIdent,
pub expr: P<Expr>,
pub type SpannedIdent = Spanned<Ident>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum BlockCheckMode {
DefaultBlock,
UnsafeBlock(UnsafeSource),
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum UnsafeSource {
CompilerGenerated,
UserProvided,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Expr {
pub id: NodeId,
pub node: Expr_,
pub span: Span,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Expr_ {
/// First expr is the place; second expr is the value.
ExprBox(Option<P<Expr>>, P<Expr>),
/// <Vec<T> as SomeTrait>::SomeAssociatedItem
/// ^~~~~ ^~~~~~~~~ ^~~~~~~~~~~~~~~~~~
/// self_type trait_name item_name
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct QPath {
pub self_type: P<Ty>,
pub trait_ref: P<TraitRef>,
pub item_name: Ident, // FIXME(#20301) -- should use Name
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum MatchSource {
Normal,
IfLetDesugar { contains_else_clause: bool },
WhileLetDesugar,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum CaptureClause {
CaptureByValue,
CaptureByRef,
}
/// A delimited sequence of token trees
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Delimited {
/// The type of delimiter
pub delim: token::DelimToken,
}
/// A sequence of token treesee
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct SequenceRepetition {
/// The sequence of token trees
pub tts: Vec<TokenTree>,
/// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
/// for token sequences.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum KleeneOp {
ZeroOrMore,
OneOrMore,
///
/// The RHS of an MBE macro is the only place `SubstNt`s are substituted.
/// Nothing special happens to misnamed or misplaced `SubstNt`s.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
#[doc="For macro invocations; parsing is delegated to the macro"]
pub enum TokenTree {
/// A single token
/// is being invoked, and the vector of token-trees contains the source
/// of the macro invocation.
/// There's only one flavor, now, so this could presumably be simplified.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Mac_ {
// NB: the additional ident for a macro_rules-style macro is actually
// stored in the enclosing item. Oog.
MacInvocTT(Path, Vec<TokenTree> , SyntaxContext), // new macro-invocation
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum StrStyle {
CookedStr,
RawStr(uint)
pub type Lit = Spanned<Lit_>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum Sign {
Minus,
Plus
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum LitIntType {
SignedIntLit(IntTy, Sign),
UnsignedIntLit(UintTy),
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Lit_ {
LitStr(InternedString, StrStyle),
- LitBinary(Rc<Vec<u8> >),
+ LitBinary(Rc<Vec<u8>>),
LitByte(u8),
LitChar(char),
LitInt(u64, LitIntType),
// NB: If you change this, you'll probably want to change the corresponding
// type structure in middle/ty.rs as well.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct MutTy {
pub ty: P<Ty>,
pub mutbl: Mutability,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct TypeField {
pub ident: Ident,
pub mt: MutTy,
/// Represents a required method in a trait declaration,
/// one without a default implementation
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct TypeMethod {
pub ident: Ident,
pub attrs: Vec<Attribute>,
/// a default implementation A trait method is either required (meaning it
/// doesn't have an implementation, just a signature) or provided (meaning it
/// has a default implementation).
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum TraitItem {
RequiredMethod(TypeMethod),
ProvidedMethod(P<Method>),
TypeTraitItem(P<AssociatedType>),
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum ImplItem {
MethodImplItem(P<Method>),
TypeImplItem(P<Typedef>),
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct AssociatedType {
pub attrs: Vec<Attribute>,
pub ty_param: TyParam,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Typedef {
pub id: NodeId,
pub span: Span,
pub typ: P<Ty>,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub enum IntTy {
TyI,
TyI8,
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub enum UintTy {
TyU,
TyU8,
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub enum FloatTy {
TyF32,
TyF64,
}
// Bind a type to an associated type: `A=Foo`.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct TypeBinding {
pub id: NodeId,
pub ident: Ident,
// NB PartialEq method appears below.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Ty {
pub id: NodeId,
pub node: Ty_,
}
/// Not represented directly in the AST, referred to by name through a ty_path.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum PrimTy {
TyInt(IntTy),
TyUint(UintTy),
TyChar
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub enum Onceness {
Once,
Many
}
/// Represents the type of a closure
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct ClosureTy {
pub lifetimes: Vec<LifetimeDef>,
pub unsafety: Unsafety,
pub bounds: TyParamBounds,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct BareFnTy {
pub unsafety: Unsafety,
pub abi: Abi,
pub decl: P<FnDecl>
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
/// The different kinds of types recognized by the compiler
pub enum Ty_ {
TyVec(P<Ty>),
TyInfer,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum AsmDialect {
AsmAtt,
AsmIntel
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct InlineAsm {
pub asm: InternedString,
pub asm_str_style: StrStyle,
}
/// represents an argument in a function header
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Arg {
pub ty: P<Ty>,
pub pat: P<Pat>,
}
/// represents the header (not the body) of a function declaration
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct FnDecl {
pub inputs: Vec<Arg>,
pub output: FunctionRetTy,
pub variadic: bool
}
-#[deriving(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
+#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
pub enum Unsafety {
Unsafe,
Normal,
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum FunctionRetTy {
/// Functions with return type ! that always
/// raise an error or exit (i.e. never return to the caller)
}
/// Represents the kind of 'self' associated with a method
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum ExplicitSelf_ {
/// No self
SelfStatic,
pub type ExplicitSelf = Spanned<ExplicitSelf_>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Method {
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub node: Method_,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Method_ {
/// Represents a method declaration
MethDecl(Ident,
MethMac(Mac),
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Mod {
/// A span from the first token past `{` to the last token until `}`.
/// For `mod foo;`, the inner span ranges from the first token
pub items: Vec<P<Item>>,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct ForeignMod {
pub abi: Abi,
pub view_items: Vec<ViewItem>,
pub items: Vec<P<ForeignItem>>,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct VariantArg {
pub ty: P<Ty>,
pub id: NodeId,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum VariantKind {
TupleVariantKind(Vec<VariantArg>),
StructVariantKind(P<StructDef>),
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct EnumDef {
pub variants: Vec<P<Variant>>,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Variant_ {
pub name: Ident,
pub attrs: Vec<Attribute>,
pub type Variant = Spanned<Variant_>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum PathListItem_ {
PathListIdent { name: Ident, id: NodeId },
PathListMod { id: NodeId }
pub type ViewPath = Spanned<ViewPath_>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum ViewPath_ {
/// `foo::bar::baz as quux`
ViewPathList(Path, Vec<PathListItem> , NodeId)
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct ViewItem {
pub node: ViewItem_,
pub attrs: Vec<Attribute>,
pub span: Span,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum ViewItem_ {
/// Ident: name used to refer to this crate in the code
/// optional (InternedString,StrStyle): if present, this is a location
/// Distinguishes between Attributes that decorate items and Attributes that
/// are contained as statements within items. These two cases need to be
/// distinguished for pretty-printing.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum AttrStyle {
AttrOuter,
AttrInner,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub struct AttrId(pub uint);
/// Doc-comments are promoted to attributes that have is_sugared_doc = true
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Attribute_ {
pub id: AttrId,
pub style: AttrStyle,
/// that the ref_id is for. The impl_id maps to the "self type" of this impl.
/// If this impl is an ItemImpl, the impl_id is redundant (it could be the
/// same as the impl's node id).
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct TraitRef {
pub path: Path,
pub ref_id: NodeId,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct PolyTraitRef {
/// The `'a` in `<'a> Foo<&'a T>`
pub bound_lifetimes: Vec<LifetimeDef>,
pub trait_ref: TraitRef,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum Visibility {
Public,
Inherited,
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct StructField_ {
pub kind: StructFieldKind,
pub id: NodeId,
pub type StructField = Spanned<StructField_>;
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum StructFieldKind {
NamedField(Ident, Visibility),
/// Element of a tuple-like struct
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct StructDef {
/// Fields, not including ctor
pub fields: Vec<StructField>,
FIXME (#3300): Should allow items to be anonymous. Right now
we just use dummy names for anon items.
*/
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct Item {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub span: Span,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum Item_ {
ItemStatic(P<Ty>, Mutability, P<Expr>),
ItemConst(P<Ty>, P<Expr>),
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub struct ForeignItem {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub vis: Visibility,
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum ForeignItem_ {
ForeignItemFn(P<FnDecl>, Generics),
ForeignItemStatic(P<Ty>, /* is_mutbl */ bool),
}
}
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum UnboxedClosureKind {
FnUnboxedClosureKind,
FnMutUnboxedClosureKind,
/// The data we save and restore about an inlined item or method. This is not
/// part of the AST that we parse from a file, but it becomes part of the tree
/// that we trans.
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum InlinedItem {
IIItem(P<Item>),
IITraitItem(DefId /* impl id */, TraitItem),
/// - The default implementation for a trait method.
///
/// To construct one, use the `Code::from_node` function.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct FnLikeNode<'a> { node: ast_map::Node<'a> }
/// MaybeFnLike wraps a method that indicates if an object
/// Carries either an FnLikeNode or a Block, as these are the two
/// constructs that correspond to "code" (as in, something from which
/// we can construct a control-flow graph).
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum Code<'a> {
FnLikeCode(FnLikeNode<'a>),
BlockCode(&'a Block),
use parse::token;
use print::pprust;
use ptr::P;
-use visit::{mod, Visitor};
+use visit::{self, Visitor};
use arena::TypedArena;
use std::cell::RefCell;
use std::fmt;
use std::io::IoResult;
-use std::iter::{mod, repeat};
+use std::iter::{self, repeat};
use std::mem;
use std::slice;
pub mod blocks;
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
pub enum PathElem {
PathMod(Name),
PathName(Name)
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
struct LinkedPathNode<'a> {
node: PathElem,
next: LinkedPath<'a>,
}
// HACK(eddyb) move this into libstd (value wrapper for slice::Iter).
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Values<'a, T:'a>(pub slice::Iter<'a, T>);
impl<'a, T: Copy> Iterator for Values<'a, T> {
}).to_string()
}
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
pub enum Node<'ast> {
NodeItem(&'ast Item),
NodeForeignItem(&'ast ForeignItem),
/// Represents an entry and its parent Node ID
/// The odd layout is to bring down the total size.
-#[deriving(Copy, Show)]
+#[derive(Copy, Show)]
enum MapEntry<'ast> {
/// Placeholder for holes in the map.
NotPresent,
}
}
-#[deriving(Show)]
+#[derive(Show)]
struct InlinedParent {
path: Vec<PathElem>,
ii: InlinedItem
// ______________________________________________________________________
// Enumerating the IDs which appear in an AST
-#[deriving(RustcEncodable, RustcDecodable, Show, Copy)]
+#[derive(RustcEncodable, RustcDecodable, Show, Copy)]
pub struct IdRange {
pub min: NodeId,
pub max: NodeId,
first_attr_value_str_by_name(attrs, "crate_name")
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum InlineAttr {
InlineNone,
InlineHint,
}
/// Represents the #[deprecated="foo"] and friends attributes.
-#[deriving(RustcEncodable,RustcDecodable,Clone,Show)]
+#[derive(RustcEncodable,RustcDecodable,Clone,Show)]
pub struct Stability {
pub level: StabilityLevel,
pub text: Option<InternedString>
}
/// The available stability levels.
-#[deriving(RustcEncodable,RustcDecodable,PartialEq,PartialOrd,Clone,Show,Copy)]
+#[derive(RustcEncodable,RustcDecodable,PartialEq,PartialOrd,Clone,Show,Copy)]
pub enum StabilityLevel {
Deprecated,
Experimental,
}
}
-#[deriving(PartialEq, Show, RustcEncodable, RustcDecodable, Copy)]
+#[derive(PartialEq, Show, RustcEncodable, RustcDecodable, Copy)]
pub enum ReprAttr {
ReprAny,
ReprInt(Span, IntType),
}
}
-#[deriving(Eq, Hash, PartialEq, Show, RustcEncodable, RustcDecodable, Copy)]
+#[derive(Eq, Hash, PartialEq, Show, RustcEncodable, RustcDecodable, Copy)]
pub enum IntType {
SignedInt(ast::IntTy),
UnsignedInt(ast::UintTy)
/// A byte offset. Keep this small (currently 32-bits), as AST contains
/// a lot of them.
-#[deriving(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Show)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Show)]
pub struct BytePos(pub u32);
/// A character offset. Because of multibyte utf8 characters, a byte offset
/// is not equivalent to a character offset. The CodeMap will convert BytePos
/// values to CharPos values as necessary.
-#[deriving(Copy, PartialEq, Hash, PartialOrd, Show)]
+#[derive(Copy, PartialEq, Hash, PartialOrd, Show)]
pub struct CharPos(pub uint);
// FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
/// are *absolute* positions from the beginning of the codemap, not positions
/// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
/// to the original source.
-#[deriving(Clone, Copy, Show, Hash)]
+#[derive(Clone, Copy, Show, Hash)]
pub struct Span {
pub lo: BytePos,
pub hi: BytePos,
pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
-#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub struct Spanned<T> {
pub node: T,
pub span: Span,
pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
/// The syntax with which a macro was invoked.
-#[deriving(Clone, Copy, Hash, Show)]
+#[derive(Clone, Copy, Hash, Show)]
pub enum MacroFormat {
- /// e.g. #[deriving(...)] <item>
+ /// e.g. #[derive(...)] <item>
MacroAttribute,
/// e.g. `format!()`
MacroBang
}
-#[deriving(Clone, Hash, Show)]
+#[derive(Clone, Hash, Show)]
pub struct NameAndSpan {
/// The name of the macro that was invoked to create the thing
/// with this Span.
}
/// Extra information for tracking macro expansion of spans
-#[deriving(Hash, Show)]
+#[derive(Hash, Show)]
pub struct ExpnInfo {
/// The location of the actual macro invocation, e.g. `let x =
/// foo!();`
pub callee: NameAndSpan
}
-#[deriving(PartialEq, Eq, Clone, Show, Hash, RustcEncodable, RustcDecodable, Copy)]
+#[derive(PartialEq, Eq, Clone, Show, Hash, RustcEncodable, RustcDecodable, Copy)]
pub struct ExpnId(u32);
pub const NO_EXPANSION: ExpnId = ExpnId(-1);
}
/// Identifies an offset of a multi-byte character in a FileMap
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct MultiByteChar {
/// The absolute offset of the character in the CodeMap
pub pos: BytePos,
/// maximum number of lines we will print for each error; arbitrary.
static MAX_LINES: uint = 6u;
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub enum RenderSpan {
/// A FullSpan renders with both with an initial line for the
/// message, prefixed by file:linenum, followed by a summary of
}
}
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub enum ColorConfig {
Auto,
Always,
/// This structure is used to signify that a task has panicked with a fatal error
/// from the diagnostics. You can use this with the `Any` trait to figure out
/// how a rustc task died (if so desired).
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct FatalError;
/// Signifies that the compiler died with an explicit call to `.bug`
/// or `.span_bug` rather than a failed assertion, etc.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct ExplicitBug;
/// A span-handler is like a handler but also
}
}
-#[deriving(Copy, PartialEq, Clone)]
+#[derive(Copy, PartialEq, Clone)]
pub enum Level {
Bug,
Fatal,
/// Fill-in macro expansion result, to allow compilation to continue
/// after hitting errors.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct DummyResult {
expr_only: bool,
span: Span
/// A syntax extension that is attached to an item and creates new items
/// based upon it.
///
- /// `#[deriving(...)]` is an `ItemDecorator`.
+ /// `#[derive(...)]` is an `ItemDecorator`.
Decorator(Box<ItemDecorator + 'static>),
/// A syntax extension that is attached to an item and modifies it
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use ast::{MetaItem, Item, Expr, mod};
+use ast::{MetaItem, Item, Expr, self};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
trait_def.expand(cx, mitem, item, push)
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum OrderingOp {
PartialCmpOp, LtOp, LeOp, GtOp, GeOp,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! The compiler code necessary for `#[deriving(Decodable)]`. See encodable.rs for more.
+//! The compiler code necessary for `#[derive(Decodable)]`. See encodable.rs for more.
use ast;
use ast::{MetaItem, Item, Expr, MutMutable};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! The compiler code necessary to implement the `#[deriving(Encodable)]`
+//! The compiler code necessary to implement the `#[derive(Encodable)]`
//! (and `Decodable`, in decodable.rs) extension. The idea here is that
-//! type-defining items may be tagged with `#[deriving(Encodable, Decodable)]`.
+//! type-defining items may be tagged with `#[derive(Encodable, Decodable)]`.
//!
//! For example, a type like:
//!
//! ```ignore
-//! #[deriving(Encodable, Decodable)]
+//! #[derive(Encodable, Decodable)]
//! struct Node { id: uint }
//! ```
//!
//! references other non-built-in types. A type definition like:
//!
//! ```ignore
-//! #[deriving(Encodable, Decodable)]
+//! #[derive(Encodable, Decodable)]
//! struct Spanned<T> { node: T, span: Span }
//! ```
//!
use attr::AttrMetaMethods;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
-use codemap::{mod, DUMMY_SP};
+use codemap::{self, DUMMY_SP};
use codemap::Span;
use fold::MoveMap;
use owned_slice::OwnedSlice;
}
}
-#[deriving(PartialEq)] // dogfooding!
+#[derive(PartialEq)] // dogfooding!
enum StructType {
Unknown, Record, Tuple
}
use ptr::P;
/// The types of pointers
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum PtrTy<'a> {
/// &'lifetime mut
Borrowed(Option<&'a str>, ast::Mutability),
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Path<'a> {
pub path: Vec<&'a str> ,
pub lifetime: Option<&'a str>,
}
/// A type. Supports pointers, Self, and literals
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum Ty<'a> {
Self,
/// &/Box/ Ty
}
/// Lifetimes and bounds on type parameters
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct LifetimeBounds<'a> {
pub lifetimes: Vec<(&'a str, Vec<&'a str>)>,
pub bounds: Vec<(&'a str, Vec<Path<'a>>)>,
}
if stmts.len() == 0 {
- cx.span_bug(trait_span, "#[deriving(Hash)] needs at least one field");
+ cx.span_bug(trait_span, "#[derive(Hash)] needs at least one field");
}
cx.expr_block(cx.block(trait_span, stmts, None))
pub mod hash;
pub mod rand;
pub mod show;
-pub mod zero;
pub mod default;
pub mod primitive;
"Show" => expand!(show::expand_deriving_show),
- "Zero" => expand!(zero::expand_deriving_zero),
"Default" => expand!(default::expand_deriving_default),
"FromPrimitive" => expand!(primitive::expand_deriving_from_primitive),
Struct(_) => substr.type_ident,
EnumMatching(_, v, _) => v.node.name,
EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => {
- cx.span_bug(span, "nonsensical .fields in `#[deriving(Show)]`")
+ cx.span_bug(span, "nonsensical .fields in `#[derive(Show)]`")
}
};
+++ /dev/null
-// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use ast::{MetaItem, Item, Expr};
-use codemap::Span;
-use ext::base::ExtCtxt;
-use ext::build::AstBuilder;
-use ext::deriving::generic::*;
-use ext::deriving::generic::ty::*;
-use parse::token::InternedString;
-use ptr::P;
-
-pub fn expand_deriving_zero<F>(cx: &mut ExtCtxt,
- span: Span,
- mitem: &MetaItem,
- item: &Item,
- push: F) where
- F: FnOnce(P<Item>),
-{
- let inline = cx.meta_word(span, InternedString::new("inline"));
- let attrs = vec!(cx.attribute(span, inline));
- let trait_def = TraitDef {
- span: span,
- attributes: Vec::new(),
- path: Path::new(vec!("std", "num", "Zero")),
- additional_bounds: Vec::new(),
- generics: LifetimeBounds::empty(),
- methods: vec!(
- MethodDef {
- name: "zero",
- generics: LifetimeBounds::empty(),
- explicit_self: None,
- args: Vec::new(),
- ret_ty: Self,
- attributes: attrs.clone(),
- combine_substructure: combine_substructure(|a, b, c| {
- zero_substructure(a, b, c)
- })
- },
- MethodDef {
- name: "is_zero",
- generics: LifetimeBounds::empty(),
- explicit_self: borrowed_explicit_self(),
- args: Vec::new(),
- ret_ty: Literal(Path::new(vec!("bool"))),
- attributes: attrs,
- combine_substructure: combine_substructure(|cx, span, substr| {
- cs_and(|cx, span, _, _| cx.span_bug(span,
- "Non-matching enum \
- variant in \
- deriving(Zero)"),
- cx, span, substr)
- })
- }
- )
- };
- trait_def.expand(cx, mitem, item, push)
-}
-
-fn zero_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
- let zero_ident = vec!(
- cx.ident_of("std"),
- cx.ident_of("num"),
- cx.ident_of("Zero"),
- cx.ident_of("zero")
- );
- let zero_call = |&: span| cx.expr_call_global(span, zero_ident.clone(), Vec::new());
-
- return match *substr.fields {
- StaticStruct(_, ref summary) => {
- match *summary {
- Unnamed(ref fields) => {
- if fields.is_empty() {
- cx.expr_ident(trait_span, substr.type_ident)
- } else {
- let exprs = fields.iter().map(|sp| zero_call(*sp)).collect();
- cx.expr_call_ident(trait_span, substr.type_ident, exprs)
- }
- }
- Named(ref fields) => {
- let zero_fields = fields.iter().map(|&(ident, span)| {
- cx.field_imm(span, ident, zero_call(span))
- }).collect();
- cx.expr_struct_ident(trait_span, substr.type_ident, zero_fields)
- }
- }
- }
- StaticEnum(..) => {
- cx.span_err(trait_span, "`Zero` cannot be derived for enums, only structs");
- // let compilation continue
- cx.expr_uint(trait_span, 0)
- }
- _ => cx.bug("Non-static method in `deriving(Zero)`")
- };
-}
/// A visitor that extracts the PatIdent (binding) paths
/// from a given thingy and puts them in a mutable
/// array
-#[deriving(Clone)]
+#[derive(Clone)]
struct PatIdentFinder {
ident_accumulator: Vec<ast::Ident>
}
// a visitor that extracts the paths
// from a given thingy and puts them in a mutable
// array (passed in to the traversal)
- #[deriving(Clone)]
+ #[derive(Clone)]
struct PathExprFinderContext {
path_accumulator: Vec<ast::Path> ,
}
use std::collections::HashMap;
use std::iter::repeat;
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
enum ArgumentType {
Known(String),
Unsigned
rename_memo: RefCell<HashMap<(SyntaxContext,Ident,Name),SyntaxContext>>,
}
-#[deriving(PartialEq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
+#[derive(PartialEq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
pub enum SyntaxContext_ {
EmptyCtxt,
Mark (Mrk,SyntaxContext),
// because of the SCTable, I now need a tidy way of
// creating syntax objects. Sigh.
- #[deriving(Clone, PartialEq, Show)]
+ #[derive(Clone, PartialEq, Show)]
enum TestSC {
M(Mrk),
R(Ident,Name)
// To avoid costly uniqueness checks, we require that `MatchSeq` always has
// a nonempty body.
-#[deriving(Clone)]
+#[derive(Clone)]
enum TokenTreeOrTokenTreeVec {
Tt(ast::TokenTree),
TtSeq(Rc<Vec<ast::TokenTree>>),
}
/// an unzipping of `TokenTree`s
-#[deriving(Clone)]
+#[derive(Clone)]
struct MatcherTtFrame {
elts: TokenTreeOrTokenTreeVec,
idx: uint,
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct MatcherPos {
stack: Vec<MatcherTtFrame>,
top_elts: TokenTreeOrTokenTreeVec,
use std::collections::HashMap;
///an unzipping of `TokenTree`s
-#[deriving(Clone)]
+#[derive(Clone)]
struct TtFrame {
forest: TokenTree,
idx: uint,
sep: Option<Token>,
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct TtReader<'a> {
pub sp_diag: &'a SpanHandler,
/// the unzipped tree:
matched_opt.map(|s| lookup_cur_matched_by_matched(r, s))
}
-#[deriving(Clone)]
+#[derive(Clone)]
enum LockstepIterSize {
LisUnconstrained,
LisConstraint(uint, Ident),
}
/// A set of features to be used by later passes.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Features {
pub default_type_params: bool,
pub unboxed_closures: bool,
/// A non-growable owned slice. This is a separate type to allow the
/// representation to change.
-#[deriving(Hash, PartialEq, Eq, PartialOrd, Ord)]
+#[derive(Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct OwnedSlice<T> {
data: Box<[T]>
}
use std::string::String;
use std::uint;
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
pub enum CommentStyle {
/// No code on either side of each line of the comment
Isolated,
BlankLine,
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Comment {
pub style: CommentStyle,
pub lines: Vec<String>,
debug!("<<< consume comment");
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Literal {
pub lit: String,
pub pos: BytePos,
use std::num;
use std::rc::Rc;
use std::str;
+use std::string::CowString;
pub use ext::tt::transcribe::{TtReader, new_tt_reader};
}
}
-#[deriving(Clone, PartialEq, Eq, Show)]
+#[derive(Clone, PartialEq, Eq, Show)]
pub struct TokenAndSpan {
pub tok: token::Token,
pub sp: Span,
/// Converts CRLF to LF in the given string, raising an error on bare CR.
fn translate_crlf<'b>(&self, start: BytePos,
- s: &'b str, errmsg: &'b str) -> str::CowString<'b> {
+ s: &'b str, errmsg: &'b str) -> CowString<'b> {
let mut i = 0u;
while i < s.len() {
let str::CharRange { ch, next } = s.char_range_at(i);
use ptr::P;
/// The specific types of unsupported syntax
-#[deriving(Copy, PartialEq, Eq, Hash)]
+#[derive(Copy, PartialEq, Eq, Hash)]
pub enum ObsoleteSyntax {
ObsoleteOwnedType,
ObsoleteOwnedExpr,
use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
use ast::{Visibility, WhereClause};
use ast;
-use ast_util::{mod, as_prec, ident_to_path, operator_prec};
-use codemap::{mod, Span, BytePos, Spanned, spanned, mk_sp, DUMMY_SP};
+use ast_util::{self, as_prec, ident_to_path, operator_prec};
+use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, DUMMY_SP};
use diagnostic;
use ext::tt::macro_parser;
use parse;
use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
use parse::lexer::{Reader, TokenAndSpan};
use parse::obsolete::*;
-use parse::token::{mod, MatchNt, SubstNt, InternedString};
+use parse::token::{self, MatchNt, SubstNt, InternedString};
use parse::token::{keywords, special_idents};
use parse::{new_sub_parser_from_file, ParseSess};
use print::pprust;
use std::num::Float;
use std::rc::Rc;
use std::slice;
-use std::str::from_str;
bitflags! {
flags Restrictions: u8 {
/// How to parse a path. There are four different kinds of paths, all of which
/// are parsed somewhat differently.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum PathParsingMode {
/// A path with no type parameters; e.g. `foo::bar::Baz`
NoTypesAllowed,
}
/// How to parse a bound, whether to allow bound modifiers such as `?`.
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
pub enum BoundParsingMode {
Bare,
Modified,
pub expected_tokens: Vec<TokenType>,
}
-#[deriving(PartialEq, Eq, Clone)]
+#[derive(PartialEq, Eq, Clone)]
pub enum TokenType {
Token(token::Token),
Operator,
use util::interner;
use serialize::{Decodable, Decoder, Encodable, Encoder};
-use std::cmp::Equiv;
use std::fmt;
use std::mem;
use std::ops::Deref;
use std::rc::Rc;
#[allow(non_camel_case_types)]
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
pub enum BinOpToken {
Plus,
Minus,
}
/// A delimeter token
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
pub enum DelimToken {
/// A round parenthesis: `(` or `)`
Paren,
Brace,
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
pub enum IdentStyle {
/// `::` follows the identifier with no whitespace in-between.
ModName,
Plain,
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show, Copy)]
pub enum Lit {
Byte(ast::Name),
Char(ast::Name),
}
#[allow(non_camel_case_types)]
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Show)]
pub enum Token {
/* Expression-operator symbols. */
Eq,
}
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)]
/// For interpolation during macro expansion.
pub enum Nonterminal {
NtItem(P<ast::Item>),
pub use self::Keyword::*;
use ast;
- #[deriving(Copy)]
+ #[derive(Copy)]
pub enum Keyword {
$( $sk_variant, )*
$( $rk_variant, )*
/// destroyed. In particular, they must not access string contents. This can
/// be fixed in the future by just leaking all strings until task death
/// somehow.
-#[deriving(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
+#[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
pub struct InternedString {
string: RcStr,
}
}
}
-#[allow(deprecated)]
-impl<'a> Equiv<&'a str> for InternedString {
- fn equiv(&self, other: & &'a str) -> bool {
- (*other) == self.string[]
- }
-}
-
impl<'a> PartialEq<&'a str> for InternedString {
#[inline(always)]
fn eq(&self, other: & &'a str) -> bool {
use std::string;
use std::iter::repeat;
-#[deriving(Clone, Copy, PartialEq)]
+#[derive(Clone, Copy, PartialEq)]
pub enum Breaks {
Consistent,
Inconsistent,
}
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct BreakToken {
offset: int,
blank_space: int
}
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
pub struct BeginToken {
offset: int,
breaks: Breaks
}
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum Token {
String(string::String, int),
Break(BreakToken),
s
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum PrintStackBreak {
Fits,
Broken(Breaks),
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct PrintStackElem {
offset: int,
pbreak: PrintStackBreak
pub use self::AnnNode::*;
use abi;
-use ast::{mod, FnUnboxedClosureKind, FnMutUnboxedClosureKind};
+use ast::{self, FnUnboxedClosureKind, FnMutUnboxedClosureKind};
use ast::{FnOnceUnboxedClosureKind};
use ast::{MethodImplItem, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
use ast::{RequiredMethod, ProvidedMethod, TypeImplItem, TypeTraitItem};
use ast_util;
use owned_slice::OwnedSlice;
use attr::{AttrMetaMethods, AttributeMethods};
-use codemap::{mod, CodeMap, BytePos};
+use codemap::{self, CodeMap, BytePos};
use diagnostic;
-use parse::token::{mod, BinOpToken, Token};
+use parse::token::{self, BinOpToken, Token};
use parse::lexer::comments;
use parse;
-use print::pp::{mod, break_offset, word, space, zerobreak, hardbreak};
+use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
use print::pp::{Breaks, Consistent, Inconsistent, eof};
use ptr::P;
use std::{ascii, mem};
-use std::io::{mod, IoResult};
+use std::io::{self, IoResult};
use std::iter;
pub enum AnnNode<'a> {
fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct NoAnn;
impl PpAnn for NoAnn {}
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct CurrentCommentAndLiteral {
cur_cmnt: uint,
cur_lit: uint,
//! implementation changes (using a special thread-local heap, for example).
//! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated.
-use std::fmt::{mod, Show};
+use std::fmt::{self, Show};
use std::hash::Hash;
use std::ops::Deref;
use std::ptr;
})
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
enum HasTestSignature {
Yes,
No,
}
}
-#[deriving(Clone, PartialEq, Hash, PartialOrd)]
+#[derive(Clone, PartialEq, Hash, PartialOrd)]
pub struct RcStr {
string: Rc<String>,
}
use ptr::P;
use owned_slice::OwnedSlice;
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum FnKind<'a> {
/// fn foo() or extern "Abi" fn foo()
FkItemFn(Ident, &'a Generics, Unsafety, Abi),
/// Most attributes can only be turned on and must be turned off with term.reset().
/// The ones that can be turned off explicitly take a boolean value.
/// Color is also represented as an attribute for convenience.
- #[deriving(Copy)]
+ #[derive(Copy)]
pub enum Attr {
/// Bold (or possibly bright) mode
Bold,
/// A parsed terminfo database entry.
-#[deriving(Show)]
+#[derive(Show)]
pub struct TermInfo {
/// Names for the terminal
pub names: Vec<String> ,
use std::mem::replace;
use std::iter::repeat;
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
enum States {
Nothing,
Percent,
SeekIfEndPercent(int)
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
enum FormatState {
FormatStateFlags,
FormatStateWidth,
/// Types of parameters a capability can use
#[allow(missing_docs)]
-#[deriving(Clone)]
+#[derive(Clone)]
pub enum Param {
Words(String),
Number(int)
Ok(output)
}
-#[deriving(Copy, PartialEq)]
+#[derive(Copy, PartialEq)]
struct Flags {
width: uint,
precision: uint,
}
}
-#[deriving(Copy)]
+#[derive(Copy)]
enum FormatOp {
FormatDigit,
FormatOctal,
use term::Terminal;
use term::color::{Color, RED, YELLOW, GREEN, CYAN};
-use std::any::{Any, AnyRefExt};
+use std::any::Any;
use std::cmp;
use std::collections::BTreeMap;
use std::f64;
use std::iter::repeat;
use std::num::{Float, FloatMath, Int};
use std::os;
-use std::str::{FromStr, from_str};
+use std::str::FromStr;
use std::sync::mpsc::{channel, Sender};
-use std::thread::{mod, Thread};
+use std::thread::{self, Thread};
use std::thunk::{Thunk, Invoke};
use std::time::Duration;
// colons. This way if some test runner wants to arrange the tests
// hierarchically it may.
-#[deriving(Clone, PartialEq, Eq, Hash)]
+#[derive(Clone, PartialEq, Eq, Hash)]
pub enum TestName {
StaticTestName(&'static str),
DynTestName(String)
}
}
-#[deriving(Clone, Copy)]
+#[derive(Clone, Copy)]
enum NamePadding {
PadNone,
PadOnLeft,
/// This is feed into functions marked with `#[bench]` to allow for
/// set-up & tear-down before running a piece of code repeatedly via a
/// call to `iter`.
-#[deriving(Copy)]
+#[derive(Copy)]
pub struct Bencher {
iterations: u64,
dur: Duration,
pub bytes: u64,
}
-#[deriving(Copy, Clone, Show, PartialEq, Eq, Hash)]
+#[derive(Copy, Clone, Show, PartialEq, Eq, Hash)]
pub enum ShouldFail {
No,
Yes(Option<&'static str>)
// The definition of a single test. A test runner will run a list of
// these.
-#[deriving(Clone, Show, PartialEq, Eq, Hash)]
+#[derive(Clone, Show, PartialEq, Eq, Hash)]
pub struct TestDesc {
pub name: TestName,
pub ignore: bool,
pub should_fail: ShouldFail,
}
-#[deriving(Show)]
+#[derive(Show)]
pub struct TestDescAndFn {
pub desc: TestDesc,
pub testfn: TestFn,
}
-#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq, Show, Copy)]
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show, Copy)]
pub struct Metric {
value: f64,
noise: f64
}
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
pub struct MetricMap(BTreeMap<String,Metric>);
impl Clone for MetricMap {
}
/// Analysis of a single change in metric
-#[deriving(Copy, PartialEq, Show)]
+#[derive(Copy, PartialEq, Show)]
pub enum MetricChange {
LikelyNoise,
MetricAdded,
test_main(args, owned_tests)
}
-#[deriving(Copy)]
+#[derive(Copy)]
pub enum ColorConfig {
AutoColor,
AlwaysColor,
}
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
pub struct BenchSamples {
ns_iter_summ: stats::Summary<f64>,
mb_s: uint,
}
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
pub enum TestResult {
TrOk,
TrFailed,
}
}
-#[deriving(Clone)]
+#[derive(Clone)]
enum TestEvent {
TeFiltered(Vec<TestDesc> ),
TeWait(TestDesc, NamePadding),
#![allow(missing_docs)]
-use std::cmp::Ordering::{mod, Less, Greater, Equal};
+use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_map;
use std::fmt::Show;
}
/// Extracted collection of all the summary statistics of a sample set.
-#[deriving(Clone, PartialEq)]
+#[derive(Clone, PartialEq)]
#[allow(missing_docs)]
pub struct Summary<T> {
pub sum: T,
#[bench]
pub fn sum_many_f64(b: &mut Bencher) {
let nums = [-1e30f64, 1e60, 1e30, 1.0, -1e60];
- let v = Vec::from_fn(500, |i| nums[i%5]);
+ let v = range(0, 500).map(|i| nums[i%5]).collect::<Vec<_>>();
b.iter(|| {
v.as_slice().sum();
+++ /dev/null
-// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! Simple time handling.
-
-#![crate_name = "time"]
-#![deprecated = "use the http://github.com/rust-lang/time crate instead"]
-#![allow(deprecated)]
-
-#![crate_type = "rlib"]
-#![crate_type = "dylib"]
-#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
- html_favicon_url = "http://www.rust-lang.org/favicon.ico",
- html_root_url = "http://doc.rust-lang.org/nightly/",
- html_playground_url = "http://play.rust-lang.org/")]
-
-#![allow(unknown_features)]
-#![feature(phase, globs)]
-#![feature(old_orphan_check)]
-#![feature(associated_types)]
-#![feature(default_type_params)]
-
-#[cfg(test)] #[phase(plugin, link)] extern crate log;
-
-extern crate "serialize" as rustc_serialize;
-extern crate libc;
-
-pub use self::ParseError::*;
-use self::Fmt::*;
-
-use std::fmt::{mod, Show};
-use std::num::SignedInt;
-use std::ops::{Add, Sub};
-use std::time::Duration;
-
-static NSEC_PER_SEC: i32 = 1_000_000_000_i32;
-
-mod rustrt {
- use super::Tm;
-
- extern {
- pub fn rust_tzset();
- pub fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm);
- pub fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm);
- pub fn rust_timegm(tm: &Tm) -> i64;
- pub fn rust_mktime(tm: &Tm) -> i64;
- }
-}
-
-#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios")))]
-mod imp {
- use libc::{c_int, timespec};
-
- // Apparently android provides this in some other library?
- #[cfg(not(target_os = "android"))]
- #[link(name = "rt")]
- extern {}
-
- extern {
- pub fn clock_gettime(clk_id: c_int, tp: *mut timespec) -> c_int;
- }
-
-}
-#[cfg(any(target_os = "macos", target_os = "ios"))]
-mod imp {
- use libc::{timeval, timezone, c_int, mach_timebase_info};
-
- extern {
- pub fn gettimeofday(tp: *mut timeval, tzp: *mut timezone) -> c_int;
- pub fn mach_absolute_time() -> u64;
- pub fn mach_timebase_info(info: *mut mach_timebase_info) -> c_int;
- }
-}
-
-/// A record specifying a time value in seconds and nanoseconds.
-#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, RustcEncodable,
- RustcDecodable, Show, Copy)]
-pub struct Timespec {
- pub sec: i64,
- pub nsec: i32,
-}
-
-/*
- * Timespec assumes that pre-epoch Timespecs have negative sec and positive
- * nsec fields. Darwin's and Linux's struct timespec functions handle pre-
- * epoch timestamps using a "two steps back, one step forward" representation,
- * though the man pages do not actually document this. For example, the time
- * -1.2 seconds before the epoch is represented by `Timespec { sec: -2_i64,
- * nsec: 800_000_000_i32 }`.
- */
-impl Timespec {
- pub fn new(sec: i64, nsec: i32) -> Timespec {
- assert!(nsec >= 0 && nsec < NSEC_PER_SEC);
- Timespec { sec: sec, nsec: nsec }
- }
-}
-
-impl Add<Duration> for Timespec {
- type Output = Timespec;
-
- fn add(self, other: Duration) -> Timespec {
- let d_sec = other.num_seconds();
- // It is safe to unwrap the nanoseconds, because there cannot be
- // more than one second left, which fits in i64 and in i32.
- let d_nsec = (other - Duration::seconds(d_sec))
- .num_nanoseconds().unwrap() as i32;
- let mut sec = self.sec + d_sec;
- let mut nsec = self.nsec + d_nsec;
- if nsec >= NSEC_PER_SEC {
- nsec -= NSEC_PER_SEC;
- sec += 1;
- } else if nsec < 0 {
- nsec += NSEC_PER_SEC;
- sec -= 1;
- }
- Timespec::new(sec, nsec)
- }
-}
-
-impl Sub for Timespec {
- type Output = Duration;
-
- fn sub(self, other: Timespec) -> Duration {
- let sec = self.sec - other.sec;
- let nsec = self.nsec - other.nsec;
- Duration::seconds(sec) + Duration::nanoseconds(nsec as i64)
- }
-}
-
-/// Returns the current time as a `timespec` containing the seconds and
-/// nanoseconds since 1970-01-01T00:00:00Z.
-pub fn get_time() -> Timespec {
- unsafe {
- let (sec, nsec) = os_get_time();
- return Timespec::new(sec, nsec);
- }
-
- #[cfg(windows)]
- unsafe fn os_get_time() -> (i64, i32) {
- static NANOSECONDS_FROM_1601_TO_1970: u64 = 11644473600000000;
-
- let mut time = libc::FILETIME {
- dwLowDateTime: 0,
- dwHighDateTime: 0,
- };
- libc::GetSystemTimeAsFileTime(&mut time);
-
- // A FILETIME contains a 64-bit value representing the number of
- // hectonanosecond (100-nanosecond) intervals since 1601-01-01T00:00:00Z.
- // http://support.microsoft.com/kb/167296/en-us
- let ns_since_1601 = (((time.dwHighDateTime as u64) << 32) |
- ((time.dwLowDateTime as u64) << 0)) / 10;
- let ns_since_1970 = ns_since_1601 - NANOSECONDS_FROM_1601_TO_1970;
-
- ((ns_since_1970 / 1000000) as i64,
- ((ns_since_1970 % 1000000) * 1000) as i32)
- }
-
- #[cfg(any(target_os = "macos", target_os = "ios"))]
- unsafe fn os_get_time() -> (i64, i32) {
- use std::ptr;
- let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
- imp::gettimeofday(&mut tv, ptr::null_mut());
- (tv.tv_sec as i64, tv.tv_usec * 1000)
- }
-
- #[cfg(not(any(target_os = "macos", target_os = "ios", windows)))]
- unsafe fn os_get_time() -> (i64, i32) {
- let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
- imp::clock_gettime(libc::CLOCK_REALTIME, &mut tv);
- (tv.tv_sec as i64, tv.tv_nsec as i32)
- }
-}
-
-
-/// Returns the current value of a high-resolution performance counter
-/// in nanoseconds since an unspecified epoch.
-pub fn precise_time_ns() -> u64 {
- return os_precise_time_ns();
-
- #[cfg(windows)]
- fn os_precise_time_ns() -> u64 {
- let mut ticks_per_s = 0;
- assert_eq!(unsafe {
- libc::QueryPerformanceFrequency(&mut ticks_per_s)
- }, 1);
- let ticks_per_s = if ticks_per_s == 0 {1} else {ticks_per_s};
- let mut ticks = 0;
- assert_eq!(unsafe {
- libc::QueryPerformanceCounter(&mut ticks)
- }, 1);
-
- return (ticks as u64 * 1000000000) / (ticks_per_s as u64);
- }
-
- #[cfg(any(target_os = "macos", target_os = "ios"))]
- fn os_precise_time_ns() -> u64 {
- static mut TIMEBASE: libc::mach_timebase_info = libc::mach_timebase_info { numer: 0,
- denom: 0 };
- static ONCE: std::sync::Once = std::sync::ONCE_INIT;
- unsafe {
- ONCE.call_once(|| {
- imp::mach_timebase_info(&mut TIMEBASE);
- });
- let time = imp::mach_absolute_time();
- time * TIMEBASE.numer as u64 / TIMEBASE.denom as u64
- }
- }
-
- #[cfg(not(any(windows, target_os = "macos", target_os = "ios")))]
- fn os_precise_time_ns() -> u64 {
- let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
- unsafe {
- imp::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
- }
- return (ts.tv_sec as u64) * 1000000000 + (ts.tv_nsec as u64)
- }
-}
-
-
-/// Returns the current value of a high-resolution performance counter
-/// in seconds since an unspecified epoch.
-pub fn precise_time_s() -> f64 {
- return (precise_time_ns() as f64) / 1000000000.;
-}
-
-pub fn tzset() {
- unsafe {
- rustrt::rust_tzset();
- }
-}
-
-/// Holds a calendar date and time broken down into its components (year, month, day, and so on),
-/// also called a broken-down time value.
-// FIXME: use c_int instead of i32?
-#[repr(C)]
-#[deriving(Clone, Copy, PartialEq, Eq, Show)]
-pub struct Tm {
- /// Seconds after the minute - [0, 60]
- pub tm_sec: i32,
-
- /// Minutes after the hour - [0, 59]
- pub tm_min: i32,
-
- /// Hours after midnight - [0, 23]
- pub tm_hour: i32,
-
- /// Day of the month - [1, 31]
- pub tm_mday: i32,
-
- /// Months since January - [0, 11]
- pub tm_mon: i32,
-
- /// Years since 1900
- pub tm_year: i32,
-
- /// Days since Sunday - [0, 6]. 0 = Sunday, 1 = Monday, ..., 6 = Saturday.
- pub tm_wday: i32,
-
- /// Days since January 1 - [0, 365]
- pub tm_yday: i32,
-
- /// Daylight Saving Time flag.
- ///
- /// This value is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time
- /// is not in effect, and negative if this information is not available.
- pub tm_isdst: i32,
-
- /// Identifies the time zone that was used to compute this broken-down time value, including any
- /// adjustment for Daylight Saving Time. This is the number of seconds east of UTC. For example,
- /// for U.S. Pacific Daylight Time, the value is -7*60*60 = -25200.
- pub tm_gmtoff: i32,
-
- /// Nanoseconds after the second - [0, 10<sup>9</sup> - 1]
- pub tm_nsec: i32,
-}
-
-pub fn empty_tm() -> Tm {
- Tm {
- tm_sec: 0_i32,
- tm_min: 0_i32,
- tm_hour: 0_i32,
- tm_mday: 0_i32,
- tm_mon: 0_i32,
- tm_year: 0_i32,
- tm_wday: 0_i32,
- tm_yday: 0_i32,
- tm_isdst: 0_i32,
- tm_gmtoff: 0_i32,
- tm_nsec: 0_i32,
- }
-}
-
-/// Returns the specified time in UTC
-pub fn at_utc(clock: Timespec) -> Tm {
- unsafe {
- let Timespec { sec, nsec } = clock;
- let mut tm = empty_tm();
- rustrt::rust_gmtime(sec, nsec, &mut tm);
- tm
- }
-}
-
-/// Returns the current time in UTC
-pub fn now_utc() -> Tm {
- at_utc(get_time())
-}
-
-/// Returns the specified time in the local timezone
-pub fn at(clock: Timespec) -> Tm {
- unsafe {
- let Timespec { sec, nsec } = clock;
- let mut tm = empty_tm();
- rustrt::rust_localtime(sec, nsec, &mut tm);
- tm
- }
-}
-
-/// Returns the current time in the local timezone
-pub fn now() -> Tm {
- at(get_time())
-}
-
-impl Tm {
- /// Convert time to the seconds from January 1, 1970
- pub fn to_timespec(&self) -> Timespec {
- unsafe {
- let sec = match self.tm_gmtoff {
- 0_i32 => rustrt::rust_timegm(self),
- _ => rustrt::rust_mktime(self)
- };
-
- Timespec::new(sec, self.tm_nsec)
- }
- }
-
- /// Convert time to the local timezone
- pub fn to_local(&self) -> Tm {
- at(self.to_timespec())
- }
-
- /// Convert time to the UTC
- pub fn to_utc(&self) -> Tm {
- at_utc(self.to_timespec())
- }
-
- /// Returns a TmFmt that outputs according to the `asctime` format in ISO
- /// C, in the local timezone.
- ///
- /// Example: "Thu Jan 1 00:00:00 1970"
- pub fn ctime(&self) -> TmFmt {
- TmFmt {
- tm: self,
- format: FmtCtime,
- }
- }
-
- /// Returns a TmFmt that outputs according to the `asctime` format in ISO
- /// C.
- ///
- /// Example: "Thu Jan 1 00:00:00 1970"
- pub fn asctime(&self) -> TmFmt {
- TmFmt {
- tm: self,
- format: FmtStr("%c"),
- }
- }
-
- /// Formats the time according to the format string.
- pub fn strftime<'a>(&'a self, format: &'a str) -> Result<TmFmt<'a>, ParseError> {
- validate_format(TmFmt {
- tm: self,
- format: FmtStr(format),
- })
- }
-
- /// Returns a TmFmt that outputs according to RFC 822.
- ///
- /// local: "Thu, 22 Mar 2012 07:53:18 PST"
- /// utc: "Thu, 22 Mar 2012 14:53:18 GMT"
- pub fn rfc822(&self) -> TmFmt {
- if self.tm_gmtoff == 0_i32 {
- TmFmt {
- tm: self,
- format: FmtStr("%a, %d %b %Y %T GMT"),
- }
- } else {
- TmFmt {
- tm: self,
- format: FmtStr("%a, %d %b %Y %T %Z"),
- }
- }
- }
-
- /// Returns a TmFmt that outputs according to RFC 822 with Zulu time.
- ///
- /// local: "Thu, 22 Mar 2012 07:53:18 -0700"
- /// utc: "Thu, 22 Mar 2012 14:53:18 -0000"
- pub fn rfc822z(&self) -> TmFmt {
- TmFmt {
- tm: self,
- format: FmtStr("%a, %d %b %Y %T %z"),
- }
- }
-
- /// Returns a TmFmt that outputs according to RFC 3339. RFC 3339 is
- /// compatible with ISO 8601.
- ///
- /// local: "2012-02-22T07:53:18-07:00"
- /// utc: "2012-02-22T14:53:18Z"
- pub fn rfc3339<'a>(&'a self) -> TmFmt {
- TmFmt {
- tm: self,
- format: FmtRfc3339,
- }
- }
-}
-
-#[deriving(Copy, PartialEq)]
-pub enum ParseError {
- InvalidSecond,
- InvalidMinute,
- InvalidHour,
- InvalidDay,
- InvalidMonth,
- InvalidYear,
- InvalidDayOfWeek,
- InvalidDayOfMonth,
- InvalidDayOfYear,
- InvalidZoneOffset,
- InvalidTime,
- MissingFormatConverter,
- InvalidFormatSpecifier(char),
- UnexpectedCharacter(char, char),
-}
-
-impl Show for ParseError {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- InvalidSecond => write!(f, "Invalid second."),
- InvalidMinute => write!(f, "Invalid minute."),
- InvalidHour => write!(f, "Invalid hour."),
- InvalidDay => write!(f, "Invalid day."),
- InvalidMonth => write!(f, "Invalid month."),
- InvalidYear => write!(f, "Invalid year."),
- InvalidDayOfWeek => write!(f, "Invalid day of the week."),
- InvalidDayOfMonth => write!(f, "Invalid day of the month."),
- InvalidDayOfYear => write!(f, "Invalid day of the year."),
- InvalidZoneOffset => write!(f, "Invalid zone offset."),
- InvalidTime => write!(f, "Invalid time."),
- MissingFormatConverter => write!(f, "Missing format converter after `%`"),
- InvalidFormatSpecifier(ch) => write!(f, "Invalid format specifier: %{}", ch),
- UnexpectedCharacter(a, b) => write!(f, "Expected: {}, found: {}.", a, b),
- }
- }
-}
-
-/// A wrapper around a `Tm` and format string that implements Show.
-pub struct TmFmt<'a> {
- tm: &'a Tm,
- format: Fmt<'a>
-}
-
-enum Fmt<'a> {
- FmtStr(&'a str),
- FmtRfc3339,
- FmtCtime,
-}
-
-fn validate_format<'a>(fmt: TmFmt<'a>) -> Result<TmFmt<'a>, ParseError> {
-
- match (fmt.tm.tm_wday, fmt.tm.tm_mon) {
- (0...6, 0...11) => (),
- (_wday, 0...11) => return Err(InvalidDayOfWeek),
- (0...6, _mon) => return Err(InvalidMonth),
- _ => return Err(InvalidDay)
- }
- match fmt.format {
- FmtStr(ref s) => {
- let mut chars = s.chars();
- loop {
- match chars.next() {
- Some('%') => {
- match chars.next() {
- Some('A') |
- Some('a') |
- Some('B') |
- Some('b') |
- Some('C') |
- Some('c') |
- Some('D') |
- Some('d') |
- Some('e') |
- Some('F') |
- Some('f') |
- Some('G') |
- Some('g') |
- Some('H') |
- Some('h') |
- Some('I') |
- Some('j') |
- Some('k') |
- Some('l') |
- Some('M') |
- Some('m') |
- Some('n') |
- Some('P') |
- Some('p') |
- Some('R') |
- Some('r') |
- Some('S') |
- Some('s') |
- Some('T') |
- Some('t') |
- Some('U') |
- Some('u') |
- Some('V') |
- Some('v') |
- Some('W') |
- Some('w') |
- Some('X') |
- Some('x') |
- Some('Y') |
- Some('y') |
- Some('Z') |
- Some('z') |
- Some('+') |
- Some('%')
- => (),
- Some(c) => return Err(InvalidFormatSpecifier(c)),
- None => return Err(MissingFormatConverter),
- }
- },
- None => break,
- _ => ()
- }
- }
- },
- _ => ()
- }
- Ok(fmt)
-}
-
-impl<'a> fmt::Show for TmFmt<'a> {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fn days_in_year(year: int) -> i32 {
- if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
- 366 /* Days in a leap year */
- } else {
- 365 /* Days in a non-leap year */
- }
- }
-
- fn iso_week_days(yday: i32, wday: i32) -> int {
- /* The number of days from the first day of the first ISO week of this
- * year to the year day YDAY with week day WDAY.
- * ISO weeks start on Monday. The first ISO week has the year's first
- * Thursday.
- * YDAY may be as small as yday_minimum.
- */
- let yday: int = yday as int;
- let wday: int = wday as int;
- let iso_week_start_wday: int = 1; /* Monday */
- let iso_week1_wday: int = 4; /* Thursday */
- let yday_minimum: int = 366;
- /* Add enough to the first operand of % to make it nonnegative. */
- let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
-
- yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
- + iso_week1_wday - iso_week_start_wday
- }
-
- fn iso_week(fmt: &mut fmt::Formatter, ch:char, tm: &Tm) -> fmt::Result {
- let mut year: int = tm.tm_year as int + 1900;
- let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);
-
- if days < 0 {
- /* This ISO week belongs to the previous year. */
- year -= 1;
- days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
- } else {
- let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
- tm.tm_wday);
- if 0 <= d {
- /* This ISO week belongs to the next year. */
- year += 1;
- days = d;
- }
- }
-
- match ch {
- 'G' => write!(fmt, "{}", year),
- 'g' => write!(fmt, "{:02}", (year % 100 + 100) % 100),
- 'V' => write!(fmt, "{:02}", days / 7 + 1),
- _ => Ok(())
- }
- }
-
- fn parse_type(fmt: &mut fmt::Formatter, ch: char, tm: &Tm) -> fmt::Result {
- let die = |&:| {
- unreachable!()
- };
- match ch {
- 'A' => match tm.tm_wday as int {
- 0 => "Sunday",
- 1 => "Monday",
- 2 => "Tuesday",
- 3 => "Wednesday",
- 4 => "Thursday",
- 5 => "Friday",
- 6 => "Saturday",
- _ => return die()
- },
- 'a' => match tm.tm_wday as int {
- 0 => "Sun",
- 1 => "Mon",
- 2 => "Tue",
- 3 => "Wed",
- 4 => "Thu",
- 5 => "Fri",
- 6 => "Sat",
- _ => return die()
- },
- 'B' => match tm.tm_mon as int {
- 0 => "January",
- 1 => "February",
- 2 => "March",
- 3 => "April",
- 4 => "May",
- 5 => "June",
- 6 => "July",
- 7 => "August",
- 8 => "September",
- 9 => "October",
- 10 => "November",
- 11 => "December",
- _ => return die()
- },
- 'b' | 'h' => match tm.tm_mon as int {
- 0 => "Jan",
- 1 => "Feb",
- 2 => "Mar",
- 3 => "Apr",
- 4 => "May",
- 5 => "Jun",
- 6 => "Jul",
- 7 => "Aug",
- 8 => "Sep",
- 9 => "Oct",
- 10 => "Nov",
- 11 => "Dec",
- _ => return die()
- },
- 'C' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) / 100),
- 'c' => {
- try!(parse_type(fmt, 'a', tm));
- try!(' '.fmt(fmt));
- try!(parse_type(fmt, 'b', tm));
- try!(' '.fmt(fmt));
- try!(parse_type(fmt, 'e', tm));
- try!(' '.fmt(fmt));
- try!(parse_type(fmt, 'T', tm));
- try!(' '.fmt(fmt));
- return parse_type(fmt, 'Y', tm);
- }
- 'D' | 'x' => {
- try!(parse_type(fmt, 'm', tm));
- try!('/'.fmt(fmt));
- try!(parse_type(fmt, 'd', tm));
- try!('/'.fmt(fmt));
- return parse_type(fmt, 'y', tm);
- }
- 'd' => return write!(fmt, "{:02}", tm.tm_mday),
- 'e' => return write!(fmt, "{:2}", tm.tm_mday),
- 'f' => return write!(fmt, "{:09}", tm.tm_nsec),
- 'F' => {
- try!(parse_type(fmt, 'Y', tm));
- try!('-'.fmt(fmt));
- try!(parse_type(fmt, 'm', tm));
- try!('-'.fmt(fmt));
- return parse_type(fmt, 'd', tm);
- }
- 'G' => return iso_week(fmt, 'G', tm),
- 'g' => return iso_week(fmt, 'g', tm),
- 'H' => return write!(fmt, "{:02}", tm.tm_hour),
- 'I' => {
- let mut h = tm.tm_hour;
- if h == 0 { h = 12 }
- if h > 12 { h -= 12 }
- return write!(fmt, "{:02}", h)
- }
- 'j' => return write!(fmt, "{:03}", tm.tm_yday + 1),
- 'k' => return write!(fmt, "{:2}", tm.tm_hour),
- 'l' => {
- let mut h = tm.tm_hour;
- if h == 0 { h = 12 }
- if h > 12 { h -= 12 }
- return write!(fmt, "{:2}", h)
- }
- 'M' => return write!(fmt, "{:02}", tm.tm_min),
- 'm' => return write!(fmt, "{:02}", tm.tm_mon + 1),
- 'n' => "\n",
- 'P' => if (tm.tm_hour as int) < 12 { "am" } else { "pm" },
- 'p' => if (tm.tm_hour as int) < 12 { "AM" } else { "PM" },
- 'R' => {
- try!(parse_type(fmt, 'H', tm));
- try!(':'.fmt(fmt));
- return parse_type(fmt, 'M', tm);
- }
- 'r' => {
- try!(parse_type(fmt, 'I', tm));
- try!(':'.fmt(fmt));
- try!(parse_type(fmt, 'M', tm));
- try!(':'.fmt(fmt));
- try!(parse_type(fmt, 'S', tm));
- try!(' '.fmt(fmt));
- return parse_type(fmt, 'p', tm);
- }
- 'S' => return write!(fmt, "{:02}", tm.tm_sec),
- 's' => return write!(fmt, "{}", tm.to_timespec().sec),
- 'T' | 'X' => {
- try!(parse_type(fmt, 'H', tm));
- try!(':'.fmt(fmt));
- try!(parse_type(fmt, 'M', tm));
- try!(':'.fmt(fmt));
- return parse_type(fmt, 'S', tm);
- }
- 't' => "\t",
- 'U' => return write!(fmt, "{:02}", (tm.tm_yday - tm.tm_wday + 7) / 7),
- 'u' => {
- let i = tm.tm_wday as int;
- return (if i == 0 { 7 } else { i }).fmt(fmt);
- }
- 'V' => return iso_week(fmt, 'V', tm),
- 'v' => {
- try!(parse_type(fmt, 'e', tm));
- try!('-'.fmt(fmt));
- try!(parse_type(fmt, 'b', tm));
- try!('-'.fmt(fmt));
- return parse_type(fmt, 'Y', tm);
- }
- 'W' => {
- return write!(fmt, "{:02}",
- (tm.tm_yday - (tm.tm_wday - 1 + 7) % 7 + 7) / 7)
- }
- 'w' => return (tm.tm_wday as int).fmt(fmt),
- 'Y' => return (tm.tm_year as int + 1900).fmt(fmt),
- 'y' => return write!(fmt, "{:02}", (tm.tm_year as int + 1900) % 100),
- 'Z' => if tm.tm_gmtoff == 0_i32 { "GMT"} else { "" }, // FIXME (#2350): support locale
- 'z' => {
- let sign = if tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
- let mut m = tm.tm_gmtoff.abs() / 60_i32;
- let h = m / 60_i32;
- m -= h * 60_i32;
- return write!(fmt, "{}{:02}{:02}", sign, h, m);
- }
- '+' => return tm.rfc3339().fmt(fmt),
- '%' => "%",
- _ => return die()
- }.fmt(fmt)
- }
-
- match self.format {
- FmtStr(ref s) => {
- let mut chars = s.chars();
- loop {
- match chars.next() {
- Some('%') => {
- // we've already validated that % always precedes another char
- try!(parse_type(fmt, chars.next().unwrap(), self.tm));
- }
- Some(ch) => try!(ch.fmt(fmt)),
- None => break,
- }
- }
-
- Ok(())
- }
- FmtCtime => {
- self.tm.to_local().asctime().fmt(fmt)
- }
- FmtRfc3339 => {
- if self.tm.tm_gmtoff == 0_i32 {
- TmFmt {
- tm: self.tm,
- format: FmtStr("%Y-%m-%dT%H:%M:%SZ"),
- }.fmt(fmt)
- } else {
- let s = TmFmt {
- tm: self.tm,
- format: FmtStr("%Y-%m-%dT%H:%M:%S"),
- };
- let sign = if self.tm.tm_gmtoff > 0_i32 { '+' } else { '-' };
- let mut m = self.tm.tm_gmtoff.abs() / 60_i32;
- let h = m / 60_i32;
- m -= h * 60_i32;
- write!(fmt, "{}{}{:02}:{:02}", s, sign, h as int, m as int)
- }
- }
- }
- }
-}
-
-/// Parses the time from the string according to the format string.
-pub fn strptime(s: &str, format: &str) -> Result<Tm, ParseError> {
- fn match_str(s: &str, pos: uint, needle: &str) -> bool {
- s.slice_from(pos).starts_with(needle)
- }
-
- fn match_strs(ss: &str, pos: uint, strs: &[(&str, i32)])
- -> Option<(i32, uint)> {
- for &(needle, value) in strs.iter() {
- if match_str(ss, pos, needle) {
- return Some((value, pos + needle.len()));
- }
- }
-
- None
- }
-
- fn match_digits(ss: &str, pos: uint, digits: uint, ws: bool)
- -> Option<(i32, uint)> {
- let mut pos = pos;
- let len = ss.len();
- let mut value = 0_i32;
-
- let mut i = 0u;
- while i < digits {
- if pos >= len {
- return None;
- }
- let range = ss.char_range_at(pos);
- pos = range.next;
-
- match range.ch {
- '0' ... '9' => {
- value = value * 10_i32 + (range.ch as i32 - '0' as i32);
- }
- ' ' if ws => (),
- _ => return None
- }
- i += 1u;
- }
-
- Some((value, pos))
- }
-
- fn match_fractional_seconds(ss: &str, pos: uint) -> (i32, uint) {
- let len = ss.len();
- let mut value = 0_i32;
- let mut multiplier = NSEC_PER_SEC / 10;
- let mut pos = pos;
-
- loop {
- if pos >= len {
- break;
- }
- let range = ss.char_range_at(pos);
-
- match range.ch {
- '0' ... '9' => {
- pos = range.next;
- // This will drop digits after the nanoseconds place
- let digit = range.ch as i32 - '0' as i32;
- value += digit * multiplier;
- multiplier /= 10;
- }
- _ => break
- }
- }
-
- (value, pos)
- }
-
- fn match_digits_in_range(ss: &str, pos: uint, digits: uint, ws: bool,
- min: i32, max: i32) -> Option<(i32, uint)> {
- match match_digits(ss, pos, digits, ws) {
- Some((val, pos)) if val >= min && val <= max => {
- Some((val, pos))
- }
- _ => None
- }
- }
-
- fn parse_char(s: &str, pos: uint, c: char) -> Result<uint, ParseError> {
- let range = s.char_range_at(pos);
-
- if c == range.ch {
- Ok(range.next)
- } else {
- Err(UnexpectedCharacter(c, range.ch))
- }
- }
-
- fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm)
- -> Result<uint, ParseError> {
- match ch {
- 'A' => match match_strs(s, pos, &[
- ("Sunday", 0_i32),
- ("Monday", 1_i32),
- ("Tuesday", 2_i32),
- ("Wednesday", 3_i32),
- ("Thursday", 4_i32),
- ("Friday", 5_i32),
- ("Saturday", 6_i32)
- ]) {
- Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
- None => Err(InvalidDay)
- },
- 'a' => match match_strs(s, pos, &[
- ("Sun", 0_i32),
- ("Mon", 1_i32),
- ("Tue", 2_i32),
- ("Wed", 3_i32),
- ("Thu", 4_i32),
- ("Fri", 5_i32),
- ("Sat", 6_i32)
- ]) {
- Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
- None => Err(InvalidDay)
- },
- 'B' => match match_strs(s, pos, &[
- ("January", 0_i32),
- ("February", 1_i32),
- ("March", 2_i32),
- ("April", 3_i32),
- ("May", 4_i32),
- ("June", 5_i32),
- ("July", 6_i32),
- ("August", 7_i32),
- ("September", 8_i32),
- ("October", 9_i32),
- ("November", 10_i32),
- ("December", 11_i32)
- ]) {
- Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
- None => Err(InvalidMonth)
- },
- 'b' | 'h' => match match_strs(s, pos, &[
- ("Jan", 0_i32),
- ("Feb", 1_i32),
- ("Mar", 2_i32),
- ("Apr", 3_i32),
- ("May", 4_i32),
- ("Jun", 5_i32),
- ("Jul", 6_i32),
- ("Aug", 7_i32),
- ("Sep", 8_i32),
- ("Oct", 9_i32),
- ("Nov", 10_i32),
- ("Dec", 11_i32)
- ]) {
- Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) }
- None => Err(InvalidMonth)
- },
- 'C' => match match_digits_in_range(s, pos, 2u, false, 0_i32,
- 99_i32) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_year += (v * 100_i32) - 1900_i32;
- Ok(pos)
- }
- None => Err(InvalidYear)
- },
- 'c' => {
- parse_type(s, pos, 'a', &mut *tm)
- .and_then(|pos| parse_char(s, pos, ' '))
- .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
- .and_then(|pos| parse_char(s, pos, ' '))
- .and_then(|pos| parse_type(s, pos, 'e', &mut *tm))
- .and_then(|pos| parse_char(s, pos, ' '))
- .and_then(|pos| parse_type(s, pos, 'T', &mut *tm))
- .and_then(|pos| parse_char(s, pos, ' '))
- .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
- }
- 'D' | 'x' => {
- parse_type(s, pos, 'm', &mut *tm)
- .and_then(|pos| parse_char(s, pos, '/'))
- .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
- .and_then(|pos| parse_char(s, pos, '/'))
- .and_then(|pos| parse_type(s, pos, 'y', &mut *tm))
- }
- 'd' => match match_digits_in_range(s, pos, 2u, false, 1_i32,
- 31_i32) {
- Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
- None => Err(InvalidDayOfMonth)
- },
- 'e' => match match_digits_in_range(s, pos, 2u, true, 1_i32,
- 31_i32) {
- Some(item) => { let (v, pos) = item; tm.tm_mday = v; Ok(pos) }
- None => Err(InvalidDayOfMonth)
- },
- 'f' => {
- let (val, pos) = match_fractional_seconds(s, pos);
- tm.tm_nsec = val;
- Ok(pos)
- }
- 'F' => {
- parse_type(s, pos, 'Y', &mut *tm)
- .and_then(|pos| parse_char(s, pos, '-'))
- .and_then(|pos| parse_type(s, pos, 'm', &mut *tm))
- .and_then(|pos| parse_char(s, pos, '-'))
- .and_then(|pos| parse_type(s, pos, 'd', &mut *tm))
- }
- 'H' => {
- match match_digits_in_range(s, pos, 2u, false, 0_i32, 23_i32) {
- Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
- None => Err(InvalidHour)
- }
- }
- 'I' => {
- match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
- Ok(pos)
- }
- None => Err(InvalidHour)
- }
- }
- 'j' => {
- match match_digits_in_range(s, pos, 3u, false, 1_i32, 366_i32) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_yday = v - 1_i32;
- Ok(pos)
- }
- None => Err(InvalidDayOfYear)
- }
- }
- 'k' => {
- match match_digits_in_range(s, pos, 2u, true, 0_i32, 23_i32) {
- Some(item) => { let (v, pos) = item; tm.tm_hour = v; Ok(pos) }
- None => Err(InvalidHour)
- }
- }
- 'l' => {
- match match_digits_in_range(s, pos, 2u, true, 1_i32, 12_i32) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_hour = if v == 12_i32 { 0_i32 } else { v };
- Ok(pos)
- }
- None => Err(InvalidHour)
- }
- }
- 'M' => {
- match match_digits_in_range(s, pos, 2u, false, 0_i32, 59_i32) {
- Some(item) => { let (v, pos) = item; tm.tm_min = v; Ok(pos) }
- None => Err(InvalidMinute)
- }
- }
- 'm' => {
- match match_digits_in_range(s, pos, 2u, false, 1_i32, 12_i32) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_mon = v - 1_i32;
- Ok(pos)
- }
- None => Err(InvalidMonth)
- }
- }
- 'n' => parse_char(s, pos, '\n'),
- 'P' => match match_strs(s, pos,
- &[("am", 0_i32), ("pm", 12_i32)]) {
-
- Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
- None => Err(InvalidHour)
- },
- 'p' => match match_strs(s, pos,
- &[("AM", 0_i32), ("PM", 12_i32)]) {
-
- Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) }
- None => Err(InvalidHour)
- },
- 'R' => {
- parse_type(s, pos, 'H', &mut *tm)
- .and_then(|pos| parse_char(s, pos, ':'))
- .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
- }
- 'r' => {
- parse_type(s, pos, 'I', &mut *tm)
- .and_then(|pos| parse_char(s, pos, ':'))
- .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
- .and_then(|pos| parse_char(s, pos, ':'))
- .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
- .and_then(|pos| parse_char(s, pos, ' '))
- .and_then(|pos| parse_type(s, pos, 'p', &mut *tm))
- }
- 'S' => {
- match match_digits_in_range(s, pos, 2u, false, 0_i32, 60_i32) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_sec = v;
- Ok(pos)
- }
- None => Err(InvalidSecond)
- }
- }
- //'s' {}
- 'T' | 'X' => {
- parse_type(s, pos, 'H', &mut *tm)
- .and_then(|pos| parse_char(s, pos, ':'))
- .and_then(|pos| parse_type(s, pos, 'M', &mut *tm))
- .and_then(|pos| parse_char(s, pos, ':'))
- .and_then(|pos| parse_type(s, pos, 'S', &mut *tm))
- }
- 't' => parse_char(s, pos, '\t'),
- 'u' => {
- match match_digits_in_range(s, pos, 1u, false, 1_i32, 7_i32) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_wday = if v == 7 { 0 } else { v };
- Ok(pos)
- }
- None => Err(InvalidDayOfWeek)
- }
- }
- 'v' => {
- parse_type(s, pos, 'e', &mut *tm)
- .and_then(|pos| parse_char(s, pos, '-'))
- .and_then(|pos| parse_type(s, pos, 'b', &mut *tm))
- .and_then(|pos| parse_char(s, pos, '-'))
- .and_then(|pos| parse_type(s, pos, 'Y', &mut *tm))
- }
- //'W' {}
- 'w' => {
- match match_digits_in_range(s, pos, 1u, false, 0_i32, 6_i32) {
- Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) }
- None => Err(InvalidDayOfWeek)
- }
- }
- 'Y' => {
- match match_digits(s, pos, 4u, false) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_year = v - 1900_i32;
- Ok(pos)
- }
- None => Err(InvalidYear)
- }
- }
- 'y' => {
- match match_digits_in_range(s, pos, 2u, false, 0_i32, 99_i32) {
- Some(item) => {
- let (v, pos) = item;
- tm.tm_year = v;
- Ok(pos)
- }
- None => Err(InvalidYear)
- }
- }
- 'Z' => {
- if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
- tm.tm_gmtoff = 0_i32;
- Ok(pos + 3u)
- } else {
- // It's odd, but to maintain compatibility with c's
- // strptime we ignore the timezone.
- let mut pos = pos;
- let len = s.len();
- while pos < len {
- let range = s.char_range_at(pos);
- pos = range.next;
- if range.ch == ' ' { break; }
- }
-
- Ok(pos)
- }
- }
- 'z' => {
- let range = s.char_range_at(pos);
-
- if range.ch == '+' || range.ch == '-' {
- match match_digits(s, range.next, 4u, false) {
- Some(item) => {
- let (v, pos) = item;
- if v == 0_i32 {
- tm.tm_gmtoff = 0_i32;
- }
-
- Ok(pos)
- }
- None => Err(InvalidZoneOffset)
- }
- } else {
- Err(InvalidZoneOffset)
- }
- }
- '%' => parse_char(s, pos, '%'),
- ch => Err(InvalidFormatSpecifier(ch))
- }
- }
-
- let mut rdr: &[u8] = format.as_bytes();
- let mut tm = Tm {
- tm_sec: 0_i32,
- tm_min: 0_i32,
- tm_hour: 0_i32,
- tm_mday: 0_i32,
- tm_mon: 0_i32,
- tm_year: 0_i32,
- tm_wday: 0_i32,
- tm_yday: 0_i32,
- tm_isdst: 0_i32,
- tm_gmtoff: 0_i32,
- tm_nsec: 0_i32,
- };
- let mut pos = 0u;
- let len = s.len();
- let mut result = Err(InvalidTime);
-
- while pos < len {
- let range = s.char_range_at(pos);
- let ch = range.ch;
- let next = range.next;
-
- let mut buf = [0];
- let c = match (&mut rdr).read(&mut buf) {
- Ok(..) => buf[0] as char,
- Err(..) => break
- };
- match c {
- '%' => {
- let ch = match (&mut rdr).read(&mut buf) {
- Ok(..) => buf[0] as char,
- Err(..) => break
- };
- match parse_type(s, pos, ch, &mut tm) {
- Ok(next) => pos = next,
- Err(e) => { result = Err(e); break; }
- }
- },
- c => {
- if c != ch { break }
- pos = next;
- }
- }
- }
-
- if pos == len && (&mut rdr).is_empty() {
- Ok(Tm {
- tm_sec: tm.tm_sec,
- tm_min: tm.tm_min,
- tm_hour: tm.tm_hour,
- tm_mday: tm.tm_mday,
- tm_mon: tm.tm_mon,
- tm_year: tm.tm_year,
- tm_wday: tm.tm_wday,
- tm_yday: tm.tm_yday,
- tm_isdst: tm.tm_isdst,
- tm_gmtoff: tm.tm_gmtoff,
- tm_nsec: tm.tm_nsec,
- })
- } else { result }
-}
-
-/// Formats the time according to the format string.
-pub fn strftime(format: &str, tm: &Tm) -> Result<String, ParseError> {
- tm.strftime(format).map(|fmt| fmt.to_string())
-}
-
-#[cfg(test)]
-mod tests {
- extern crate test;
- use super::{Timespec, InvalidTime, InvalidYear, get_time, precise_time_ns,
- precise_time_s, tzset, at_utc, at, strptime, MissingFormatConverter,
- InvalidFormatSpecifier};
-
- use std::f64;
- use std::result::Result::{Err, Ok};
- use std::time::Duration;
- use self::test::Bencher;
-
- #[cfg(windows)]
- fn set_time_zone() {
- use libc;
- use std::c_str::ToCStr;
- // Windows crt doesn't see any environment variable set by
- // `SetEnvironmentVariable`, which `os::setenv` internally uses.
- // It is why we use `putenv` here.
- extern {
- fn _putenv(envstring: *const libc::c_char) -> libc::c_int;
- }
-
- unsafe {
- // Windows does not understand "America/Los_Angeles".
- // PST+08 may look wrong, but not! "PST" indicates
- // the name of timezone. "+08" means UTC = local + 08.
- "TZ=PST+08".with_c_str(|env| {
- _putenv(env);
- })
- }
- tzset();
- }
- #[cfg(not(windows))]
- fn set_time_zone() {
- use std::os;
- os::setenv("TZ", "America/Los_Angeles");
- tzset();
- }
-
- fn test_get_time() {
- static SOME_RECENT_DATE: i64 = 1325376000i64; // 2012-01-01T00:00:00Z
- static SOME_FUTURE_DATE: i64 = 1577836800i64; // 2020-01-01T00:00:00Z
-
- let tv1 = get_time();
- debug!("tv1={} sec + {} nsec", tv1.sec as uint, tv1.nsec as uint);
-
- assert!(tv1.sec > SOME_RECENT_DATE);
- assert!(tv1.nsec < 1000000000i32);
-
- let tv2 = get_time();
- debug!("tv2={} sec + {} nsec", tv2.sec as uint, tv2.nsec as uint);
-
- assert!(tv2.sec >= tv1.sec);
- assert!(tv2.sec < SOME_FUTURE_DATE);
- assert!(tv2.nsec < 1000000000i32);
- if tv2.sec == tv1.sec {
- assert!(tv2.nsec >= tv1.nsec);
- }
- }
-
- fn test_precise_time() {
- let s0 = precise_time_s();
- debug!("s0={} sec", f64::to_str_digits(s0, 9u));
- assert!(s0 > 0.);
-
- let ns0 = precise_time_ns();
- let ns1 = precise_time_ns();
- debug!("ns0={} ns", ns0);
- debug!("ns1={} ns", ns1);
- assert!(ns1 >= ns0);
-
- let ns2 = precise_time_ns();
- debug!("ns2={} ns", ns2);
- assert!(ns2 >= ns1);
- }
-
- fn test_at_utc() {
- set_time_zone();
-
- let time = Timespec::new(1234567890, 54321);
- let utc = at_utc(time);
-
- assert_eq!(utc.tm_sec, 30_i32);
- assert_eq!(utc.tm_min, 31_i32);
- assert_eq!(utc.tm_hour, 23_i32);
- assert_eq!(utc.tm_mday, 13_i32);
- assert_eq!(utc.tm_mon, 1_i32);
- assert_eq!(utc.tm_year, 109_i32);
- assert_eq!(utc.tm_wday, 5_i32);
- assert_eq!(utc.tm_yday, 43_i32);
- assert_eq!(utc.tm_isdst, 0_i32);
- assert_eq!(utc.tm_gmtoff, 0_i32);
- assert_eq!(utc.tm_nsec, 54321_i32);
- }
-
- fn test_at() {
- set_time_zone();
-
- let time = Timespec::new(1234567890, 54321);
- let local = at(time);
-
- debug!("time_at: {}", local);
-
- assert_eq!(local.tm_sec, 30_i32);
- assert_eq!(local.tm_min, 31_i32);
- assert_eq!(local.tm_hour, 15_i32);
- assert_eq!(local.tm_mday, 13_i32);
- assert_eq!(local.tm_mon, 1_i32);
- assert_eq!(local.tm_year, 109_i32);
- assert_eq!(local.tm_wday, 5_i32);
- assert_eq!(local.tm_yday, 43_i32);
- assert_eq!(local.tm_isdst, 0_i32);
- assert_eq!(local.tm_gmtoff, -28800_i32);
- assert_eq!(local.tm_nsec, 54321_i32);
- }
-
- fn test_to_timespec() {
- set_time_zone();
-
- let time = Timespec::new(1234567890, 54321);
- let utc = at_utc(time);
-
- assert_eq!(utc.to_timespec(), time);
- assert_eq!(utc.to_local().to_timespec(), time);
- }
-
- fn test_conversions() {
- set_time_zone();
-
- let time = Timespec::new(1234567890, 54321);
- let utc = at_utc(time);
- let local = at(time);
-
- assert!(local.to_local() == local);
- assert!(local.to_utc() == utc);
- assert!(local.to_utc().to_local() == local);
- assert!(utc.to_utc() == utc);
- assert!(utc.to_local() == local);
- assert!(utc.to_local().to_utc() == utc);
- }
-
- fn test_strptime() {
- set_time_zone();
-
- match strptime("", "") {
- Ok(ref tm) => {
- assert!(tm.tm_sec == 0_i32);
- assert!(tm.tm_min == 0_i32);
- assert!(tm.tm_hour == 0_i32);
- assert!(tm.tm_mday == 0_i32);
- assert!(tm.tm_mon == 0_i32);
- assert!(tm.tm_year == 0_i32);
- assert!(tm.tm_wday == 0_i32);
- assert!(tm.tm_isdst == 0_i32);
- assert!(tm.tm_gmtoff == 0_i32);
- assert!(tm.tm_nsec == 0_i32);
- }
- Err(_) => ()
- }
-
- let format = "%a %b %e %T.%f %Y";
- assert_eq!(strptime("", format), Err(InvalidTime));
- assert!(strptime("Fri Feb 13 15:31:30", format)
- == Err(InvalidTime));
-
- match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
- Err(e) => panic!(e),
- Ok(ref tm) => {
- assert!(tm.tm_sec == 30_i32);
- assert!(tm.tm_min == 31_i32);
- assert!(tm.tm_hour == 15_i32);
- assert!(tm.tm_mday == 13_i32);
- assert!(tm.tm_mon == 1_i32);
- assert!(tm.tm_year == 109_i32);
- assert!(tm.tm_wday == 5_i32);
- assert!(tm.tm_yday == 0_i32);
- assert!(tm.tm_isdst == 0_i32);
- assert!(tm.tm_gmtoff == 0_i32);
- assert!(tm.tm_nsec == 12340000_i32);
- }
- }
-
- fn test(s: &str, format: &str) -> bool {
- match strptime(s, format) {
- Ok(ref tm) => {
- tm.strftime(format).unwrap().to_string() == s.to_string()
- },
- Err(e) => panic!(e)
- }
- }
-
- let days = [
- "Sunday".to_string(),
- "Monday".to_string(),
- "Tuesday".to_string(),
- "Wednesday".to_string(),
- "Thursday".to_string(),
- "Friday".to_string(),
- "Saturday".to_string()
- ];
- for day in days.iter() {
- assert!(test(day.as_slice(), "%A"));
- }
-
- let days = [
- "Sun".to_string(),
- "Mon".to_string(),
- "Tue".to_string(),
- "Wed".to_string(),
- "Thu".to_string(),
- "Fri".to_string(),
- "Sat".to_string()
- ];
- for day in days.iter() {
- assert!(test(day.as_slice(), "%a"));
- }
-
- let months = [
- "January".to_string(),
- "February".to_string(),
- "March".to_string(),
- "April".to_string(),
- "May".to_string(),
- "June".to_string(),
- "July".to_string(),
- "August".to_string(),
- "September".to_string(),
- "October".to_string(),
- "November".to_string(),
- "December".to_string()
- ];
- for day in months.iter() {
- assert!(test(day.as_slice(), "%B"));
- }
-
- let months = [
- "Jan".to_string(),
- "Feb".to_string(),
- "Mar".to_string(),
- "Apr".to_string(),
- "May".to_string(),
- "Jun".to_string(),
- "Jul".to_string(),
- "Aug".to_string(),
- "Sep".to_string(),
- "Oct".to_string(),
- "Nov".to_string(),
- "Dec".to_string()
- ];
- for day in months.iter() {
- assert!(test(day.as_slice(), "%b"));
- }
-
- assert!(test("19", "%C"));
- assert!(test("Fri Feb 13 23:31:30 2009", "%c"));
- assert!(test("02/13/09", "%D"));
- assert!(test("03", "%d"));
- assert!(test("13", "%d"));
- assert!(test(" 3", "%e"));
- assert!(test("13", "%e"));
- assert!(test("2009-02-13", "%F"));
- assert!(test("03", "%H"));
- assert!(test("13", "%H"));
- assert!(test("03", "%I")); // FIXME (#2350): flesh out
- assert!(test("11", "%I")); // FIXME (#2350): flesh out
- assert!(test("044", "%j"));
- assert!(test(" 3", "%k"));
- assert!(test("13", "%k"));
- assert!(test(" 1", "%l"));
- assert!(test("11", "%l"));
- assert!(test("03", "%M"));
- assert!(test("13", "%M"));
- assert!(test("\n", "%n"));
- assert!(test("am", "%P"));
- assert!(test("pm", "%P"));
- assert!(test("AM", "%p"));
- assert!(test("PM", "%p"));
- assert!(test("23:31", "%R"));
- assert!(test("11:31:30 AM", "%r"));
- assert!(test("11:31:30 PM", "%r"));
- assert!(test("03", "%S"));
- assert!(test("13", "%S"));
- assert!(test("15:31:30", "%T"));
- assert!(test("\t", "%t"));
- assert!(test("1", "%u"));
- assert!(test("7", "%u"));
- assert!(test("13-Feb-2009", "%v"));
- assert!(test("0", "%w"));
- assert!(test("6", "%w"));
- assert!(test("2009", "%Y"));
- assert!(test("09", "%y"));
- assert!(strptime("-0000", "%z").unwrap().tm_gmtoff ==
- 0);
- assert!(strptime("-0800", "%z").unwrap().tm_gmtoff ==
- 0);
- assert!(test("%", "%%"));
-
- // Test for #7256
- assert_eq!(strptime("360", "%Y-%m-%d"), Err(InvalidYear));
- }
-
- fn test_asctime() {
- set_time_zone();
-
- let time = Timespec::new(1234567890, 54321);
- let utc = at_utc(time);
- let local = at(time);
-
- debug!("test_ctime: {} {}", utc.asctime(), local.asctime());
-
- assert_eq!(utc.asctime().to_string(), "Fri Feb 13 23:31:30 2009");
- assert_eq!(local.asctime().to_string(), "Fri Feb 13 15:31:30 2009");
- }
-
- fn test_ctime() {
- set_time_zone();
-
- let time = Timespec::new(1234567890, 54321);
- let utc = at_utc(time);
- let local = at(time);
-
- debug!("test_ctime: {} {}", utc.ctime(), local.ctime());
-
- assert_eq!(utc.ctime().to_string(), "Fri Feb 13 15:31:30 2009");
- assert_eq!(local.ctime().to_string(), "Fri Feb 13 15:31:30 2009");
- }
-
- fn test_strftime() {
- set_time_zone();
-
- let time = Timespec::new(1234567890, 54321);
- let utc = at_utc(time);
- let local = at(time);
-
- assert_eq!(local.strftime("").unwrap().to_string(), "");
- assert_eq!(local.strftime("%A").unwrap().to_string(), "Friday");
- assert_eq!(local.strftime("%a").unwrap().to_string(), "Fri");
- assert_eq!(local.strftime("%B").unwrap().to_string(), "February");
- assert_eq!(local.strftime("%b").unwrap().to_string(), "Feb");
- assert_eq!(local.strftime("%C").unwrap().to_string(), "20");
- assert_eq!(local.strftime("%c").unwrap().to_string(),
- "Fri Feb 13 15:31:30 2009");
- assert_eq!(local.strftime("%D").unwrap().to_string(), "02/13/09");
- assert_eq!(local.strftime("%d").unwrap().to_string(), "13");
- assert_eq!(local.strftime("%e").unwrap().to_string(), "13");
- assert_eq!(local.strftime("%F").unwrap().to_string(), "2009-02-13");
- assert_eq!(local.strftime("%f").unwrap().to_string(), "000054321");
- assert_eq!(local.strftime("%G").unwrap().to_string(), "2009");
- assert_eq!(local.strftime("%g").unwrap().to_string(), "09");
- assert_eq!(local.strftime("%H").unwrap().to_string(), "15");
- assert_eq!(local.strftime("%h").unwrap().to_string(), "Feb");
- assert_eq!(local.strftime("%I").unwrap().to_string(), "03");
- assert_eq!(local.strftime("%j").unwrap().to_string(), "044");
- assert_eq!(local.strftime("%k").unwrap().to_string(), "15");
- assert_eq!(local.strftime("%l").unwrap().to_string(), " 3");
- assert_eq!(local.strftime("%M").unwrap().to_string(), "31");
- assert_eq!(local.strftime("%m").unwrap().to_string(), "02");
- assert_eq!(local.strftime("%n").unwrap().to_string(), "\n");
- assert_eq!(local.strftime("%P").unwrap().to_string(), "pm");
- assert_eq!(local.strftime("%p").unwrap().to_string(), "PM");
- assert_eq!(local.strftime("%R").unwrap().to_string(), "15:31");
- assert_eq!(local.strftime("%r").unwrap().to_string(), "03:31:30 PM");
- assert_eq!(local.strftime("%S").unwrap().to_string(), "30");
- assert_eq!(local.strftime("%s").unwrap().to_string(), "1234567890");
- assert_eq!(local.strftime("%T").unwrap().to_string(), "15:31:30");
- assert_eq!(local.strftime("%t").unwrap().to_string(), "\t");
- assert_eq!(local.strftime("%U").unwrap().to_string(), "06");
- assert_eq!(local.strftime("%u").unwrap().to_string(), "5");
- assert_eq!(local.strftime("%V").unwrap().to_string(), "07");
- assert_eq!(local.strftime("%v").unwrap().to_string(), "13-Feb-2009");
- assert_eq!(local.strftime("%W").unwrap().to_string(), "06");
- assert_eq!(local.strftime("%w").unwrap().to_string(), "5");
- // FIXME (#2350): support locale
- assert_eq!(local.strftime("%X").unwrap().to_string(), "15:31:30");
- // FIXME (#2350): support locale
- assert_eq!(local.strftime("%x").unwrap().to_string(), "02/13/09");
- assert_eq!(local.strftime("%Y").unwrap().to_string(), "2009");
- assert_eq!(local.strftime("%y").unwrap().to_string(), "09");
- // FIXME (#2350): support locale
- assert_eq!(local.strftime("%Z").unwrap().to_string(), "");
- assert_eq!(local.strftime("%z").unwrap().to_string(), "-0800");
- assert_eq!(local.strftime("%+").unwrap().to_string(),
- "2009-02-13T15:31:30-08:00");
- assert_eq!(local.strftime("%%").unwrap().to_string(), "%");
-
- let invalid_specifiers = ["%E", "%J", "%K", "%L", "%N", "%O", "%o", "%Q", "%q"];
- for &sp in invalid_specifiers.iter() {
- assert_eq!(local.strftime(sp).unwrap_err(), InvalidFormatSpecifier(sp.char_at(1)));
- }
- assert_eq!(local.strftime("%").unwrap_err(), MissingFormatConverter);
- assert_eq!(local.strftime("%A %").unwrap_err(), MissingFormatConverter);
-
- assert_eq!(local.asctime().to_string(), "Fri Feb 13 15:31:30 2009");
- assert_eq!(local.ctime().to_string(), "Fri Feb 13 15:31:30 2009");
- assert_eq!(local.rfc822z().to_string(), "Fri, 13 Feb 2009 15:31:30 -0800");
- assert_eq!(local.rfc3339().to_string(), "2009-02-13T15:31:30-08:00");
-
- assert_eq!(utc.asctime().to_string(), "Fri Feb 13 23:31:30 2009");
- assert_eq!(utc.ctime().to_string(), "Fri Feb 13 15:31:30 2009");
- assert_eq!(utc.rfc822().to_string(), "Fri, 13 Feb 2009 23:31:30 GMT");
- assert_eq!(utc.rfc822z().to_string(), "Fri, 13 Feb 2009 23:31:30 -0000");
- assert_eq!(utc.rfc3339().to_string(), "2009-02-13T23:31:30Z");
- }
-
- fn test_timespec_eq_ord() {
- let a = &Timespec::new(-2, 1);
- let b = &Timespec::new(-1, 2);
- let c = &Timespec::new(1, 2);
- let d = &Timespec::new(2, 1);
- let e = &Timespec::new(2, 1);
-
- assert!(d.eq(e));
- assert!(c.ne(e));
-
- assert!(a.lt(b));
- assert!(b.lt(c));
- assert!(c.lt(d));
-
- assert!(a.le(b));
- assert!(b.le(c));
- assert!(c.le(d));
- assert!(d.le(e));
- assert!(e.le(d));
-
- assert!(b.ge(a));
- assert!(c.ge(b));
- assert!(d.ge(c));
- assert!(e.ge(d));
- assert!(d.ge(e));
-
- assert!(b.gt(a));
- assert!(c.gt(b));
- assert!(d.gt(c));
- }
-
- fn test_timespec_add() {
- let a = Timespec::new(1, 2);
- let b = Duration::seconds(2) + Duration::nanoseconds(3);
- let c = a + b;
- assert_eq!(c.sec, 3);
- assert_eq!(c.nsec, 5);
-
- let p = Timespec::new(1, super::NSEC_PER_SEC - 2);
- let q = Duration::seconds(2) + Duration::nanoseconds(2);
- let r = p + q;
- assert_eq!(r.sec, 4);
- assert_eq!(r.nsec, 0);
-
- let u = Timespec::new(1, super::NSEC_PER_SEC - 2);
- let v = Duration::seconds(2) + Duration::nanoseconds(3);
- let w = u + v;
- assert_eq!(w.sec, 4);
- assert_eq!(w.nsec, 1);
-
- let k = Timespec::new(1, 0);
- let l = Duration::nanoseconds(-1);
- let m = k + l;
- assert_eq!(m.sec, 0);
- assert_eq!(m.nsec, 999_999_999);
- }
-
- fn test_timespec_sub() {
- let a = Timespec::new(2, 3);
- let b = Timespec::new(1, 2);
- let c = a - b;
- assert_eq!(c.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 + 1));
-
- let p = Timespec::new(2, 0);
- let q = Timespec::new(1, 2);
- let r = p - q;
- assert_eq!(r.num_nanoseconds(), Some(super::NSEC_PER_SEC as i64 - 2));
-
- let u = Timespec::new(1, 2);
- let v = Timespec::new(2, 3);
- let w = u - v;
- assert_eq!(w.num_nanoseconds(), Some(-super::NSEC_PER_SEC as i64 - 1));
- }
-
- #[test]
- #[cfg_attr(target_os = "android", ignore)] // FIXME #10958
- fn run_tests() {
- // The tests race on tzset. So instead of having many independent
- // tests, we will just call the functions now.
- test_get_time();
- test_precise_time();
- test_at_utc();
- test_at();
- test_to_timespec();
- test_conversions();
- test_strptime();
- test_asctime();
- test_ctime();
- test_strftime();
- test_timespec_eq_ord();
- test_timespec_add();
- test_timespec_sub();
- }
-
- #[bench]
- fn bench_precise_time_ns(b: &mut Bencher) {
- b.iter(|| precise_time_ns())
- }
-}
/// however the converse is not always true due to the above range limits
/// and, as such, should be performed via the `from_u32` function..
pub mod char {
- pub use core::char::{MAX, from_u32, is_digit_radix, to_digit};
- pub use core::char::{from_digit, escape_unicode, escape_default};
- pub use core::char::{len_utf8_bytes, Char};
+ pub use core::char::{MAX, from_u32};
+ pub use core::char::{from_digit};
+ pub use core::char::Char;
pub use normalize::{decompose_canonical, decompose_compatible, compose};
pub use tables::normalization::canonical_combining_class;
pub use tables::UNICODE_VERSION;
- pub use u_char::{is_alphabetic, is_XID_start, is_XID_continue};
- pub use u_char::{is_lowercase, is_uppercase, is_whitespace};
- pub use u_char::{is_alphanumeric, is_control, is_digit};
- pub use u_char::{to_uppercase, to_lowercase, width, UnicodeChar};
+ pub use u_char::UnicodeChar;
}
pub mod str {
pub use u_str::{utf16_items, Utf16Encoder};
}
-// this lets us use #[deriving(..)]
+// this lets us use #[derive(..)]
mod std {
pub use core::clone;
pub use core::cmp;
use core::result::Result::{Ok, Err};
#[allow(non_camel_case_types)]
- #[deriving(Clone)]
+ #[derive(Clone)]
pub enum GraphemeCat {
GC_LV,
GC_LVT,
use core::option::Option;
use tables::{derived_property, property, general_category, conversions, charwidth};
-/// Returns whether the specified `char` is considered a Unicode alphabetic
-/// code point
-#[deprecated = "use UnicodeChar::is_alphabetic"]
-pub fn is_alphabetic(c: char) -> bool {
- c.is_alphabetic()
-}
-
-/// Returns whether the specified `char` satisfies the 'XID_Start' Unicode property
-///
-/// 'XID_Start' is a Unicode Derived Property specified in
-/// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
-/// mostly similar to ID_Start but modified for closure under NFKx.
-#[allow(non_snake_case)]
-#[deprecated = "use UnicodeChar::is_XID_start"]
-pub fn is_XID_start(c: char) -> bool { derived_property::XID_Start(c) }
-
-/// Returns whether the specified `char` satisfies the 'XID_Continue' Unicode property
-///
-/// 'XID_Continue' is a Unicode Derived Property specified in
-/// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
-/// mostly similar to 'ID_Continue' but modified for closure under NFKx.
-#[allow(non_snake_case)]
-#[deprecated = "use UnicodeChar::is_XID_continue"]
-pub fn is_XID_continue(c: char) -> bool { derived_property::XID_Continue(c) }
-
-///
-/// Indicates whether a `char` is in lower case
-///
-/// This is defined according to the terms of the Unicode Derived Core Property 'Lowercase'.
-///
-#[inline]
-#[deprecated = "use UnicodeChar::is_lowercase"]
-pub fn is_lowercase(c: char) -> bool {
- c.is_lowercase()
-}
-
-///
-/// Indicates whether a `char` is in upper case
-///
-/// This is defined according to the terms of the Unicode Derived Core Property 'Uppercase'.
-///
-#[inline]
-#[deprecated = "use UnicodeChar::is_uppercase"]
-pub fn is_uppercase(c: char) -> bool {
- c.is_uppercase()
-}
-
-///
-/// Indicates whether a `char` is whitespace
-///
-/// Whitespace is defined in terms of the Unicode Property 'White_Space'.
-///
-#[inline]
-#[deprecated = "use UnicodeChar::is_whitespace"]
-pub fn is_whitespace(c: char) -> bool {
- c.is_whitespace()
-}
-
-///
-/// Indicates whether a `char` is alphanumeric
-///
-/// Alphanumericness is defined in terms of the Unicode General Categories
-/// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
-///
-#[inline]
-#[deprecated = "use UnicodeChar::is_alphanumeric"]
-pub fn is_alphanumeric(c: char) -> bool {
- c.is_alphanumeric()
-}
-
-///
-/// Indicates whether a `char` is a control code point
-///
-/// Control code points are defined in terms of the Unicode General Category
-/// 'Cc'.
-///
-#[inline]
-#[deprecated = "use UnicodeChar::is_control"]
-pub fn is_control(c: char) -> bool { general_category::Cc(c) }
-
-/// Indicates whether the `char` is numeric (Nd, Nl, or No)
-#[inline]
-#[deprecated = "use UnicodeChar::is_numeric"]
-pub fn is_digit(c: char) -> bool {
- c.is_numeric()
-}
-
-/// Convert a char to its uppercase equivalent
-///
-/// The case-folding performed is the common or simple mapping:
-/// it maps one Unicode codepoint (one char in Rust) to its uppercase equivalent according
-/// to the Unicode database at ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
-/// The additional SpecialCasing.txt is not considered here, as it expands to multiple
-/// codepoints in some cases.
-///
-/// A full reference can be found here
-/// http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
-///
-/// # Return value
-///
-/// Returns the char itself if no conversion was made
-#[inline]
-#[deprecated = "use UnicodeChar::to_uppercase"]
-pub fn to_uppercase(c: char) -> char {
- conversions::to_upper(c)
-}
-
-/// Convert a char to its lowercase equivalent
-///
-/// The case-folding performed is the common or simple mapping
-/// see `to_uppercase` for references and more information
-///
-/// # Return value
-///
-/// Returns the char itself if no conversion if possible
-#[inline]
-#[deprecated = "use UnicodeChar::to_lowercase"]
-pub fn to_lowercase(c: char) -> char {
- conversions::to_lower(c)
-}
-
-/// Returns this character's displayed width in columns, or `None` if it is a
-/// control character other than `'\x00'`.
-///
-/// `is_cjk` determines behavior for characters in the Ambiguous category:
-/// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1.
-/// In CJK contexts, `is_cjk` should be `true`, else it should be `false`.
-/// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
-/// recommends that these characters be treated as 1 column (i.e.,
-/// `is_cjk` = `false`) if the context cannot be reliably determined.
-#[deprecated = "use UnicodeChar::width"]
-pub fn width(c: char, is_cjk: bool) -> Option<uint> {
- charwidth::width(c, is_cjk)
-}
-
/// Useful functions for Unicode characters.
#[experimental = "pending prelude organization"]
pub trait UnicodeChar {
/// alphabetic code point.
fn is_alphabetic(self) -> bool;
- /// Returns whether the specified character satisfies the 'XID_Start'
- /// Unicode property.
- ///
- /// 'XID_Start' is a Unicode Derived Property specified in
- /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
- /// mostly similar to ID_Start but modified for closure under NFKx.
- #[allow(non_snake_case)]
- #[deprecated = "use is_xid_start"]
- fn is_XID_start(self) -> bool;
-
/// Returns whether the specified character satisfies the 'XID_Start'
/// Unicode property.
///
/// mostly similar to ID_Start but modified for closure under NFKx.
fn is_xid_start(self) -> bool;
- /// Returns whether the specified `char` satisfies the 'XID_Continue'
- /// Unicode property.
- ///
- /// 'XID_Continue' is a Unicode Derived Property specified in
- /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
- /// mostly similar to 'ID_Continue' but modified for closure under NFKx.
- #[allow(non_snake_case)]
- #[deprecated = "use is_xid_continue"]
- fn is_XID_continue(self) -> bool;
-
/// Returns whether the specified `char` satisfies the 'XID_Continue'
/// Unicode property.
///
}
}
- #[deprecated = "use is_xid_start"]
- fn is_XID_start(self) -> bool { derived_property::XID_Start(self) }
-
- #[deprecated = "use is_xid_continue"]
- fn is_XID_continue(self) -> bool { derived_property::XID_Continue(self) }
-
fn is_xid_start(self) -> bool { derived_property::XID_Start(self) }
fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) }
}
/// External iterator for grapheme clusters and byte offsets.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct GraphemeIndices<'a> {
start_offset: uint,
iter: Graphemes<'a>,
/// External iterator for a string's
/// [grapheme clusters](http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries).
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Graphemes<'a> {
string: &'a str,
extended: bool,
}
// state machine for cluster boundary rules
-#[deriving(PartialEq,Eq)]
+#[derive(PartialEq,Eq)]
enum GraphemeState {
Start,
FindExtend,
/// An iterator that decodes UTF-16 encoded codepoints from a vector
/// of `u16`s.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Utf16Items<'a> {
iter: slice::Iter<'a, u16>
}
/// The possibilities for values decoded from a `u16` stream.
-#[deriving(PartialEq, Eq, Clone, Show)]
+#[derive(PartialEq, Eq, Clone, Show)]
pub enum Utf16Item {
/// A valid codepoint.
ScalarValue(char),
}
/// Iterator adaptor for encoding `char`s to UTF-16.
-#[deriving(Clone)]
+#[derive(Clone)]
pub struct Utf16Encoder<I> {
chars: I,
extra: u16
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::{Receiver, channel};
pub fn foo<T:Send + Clone>(x: T) -> Receiver<T> {
let (tx, rx) = channel();
- task::spawn(move|| {
+ Thread::spawn(move|| {
tx.send(x.clone());
- });
+ }).detach();
rx
}
#![crate_type = "lib"]
use std::int;
-use std::str::from_str;
pub trait read {
fn readMaybe(s: String) -> Option<Self>;
impl read for int {
fn readMaybe(s: String) -> Option<int> {
- from_str::<int>(s.as_slice())
+ s.parse()
}
}
use std::collections::{BTreeMap, HashMap, HashSet};
use std::os;
use std::rand::{Rng, IsaacRng, SeedableRng};
-use std::str::from_str;
use std::time::Duration;
use std::uint;
let args = args.as_slice();
let n_keys = {
if args.len() == 2 {
- from_str::<uint>(args[1].as_slice()).unwrap()
+ args[1].parse::<uint>().unwrap()
} else {
1000000
}
use std::collections::HashSet;
use std::hash::Hash;
use std::os;
-use std::str::from_str;
use std::time::Duration;
use std::uint;
let args = args.as_slice();
let num_keys = {
if args.len() == 2 {
- from_str::<uint>(args[1].as_slice()).unwrap()
+ args[1].parse::<uint>().unwrap()
} else {
100 // woefully inadequate for any real measurement
}
#![feature(unboxed_closures)]
use std::io::File;
+use std::iter::repeat;
use std::mem::swap;
use std::os;
use std::rand::Rng;
}
fn shift_push() {
- let mut v1 = Vec::from_elem(30000, 1i);
+ let mut v1 = repeat(1i).take(30000).collect::<Vec<_>>();
let mut v2 = Vec::new();
while v1.len() > 0 {
let mut v = Vec::new();
let mut i = 0;
while i < 1500 {
- let rv = Vec::from_elem(r.gen_range(0u, i + 1), i);
+ let rv = repeat(i).take(r.gen_range(0u, i + 1)).collect::<Vec<_>>();
if r.gen() {
v.extend(rv.into_iter());
} else {
let mut v = Vec::new();
let mut i = 0;
while i < 1500 {
- let rv = Vec::from_elem(r.gen_range(0u, i + 1), i);
+ let rv = repeat(i).take(r.gen_range(0u, i + 1)).collect::<Vec<_>>();
if r.gen() {
let mut t = v.clone();
t.push_all(rv.as_slice());
let mut v = Vec::new();
for i in range(0u, 1500) {
- let mut rv = Vec::from_elem(r.gen_range(0u, i + 1), i);
+ let mut rv = repeat(i).take(r.gen_range(0u, i + 1)).collect::<Vec<_>>();
if r.gen() {
v.push_all(rv.as_slice());
}
let mut v : Vec<u8> = Vec::new();
for _ in range(0u, 20000) {
v.push('b' as u8);
- if !str::is_utf8(v.as_slice()) {
- panic!("is_utf8 panicked");
+ if str::from_utf8(v.as_slice()).is_err() {
+ panic!("from_utf8 panicked");
}
}
}
let mut v : Vec<u8> = Vec::new();
for _ in range(0u, 5000) {
v.push_all(s.as_bytes());
- if !str::is_utf8(v.as_slice()) {
- panic!("is_utf8 panicked");
+ if str::from_utf8(v.as_slice()).is_err() {
+ panic!("from_utf8 panicked");
}
}
}
// except according to those terms.
use std::os;
-use std::str::from_str;
use std::uint;
fn main() {
args.into_iter().collect()
};
- let n = from_str::<uint>(args[1].as_slice()).unwrap();
+ let n = args[1].parse().unwrap();
for i in range(0u, n) {
let x = i.to_string();
use std::sync::mpsc::{channel, Sender, Receiver};
use std::os;
-use std::str::from_str;
use std::thread::Thread;
use std::time::Duration;
use std::uint;
let (to_parent, from_child) = channel();
let (to_child, from_parent) = channel();
- let size = from_str::<uint>(args[1].as_slice()).unwrap();
- let workers = from_str::<uint>(args[2].as_slice()).unwrap();
+ let size = args[1].parse::<uint>().unwrap();
+ let workers = args[2].parse::<uint>().unwrap();
let num_bytes = 100;
let mut result = None;
let mut p = Some((to_child, to_parent, from_parent));
// ignore-lexer-test FIXME #15679
use std::os;
-use std::str::from_str;
use std::sync::{Arc, Future, Mutex, Condvar};
use std::time::Duration;
use std::uint;
args.clone().into_iter().collect()
};
- let num_tasks = from_str::<uint>(args[1].as_slice()).unwrap();
- let msg_per_task = from_str::<uint>(args[2].as_slice()).unwrap();
+ let num_tasks = args[1].parse::<uint>().unwrap();
+ let msg_per_task = args[2].parse::<uint>().unwrap();
let (mut num_chan, num_port) = init();
use std::sync::mpsc::channel;
use std::os;
-use std::str::from_str;
use std::thread::Thread;
use std::uint;
let args = os::args();
let args = args.as_slice();
let n = if args.len() == 3 {
- from_str::<uint>(args[1].as_slice()).unwrap()
+ args[1].parse::<uint>().unwrap()
} else {
10000
};
let m = if args.len() == 3 {
- from_str::<uint>(args[2].as_slice()).unwrap()
+ args[2].parse::<uint>().unwrap()
} else {
4
};
// except according to those terms.
use std::os;
-use std::str::from_str;
fn ack(m: int, n: int) -> int {
if m == 0 {
} else {
args.into_iter().collect()
};
- let n = from_str::<int>(args[1].as_slice()).unwrap();
+ let n = args[1].parse().unwrap();
println!("Ack(3,{}): {}\n", n, ack(3, n));
}
use self::Color::{Red, Yellow, Blue};
use std::sync::mpsc::{channel, Sender, Receiver};
use std::fmt;
-use std::str::from_str;
use std::thread::Thread;
fn print_complements() {
} else {
std::os::args().as_slice()
.get(1)
- .and_then(|arg| from_str(arg.as_slice()))
- .unwrap_or(600)
+ .and_then(|arg| arg.parse())
+ .unwrap_or(600u)
};
print_complements();
use std::cmp::min;
use std::io::{stdout, IoResult};
+use std::iter::repeat;
use std::os;
use std::slice::bytes::copy_memory;
-use std::str::from_str;
const LINE_LEN: uint = 60;
const LOOKUP_SIZE: uint = 4 * 1024;
fn make(&mut self, n: uint) -> IoResult<()> {
let alu_len = self.alu.len();
- let mut buf = Vec::from_elem(alu_len + LINE_LEN, 0u8);
+ let mut buf = repeat(0u8).take(alu_len + LINE_LEN).collect::<Vec<_>>();
let alu: &[u8] = self.alu.as_bytes();
copy_memory(buf.as_mut_slice(), alu);
let args = os::args();
let args = args.as_slice();
let n = if args.len() > 1 {
- from_str::<uint>(args[1].as_slice()).unwrap()
+ args[1].parse::<uint>().unwrap()
} else {
5
};
use std::io;
use std::num::Float;
use std::os;
-use std::str::from_str;
const LINE_LENGTH: uint = 60;
const IM: u32 = 139968;
} else if args.len() <= 1u {
1000
} else {
- from_str(args[1].as_slice()).unwrap()
+ args[1].parse().unwrap()
};
let rng = &mut MyRandom::new();
// except according to those terms.
use std::os;
-use std::str::from_str;
fn fib(n: int) -> int {
if n < 2 {
} else {
args.into_iter().collect()
};
- let n = from_str::<int>(args[1].as_slice()).unwrap();
+ let n = args[1].parse().unwrap();
println!("{}\n", fib(n));
}
#![feature(slicing_syntax)]
-extern crate collections;
-
use std::ascii::{AsciiExt, OwnedAsciiExt};
-use std::cmp::Ordering::{mod, Less, Greater, Equal};
+use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::collections::HashMap;
-use std::sync::mpsc::{channel, Sender, Receiver};
use std::mem::replace;
use std::num::Float;
use std::option;
use std::os;
-use std::string::IntoString;
+use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread::Thread;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// given a map, increment the counter for a key
fn update_freq(mm: &mut HashMap<Vec<u8> , uint>, key: &[u8]) {
let key = key.to_vec();
- let newval = match mm.pop(&key) {
+ let newval = match mm.remove(&key) {
Some(v) => v + 1,
None => 1
};
_ => { "".to_string() }
};
- to_parent.send(buffer);
+ to_parent.send(buffer).unwrap();
}
// given a FASTA file on stdin, process sequence THREE
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
- let mut streams = Vec::from_fn(sizes.len(), |_| Some(channel::<String>()));
+ let mut streams = range(0, sizes.len()).map(|_| {
+ Some(channel::<String>())
+ }).collect::<Vec<_>>();
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.iter_mut()).map(|(sz, stream_ref)| {
let sz = *sz;
for (ii, _sz) in sizes.iter().enumerate() {
let lb = line_bytes.to_vec();
- to_child[ii].send(lb);
+ to_child[ii].send(lb).unwrap();
}
}
// finish...
for (ii, _sz) in sizes.iter().enumerate() {
- to_child[ii].send(Vec::new());
+ to_child[ii].send(Vec::new()).unwrap();
}
// now fetch and print result messages
#![feature(associated_types, slicing_syntax)]
use std::ascii::OwnedAsciiExt;
+use std::iter::repeat;
use std::slice;
-use std::sync::{Arc, Future};
+use std::sync::Arc;
+use std::thread::Thread;
static TABLE: [u8;4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
impl Table {
fn new() -> Table {
Table {
- items: Vec::from_fn(TABLE_SIZE, |_| None),
+ items: range(0, TABLE_SIZE).map(|_| None).collect()
}
}
};
let input = Arc::new(input);
- let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
+ let nb_freqs: Vec<_> = range(1u, 3).map(|i| {
let input = input.clone();
- (i, Future::spawn(move|| generate_frequencies(input.as_slice(), i)))
+ (i, Thread::spawn(move|| generate_frequencies(input.as_slice(), i)))
}).collect();
- let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
+ let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
- Future::spawn(move|| generate_frequencies(input.as_slice(), occ.len()))
+ Thread::spawn(move|| generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.into_iter() {
- print_frequencies(&freq.unwrap(), i);
+ print_frequencies(&freq.join().ok().unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.into_iter()) {
- print_occurrences(&mut freq.unwrap(), occ);
+ print_occurrences(&mut freq.join().ok().unwrap(), occ);
}
}
use std::io;
use std::os;
use std::simd::f64x2;
-use std::str::from_str;
-use std::sync::{Arc, Future};
+use std::sync::Arc;
+use std::thread::Thread;
const ITER: int = 50;
const LIMIT: f64 = 2.0;
let mut precalc_r = Vec::with_capacity(w);
let mut precalc_i = Vec::with_capacity(h);
- let precalc_futures = Vec::from_fn(WORKERS, |i| {
- Future::spawn(move|| {
+ let precalc_futures = range(0, WORKERS).map(|i| {
+ Thread::spawn(move|| {
let mut rs = Vec::with_capacity(w / WORKERS);
let mut is = Vec::with_capacity(w / WORKERS);
(rs, is)
})
- });
+ }).collect::<Vec<_>>();
for res in precalc_futures.into_iter() {
- let (rs, is) = res.unwrap();
+ let (rs, is) = res.join().ok().unwrap();
precalc_r.extend(rs.into_iter());
precalc_i.extend(is.into_iter());
}
let arc_init_r = Arc::new(precalc_r);
let arc_init_i = Arc::new(precalc_i);
- let data = Vec::from_fn(WORKERS, |i| {
+ let data = range(0, WORKERS).map(|i| {
let vec_init_r = arc_init_r.clone();
let vec_init_i = arc_init_i.clone();
- Future::spawn(move|| {
+ Thread::spawn(move|| {
let mut res: Vec<u8> = Vec::with_capacity((chunk_size * w) / 8);
let init_r_slice = vec_init_r.as_slice();
res
})
- });
+ }).collect::<Vec<_>>();
try!(writeln!(&mut out as &mut Writer, "P4\n{} {}", w, h));
for res in data.into_iter() {
- try!(out.write(res.unwrap().as_slice()));
+ try!(out.write(res.join().ok().unwrap().as_slice()));
}
out.flush()
}
which interferes with the test runner.");
mandelbrot(1000, io::util::NullWriter)
} else {
- mandelbrot(from_str(args[1].as_slice()).unwrap(), io::stdout())
+ mandelbrot(args[1].parse().unwrap(), io::stdout())
};
res.unwrap();
}
#![feature(associated_types)]
-use std::sync::mpsc::channel;
+use std::iter::repeat;
use std::sync::Arc;
+use std::sync::mpsc::channel;
use std::thread::Thread;
//
// Converts a list of mask to a Vec<u8>.
fn to_vec(raw_sol: &List<u64>) -> Vec<u8> {
- let mut sol = Vec::from_elem(50, '.' as u8);
+ let mut sol = repeat('.' as u8).take(50).collect::<Vec<_>>();
for &m in raw_sol.iter() {
let id = '0' as u8 + get_id(m);
for i in range(0u, 50) {
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
-use std::str::from_str;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
5000000
} else {
std::os::args().as_slice().get(1)
- .and_then(|arg| from_str(arg.as_slice()))
+ .and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
use std::sync::mpsc::{channel, Sender};
use std::os;
use std::result::Result::{Ok, Err};
-use std::str::from_str;
use std::thread::Thread;
use std::time::Duration;
if opts.stress {
stress(2);
} else {
- let max = from_str::<uint>(args[1].as_slice()).unwrap() as int;
+ let max = args[1].parse::<int>().unwrap();
let num_trials = 10;
#![feature(macro_rules, phase, slicing_syntax)]
extern crate regex;
-#[phase(plugin)]extern crate regex_macros;
use std::io;
use regex::{NoExpand, Regex};
use std::sync::{Arc, Future};
+macro_rules! regex {
+ ($e:expr) => (Regex::new($e).unwrap())
+}
+
fn count_matches(seq: &str, variant: &Regex) -> int {
let mut n = 0;
for _ in variant.find_iter(seq) {
use std::io::stdio::{stdin_raw, stdout_raw};
use std::io::{IoResult, EndOfFile};
-use std::num::{div_rem};
use std::ptr::{copy_memory, Unique};
use std::thread::Thread;
i += LINE_LEN + 1;
}
- let (div, rem) = div_rem(len, 4);
+ let div = len / 4;
+ let rem = len % 4;
unsafe {
let mut left = seq.as_mut_ptr() as *mut u16;
// This is slow if len % 2 != 0 but still faster than bytewise operations.
#![allow(non_snake_case)]
#![feature(unboxed_closures)]
-use std::iter::AdditiveIterator;
+use std::iter::{repeat, AdditiveIterator};
use std::thread::Thread;
use std::mem;
use std::num::Float;
use std::os;
use std::raw::Repr;
use std::simd::f64x2;
-use std::str::from_str;
fn main() {
let args = os::args();
} else if args.len() < 2 {
2000
} else {
- from_str(args[1].as_slice()).unwrap()
+ args[1].parse().unwrap()
});
println!("{:.9}", answer);
}
fn spectralnorm(n: uint) -> f64 {
assert!(n % 2 == 0, "only even lengths are accepted");
- let mut u = Vec::from_elem(n, 1.0);
- let mut v = Vec::from_elem(n, 1.0);
- let mut tmp = Vec::from_elem(n, 1.0);
+ let mut u = repeat(1.0).take(n).collect::<Vec<_>>();
+ let mut v = u.clone();
+ let mut tmp = v.clone();
for _ in range(0u, 10) {
mult_AtAv(u.as_slice(), v.as_mut_slice(), tmp.as_mut_slice());
mult_AtAv(v.as_slice(), u.as_mut_slice(), tmp.as_mut_slice());
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::sync::mpsc::{channel, Sender, Receiver};
-use std::str::from_str;
use std::thread::Thread;
fn start(n_tasks: int, token: int) {
let token = if std::os::getenv("RUST_BENCH").is_some() {
2000000
} else {
- args.get(1).and_then(|arg| from_str(arg.as_slice())).unwrap_or(1000)
+ args.get(1).and_then(|arg| arg.parse()).unwrap_or(1000)
};
let n_tasks = args.get(2)
- .and_then(|arg| from_str(arg.as_slice()))
+ .and_then(|arg| arg.parse())
.unwrap_or(503);
start(n_tasks, token);
use std::collections::VecMap;
use std::os;
-use std::str::from_str;
use std::time::Duration;
use std::uint;
} else {
args.into_iter().collect()
};
- let max = from_str::<uint>(args[1].as_slice()).unwrap();
- let rep = from_str::<uint>(args[2].as_slice()).unwrap();
+ let max = args[1].parse::<uint>().unwrap();
+ let rep = args[2].parse::<uint>().unwrap();
let mut checkf = Duration::seconds(0);
let mut appendf = Duration::seconds(0);
use std::io::BufferedReader;
use std::io::stdio::StdReader;
use std::io;
+use std::iter::repeat;
use std::num::Int;
use std::os;
-use std::str::from_str;
// Computes a single solution to a given 9x9 sudoku
//
}
pub fn from_vec(vec: &[[u8;9];9]) -> Sudoku {
- let g = Vec::from_fn(9u, |i| {
- Vec::from_fn(9u, |j| { vec[i][j] })
- });
+ let g = range(0, 9u).map(|i| {
+ range(0, 9u).map(|j| { vec[i][j] }).collect()
+ }).collect();
return Sudoku::new(g)
}
/* assert first line is exactly "9,9" */
assert!(reader.read_line().unwrap() == "9,9".to_string());
- let mut g = Vec::from_fn(10u, { |_i| vec!(0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8) });
+ let mut g = repeat(vec![0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8])
+ .take(10).collect::<Vec<_>>();
for line in reader.lines() {
let line = line.unwrap();
let comps: Vec<&str> = line.as_slice()
.collect();
if comps.len() == 3u {
- let row = from_str::<uint>(comps[0]).unwrap() as u8;
- let col = from_str::<uint>(comps[1]).unwrap() as u8;
- g[row as uint][col as uint] =
- from_str::<uint>(comps[2]).unwrap() as u8;
+ let row = comps[0].parse::<u8>().unwrap();
+ let col = comps[1].parse::<u8>().unwrap();
+ g[row as uint][col as uint] = comps[2].parse().unwrap();
}
else {
panic!("Invalid sudoku file");
#![feature(unsafe_destructor)]
use std::os;
-use std::task;
+use std::thread::Thread;
use std::time::Duration;
#[derive(Clone)]
fn run(repeat: int, depth: int) {
for _ in range(0, repeat) {
let dur = Duration::span(|| {
- task::try(move|| {
+ let _ = Thread::spawn(move|| {
recurse_or_panic(depth, None)
- });
+ }).join();
});
println!("iter: {}", dur);
}
use std::sync::mpsc::{channel, Sender};
use std::os;
-use std::str::from_str;
-use std::task;
use std::thread::Thread;
use std::uint;
// alive at a time,
Thread::spawn(move|| {
if gens_left & 1 == 1 {
- task::deschedule(); // shake things up a bit
+ Thread::yield_now(); // shake things up a bit
}
if gens_left > 0 {
child_generation(gens_left - 1, tx); // recurse
};
let (tx, rx) = channel();
- child_generation(from_str::<uint>(args[1].as_slice()).unwrap(), tx);
+ child_generation(args[1].parse().unwrap(), tx);
if rx.recv().is_err() {
panic!("it happened when we slumbered");
}
// except according to those terms.
use std::os;
-use std::task;
use std::uint;
-use std::str::from_str;
+use std::thread::Thread;
fn f(n: uint) {
let mut i = 0u;
while i < n {
- task::try(move|| g());
+ let _ = Thread::spawn(move|| g()).join();
i += 1u;
}
}
} else {
args.into_iter().collect()
};
- let n = from_str::<uint>(args[1].as_slice()).unwrap();
+ let n = args[1].parse().unwrap();
let mut i = 0u;
- while i < n { task::spawn(move|| f(n) ); i += 1u; }
+ while i < n { Thread::spawn(move|| f(n) ).detach(); i += 1u; }
}
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// ignore-stage1
-
-#![feature(phase)]
-
-extern crate regex;
-#[phase(plugin)] extern crate regex_macros;
-
-// Tests to make sure that `regex!` will produce a compile error when given
-// an invalid regular expression.
-// More exhaustive failure tests for the parser are done with the traditional
-// unit testing infrastructure, since both dynamic and native regexes use the
-// same parser.
-
-fn main() {
- let _ = regex!("("); //~ ERROR Regex syntax error
-}
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// ignore-stage1
-
-#![feature(phase)]
-
-extern crate regex;
-#[phase(plugin)] extern crate regex_macros;
-
-#[deny(unused_variables)]
-#[deny(dead_code)]
-#[allow(non_upper_case_globals)]
-
-// Tests to make sure that extraneous dead code warnings aren't emitted from
-// the code generated by regex!.
-//
-// The warning used for `static` items seems to be dead_code, which is why this
-// is a distinct test from using a normal let binding (which generates an
-// unused variable warning).
-
-fn main() {
- static fubar: regex::Regex = regex!("abc"); //~ ERROR static item is never used: `fubar`
-}
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// ignore-stage1
-
-#![feature(phase)]
-
-extern crate regex;
-#[phase(plugin)] extern crate regex_macros;
-
-#[deny(unused_variables)]
-#[deny(dead_code)]
-
-// Tests to make sure that extraneous dead code warnings aren't emitted from
-// the code generated by regex!.
-
-fn main() {
- let fubar = regex!("abc"); //~ ERROR unused variable: `fubar`
-}
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use std::sync::atomic::AtomicOption;
-
-fn main() {
- let x = 0u;
- AtomicOption::new(box &x); //~ ERROR `x` does not live long enough
-}
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use std::kinds::marker;
-use std::sync::atomic::AtomicOption;
-
-fn main() {
- AtomicOption::new(box marker::NoSend); //~ ERROR `core::kinds::Send` is not implemented
-}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+use std::iter::repeat;
+
fn main() {
let mut vector = vec![1u, 2];
for &x in vector.iter() {
let cap = vector.capacity();
- vector.grow(cap, 0u); //~ ERROR cannot borrow
+ vector.extend(repeat(0)); //~ ERROR cannot borrow
vector[1u] = 5u; //~ ERROR cannot borrow
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
fn borrow(v: &int, f: |x: &int|) {
f(v);
fn box_imm() {
let v = box 3i;
let _w = &v;
- task::spawn(move|| {
+ Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move `v` into closure
});
fn box_imm_explicit() {
let v = box 3i;
let _w = &v;
- task::spawn(move|| {
+ Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move
});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
fn borrow<T>(_: &T) { }
let p1 = &x1;
let x2 = box 2i;
let p2 = &x2;
- task::spawn(move|| {
+ Thread::spawn(move|| {
drop(x1); //~ ERROR cannot move `x1` into closure because it is borrowed
drop(x2); //~ ERROR cannot move `x2` into closure because it is borrowed
});
drop(x1);
let x2 = box 2i;
drop(x2);
- task::spawn(move|| {
+ Thread::spawn(move|| {
drop(x1); //~ ERROR capture of moved value: `x1`
drop(x2); //~ ERROR capture of moved value: `x2`
});
fn same_var_after_borrow() {
let x = box 1i;
let p = &x;
- task::spawn(move|| {
+ Thread::spawn(move|| {
drop(x); //~ ERROR cannot move `x` into closure because it is borrowed
drop(x); //~ ERROR use of moved value: `x`
});
fn same_var_after_move() {
let x = box 1i;
drop(x);
- task::spawn(move|| {
+ Thread::spawn(move|| {
drop(x); //~ ERROR capture of moved value: `x`
drop(x); //~ ERROR use of moved value: `x`
});
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// This file was auto-generated using 'src/etc/generate-deriving-span-tests.py'
-
-extern crate rand;
-
-
-struct Error;
-
-#[derive(Zero)] //~ ERROR not implemented
-struct Struct {
- x: Error
-}
-
-fn main() {}
+++ /dev/null
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// This file was auto-generated using 'src/etc/generate-deriving-span-tests.py'
-
-extern crate rand;
-
-
-struct Error;
-
-#[derive(Zero)] //~ ERROR not implemented
-struct Struct(
- Error
-);
-
-fn main() {}
fn main() {
let f = Future::from_value(());
let g = f;
- f.unwrap(); //~ ERROR use of moved value
+ f.into_inner(); //~ ERROR use of moved value
}
my_stuff.insert(0i, 42i);
let mut it = my_stuff.iter();
- my_stuff.swap(1, 43); //~ ERROR cannot borrow
+ my_stuff.insert(1, 43); //~ ERROR cannot borrow
}
fn main() {
let mut c = for_stdin();
- let mut v = vec::Vec::from_elem(10, 0u8);
+ let mut v = Vec::new();
c.read_to(v.as_mut_slice());
}
// except according to those terms.
pub fn foo(params: Option<&[&str]>) -> uint {
- params.unwrap().head().unwrap().len()
+ params.unwrap().first().unwrap().len()
}
fn main() {
trait TraversesWorld {
fn attemptTraverse(&self, room: &Room, directionStr: &str) -> Result<&Room, &str> {
let direction = str_to_direction(directionStr);
- let maybe_room = room.direction_to_room.find(&direction);
+ let maybe_room = room.direction_to_room.get(&direction);
//~^ ERROR cannot infer an appropriate lifetime for autoref due to conflicting requirements
match maybe_room {
Some(entry) => Ok(entry),
fn akemi(homura: Homura) {
let Some(ref madoka) = Some(homura.kaname()); //~ ERROR does not implement any method
- madoka.clone(); //~ ERROR the type of this value must be known
+ madoka.clone();
}
fn main() { }
// Test that Copy bounds inherited by trait are checked.
use std::any::Any;
-use std::any::AnyRefExt;
trait Foo : Copy {
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
fn main() {
let x = "Hello world!".to_string();
- task::spawn(move|| {
+ Thread::spawn(move|| {
println!("{}", x);
});
println!("{}", x); //~ ERROR use of moved value
// error-pattern: use of moved value
use std::sync::Arc;
-use std::task;
+use std::thread::Thread;
fn main() {
let v = vec!(1i, 2, 3, 4, 5, 6, 7, 8, 9, 10);
let arc_v = Arc::new(v);
- task::spawn(move|| {
+ Thread::spawn(move|| {
assert_eq!((*arc_v)[3], 4);
});
// except according to those terms.
use std::sync::Arc;
-use std::task;
+use std::thread::Thread;
fn main() {
let v = vec!(1i, 2, 3, 4, 5, 6, 7, 8, 9, 10);
let arc_v = Arc::new(v);
- task::spawn(move|| {
+ Thread::spawn(move|| {
assert_eq!((*arc_v)[3], 4);
});
#![feature(unsafe_destructor)]
-use std::task;
+use std::thread::Thread;
use std::rc::Rc;
#[derive(Show)]
let x = foo(Port(Rc::new(())));
- task::spawn(move|| {
+ Thread::spawn(move|| {
//~^ ERROR `core::kinds::Send` is not implemented
//~^^ ERROR `core::kinds::Send` is not implemented
let y = x;
+++ /dev/null
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use std::task;
-
-fn main() {
- // We get an error because return type is `->int` and not `->()`.
- task::spawn(|| -> int { 10 });
- //~^ ERROR type mismatch
-}
let x = *&x; //~ ERROR: cannot move out of dereference
let x: AtomicPtr<uint> = AtomicPtr::new(ptr::null_mut());
let x = *&x; //~ ERROR: cannot move out of dereference
- let x: AtomicOption<uint> = AtomicOption::empty();
- let x = *&x; //~ ERROR: cannot move out of dereference
}
#![feature(phase)]
#[phase(plugin, link)] extern crate log;
use std::os;
-use std::task;
+use std::thread::Thread;
struct r {
x:int,
fn main() {
error!("whatever");
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
let _i = r(5);
});
panic!();
// error-pattern:Ensure that the child task runs by panicking
-use std::task;
+use std::thread::Thread;
fn main() {
// the purpose of this test is to make sure that task::spawn()
// works when provided with a bare function:
- let r = task::try(startfn);
+ let r = Thread::spawn(startfn).join();
if r.is_err() {
panic!()
}
#![feature(phase)]
extern crate lib;
-extern crate regex;
-#[phase(plugin)] extern crate regex_macros;
+#[phase(plugin, link)] extern crate log;
-fn main() {
- regex!("1234");
-}
+fn main() {}
extern crate lib;
-use std::task;
+use std::thread::Thread;
static mut statik: int = 0;
}
fn main() {
- task::try(move|| {
+ Thread::spawn(move|| {
let _a = A;
lib::callback(|| panic!());
1i
- });
+ }).join().err().unwrap();
unsafe {
assert!(lib::statik == 1);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::{char, os};
use std::io::{File, Command};
+use std::iter::repeat;
use std::rand::{thread_rng, Rng};
+use std::{char, os};
// creates a file with `fn main() { <random ident> }` and checks the
// compiler emits a span of the appropriate length (for the
let err = String::from_utf8_lossy(result.error.as_slice());
// the span should end the line (e.g no extra ~'s)
- let expected_span = format!("^{}\n", "~".repeat(n - 1));
+ let expected_span = format!("^{}\n", repeat("~").take(n - 1)
+ .collect::<String>());
assert!(err.as_slice().contains(expected_span.as_slice()));
}
}
fn boo(&self) -> <Self as Foo>::A;
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
struct Bar;
impl Foo for int {
#![no_implicit_prelude]
use std::kinds::Sized;
-use std::option::Option::{None, Some, mod};
+use std::option::Option::{None, Some, self};
trait Iterator {
type Item;
fn boo(&self) -> <Self as Foo>::A;
}
-#[deriving(PartialEq)]
+#[derive(PartialEq)]
struct Bar;
impl Foo for int {
#![no_implicit_prelude]
use std::kinds::Sized;
-use std::option::Option::{None, Some, mod};
+use std::option::Option::{None, Some, self};
trait Iterator {
type Item;
// Reported as issue #126, child leaks the string.
-use std::task;
+use std::thread::Thread;
fn child2(_s: String) { }
pub fn main() {
- let _x = task::spawn(move|| child2("hi".to_string()));
+ let _x = Thread::spawn(move|| child2("hi".to_string()));
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task::spawn;
+use std::thread::Thread;
struct Pair {
a: int,
pub fn main() {
let z = box Pair { a : 10, b : 12};
- spawn(move|| {
+ let _t = Thread::spawn(move|| {
assert_eq!(z.a, 10);
assert_eq!(z.b, 12);
});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
pub fn main() {
let (tx, rx) = channel();
- let _t = task::spawn(move|| { child(&tx) });
+ let _t = Thread::spawn(move|| { child(&tx) });
let y = rx.recv().unwrap();
println!("received");
println!("{}", y);
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(macro_rules)]
+
+use std::collections::Bitv;
+use std::default::Default;
+use std::iter::FromIterator;
+use std::option::IntoIter as OptionIter;
+use std::rand::Rand;
+use std::rand::XorShiftRng as DummyRng;
+// FIXME the glob std::prelude::*; import of Vec is missing non-static inherent methods.
+use std::vec::Vec;
+
+#[derive(PartialEq, Eq)]
+struct Newt<T>(T);
+
+fn id<T>(x: T) -> T { x }
+fn eq<T: Eq>(a: T, b: T) -> bool { a == b }
+fn u8_as_i8(x: u8) -> i8 { x as i8 }
+fn odd(x: uint) -> bool { x % 2 == 1 }
+fn dummy_rng() -> DummyRng { DummyRng::new_unseeded() }
+
+macro_rules! tests {
+ ($($expr:expr: $ty:ty /($($test:expr),*);)+) => (pub fn main() {$({
+ const C: $ty = $expr;
+ static S: $ty = $expr;
+ assert!(eq(C($($test),*), $expr($($test),*)));
+ assert!(eq(S($($test),*), $expr($($test),*)));
+ assert!(eq(C($($test),*), S($($test),*)));
+ })+})
+}
+
+tests! {
+ // Free function.
+ id: fn(int) -> int /(5);
+ id::<int>: fn(int) -> int /(5);
+
+ // Enum variant constructor.
+ Some: fn(int) -> Option<int> /(5);
+ Some::<int>: fn(int) -> Option<int> /(5);
+
+ // Tuple struct constructor.
+ Newt: fn(int) -> Newt<int> /(5);
+ Newt::<int>: fn(int) -> Newt<int> /(5);
+
+ // Inherent static methods.
+ Vec::new: fn() -> Vec<()> /();
+ Vec::<()>::new: fn() -> Vec<()> /();
+ Vec::with_capacity: fn(uint) -> Vec<()> /(5);
+ Vec::<()>::with_capacity: fn(uint) -> Vec<()> /(5);
+ Bitv::from_fn: fn(uint, fn(uint) -> bool) -> Bitv /(5, odd);
+ Bitv::from_fn::<fn(uint) -> bool>: fn(uint, fn(uint) -> bool) -> Bitv /(5, odd);
+
+ // Inherent non-static method.
+ Vec::map_in_place: fn(Vec<u8>, fn(u8) -> i8) -> Vec<i8>
+ /(vec![b'f', b'o', b'o'], u8_as_i8);
+ Vec::map_in_place::<i8, fn(u8) -> i8>: fn(Vec<u8>, fn(u8) -> i8) -> Vec<i8>
+ /(vec![b'f', b'o', b'o'], u8_as_i8);
+ // FIXME these break with "type parameter might not appear here pointing at `<u8>`.
+ // Vec::<u8>::map_in_place: fn(Vec<u8>, fn(u8) -> i8) -> Vec<i8>
+ // /(vec![b'f', b'o', b'o'], u8_as_i8);
+ // Vec::<u8>::map_in_place::<i8, fn(u8) -> i8>: fn(Vec<u8>, fn(u8) -> i8) -> Vec<i8>
+ // /(vec![b'f', b'o', b'o'], u8_as_i8);
+
+ // Trait static methods.
+ // FIXME qualified path expressions aka UFCS i.e. <T as Trait>::method.
+ Default::default: fn() -> int /();
+ Rand::rand: fn(&mut DummyRng) -> int /(&mut dummy_rng());
+ Rand::rand::<DummyRng>: fn(&mut DummyRng) -> int /(&mut dummy_rng());
+
+ // Trait non-static methods.
+ Clone::clone: fn(&int) -> int /(&5);
+ FromIterator::from_iter: fn(OptionIter<int>) -> Vec<int> /(Some(5).into_iter());
+ FromIterator::from_iter::<OptionIter<int>>: fn(OptionIter<int>) -> Vec<int>
+ /(Some(5).into_iter());
+}
pub fn main() {
unsafe {
let foo = &A as *const u8;
- assert_eq!(str::raw::from_utf8(&A), "hi");
- assert_eq!(string::raw::from_buf_len(foo, A.len()), "hi".to_string());
- assert_eq!(string::raw::from_buf_len(C, B.len()), "hi".to_string());
+ assert_eq!(str::from_utf8_unchecked(&A), "hi");
+ assert_eq!(String::from_raw_buf_len(foo, A.len()), "hi".to_string());
+ assert_eq!(String::from_raw_buf_len(C, B.len()), "hi".to_string());
assert!(*C == A[0]);
assert!(*(&B[0] as *const u8) == A[0]);
- let bar = str::raw::from_utf8(&A).to_c_str();
+ let bar = str::from_utf8_unchecked(&A).to_c_str();
assert_eq!(bar.as_str(), "hi".to_c_str().as_str());
}
}
+++ /dev/null
-// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#![feature(associated_types)]
-
-use std::num::Zero;
-use std::ops::Add;
-
-#[derive(Zero)]
-struct Vector2<T>(T, T);
-
-impl<T: Add<Output=T>> Add for Vector2<T> {
- type Output = Vector2<T>;
-
- fn add(self, other: Vector2<T>) -> Vector2<T> {
- match (self, other) {
- (Vector2(x0, y0), Vector2(x1, y1)) => {
- Vector2(x0 + x1, y0 + y1)
- }
- }
- }
-}
-
-#[derive(Zero)]
-struct Vector3<T> {
- x: T, y: T, z: T,
-}
-
-impl<T: Add<Output=T>> Add for Vector3<T> {
- type Output = Vector3<T>;
-
- fn add(self, other: Vector3<T>) -> Vector3<T> {
- Vector3 {
- x: self.x + other.x,
- y: self.y + other.y,
- z: self.z + other.z,
- }
- }
-}
-
-#[derive(Zero)]
-struct Matrix3x2<T> {
- x: Vector2<T>,
- y: Vector2<T>,
- z: Vector2<T>,
-}
-
-impl<T: Add<Output=T>> Add for Matrix3x2<T> {
- type Output = Matrix3x2<T>;
-
- fn add(self, other: Matrix3x2<T>) -> Matrix3x2<T> {
- Matrix3x2 {
- x: self.x + other.x,
- y: self.y + other.y,
- z: self.z + other.z,
- }
- }
-}
-
-pub fn main() {
- let _: Vector2<int> = Zero::zero();
- let _: Vector3<f64> = Zero::zero();
- let _: Matrix3x2<u8> = Zero::zero();
-}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
#[derive(PartialEq, Show)]
assert_eq!(receiver.recv().ok(), None);
let (sender, receiver) = channel();
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
let v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } };
});
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().ok(), None);
let (sender, receiver) = channel();
- {
- task::spawn(move|| {
+ let _t = {
+ Thread::spawn(move|| {
let mut v = Foo::NestedVariant(box 42u, SendOnDrop {
sender: sender.clone()
}, sender.clone());
v = Foo::NestedVariant(box 42u, SendOnDrop { sender: sender.clone() }, sender.clone());
v = Foo::SimpleVariant(sender.clone());
v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } };
- });
- }
+ })
+ };
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
assert_eq!(receiver.recv().unwrap(), Message::Dropped);
assert_eq!(receiver.recv().unwrap(), Message::DestructorRan);
// except according to those terms.
extern crate libc;
-use std::task;
+use std::thread::Thread;
mod rustrt {
extern crate libc;
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
let result = count(1000);
println!("result = {}", result);
assert_eq!(result, 1000);
// directions
extern crate libc;
-use std::task;
+use std::thread::Thread;
mod rustrt {
extern crate libc;
pub fn main() {
// Make sure we're on a task with small Rust stacks (main currently
// has a large stack)
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
let result = count(12);
println!("result = {}", result);
assert_eq!(result, 2048);
// while holding onto C stacks
extern crate libc;
-use std::task;
+use std::thread::Thread;
mod rustrt {
extern crate libc;
if data == 1 {
data
} else {
- task::deschedule();
+ Thread::yield_now();
count(data - 1) + count(data - 1)
}
}
}
pub fn main() {
- for _ in range(0u, 100) {
- task::spawn(move|| {
+ range(0u, 100).map(|_| {
+ Thread::spawn(move|| {
assert_eq!(count(5), 16);
- });
- }
+ })
+ }).collect::<Vec<_>>();
}
// except according to those terms.
extern crate libc;
-use std::task;
+use std::thread::Thread;
mod rustrt {
extern crate libc;
fn count(n: libc::uintptr_t) -> libc::uintptr_t {
unsafe {
- task::deschedule();
+ Thread::yield_now();
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
- for _ in range(0, 10u) {
- task::spawn(move|| {
+ range(0, 10u).map(|i| {
+ Thread::spawn(move|| {
let result = count(5);
println!("result = {}", result);
assert_eq!(result, 16);
- });
- }
+ })
+ }).collect::<Vec<_>>();
}
use std::collections::HashMap;
use std::sync::mpsc::{channel, Sender};
use std::str;
- use std::task;
+ use std::thread::Thread;
pub type putter<'a> = |String, String|: 'a;
for i in inputs.iter() {
let ctrl = ctrl.clone();
let i = i.clone();
- task::spawn(move|| map_task(ctrl.clone(), i.clone()) );
+ Thread::spawn(move|| map_task(ctrl.clone(), i.clone()) ).detach();
}
}
impl StrWrap {
fn new(s: &str) -> StrWrap {
- StrWrap { s: s.into_string() }
+ StrWrap { s: s.to_string() }
}
fn get_s<'a>(&'a self) -> &'a str {
use std::io::{TempDir, Command, fs};
use std::os;
-use std::task::TaskBuilder;
fn main() {
// If we're the child, make sure we were invoked correctly
extern crate "issue-17718" as other;
-use std::sync::atomic;
+use std::sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering};
const C1: uint = 1;
-const C2: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT;
+const C2: AtomicUint = ATOMIC_UINT_INIT;
const C3: fn() = foo;
const C4: uint = C1 * C1 + C1 / C1;
const C5: &'static uint = &C4;
};
static S1: uint = 3;
-static S2: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT;
+static S2: AtomicUint = ATOMIC_UINT_INIT;
mod test {
static A: uint = 4;
fn main() {
assert_eq!(C1, 1);
assert_eq!(C3(), ());
- assert_eq!(C2.fetch_add(1, atomic::SeqCst), 0);
- assert_eq!(C2.fetch_add(1, atomic::SeqCst), 0);
+ assert_eq!(C2.fetch_add(1, Ordering::SeqCst), 0);
+ assert_eq!(C2.fetch_add(1, Ordering::SeqCst), 0);
assert_eq!(C4, 2);
assert_eq!(*C5, 2);
assert_eq!(C6, 3);
assert_eq!(S1, 3);
- assert_eq!(S2.fetch_add(1, atomic::SeqCst), 0);
- assert_eq!(S2.fetch_add(1, atomic::SeqCst), 1);
+ assert_eq!(S2.fetch_add(1, Ordering::SeqCst), 0);
+ assert_eq!(S2.fetch_add(1, Ordering::SeqCst), 1);
match 1 {
C1 => {}
assert_eq!(other::C1, 1);
assert_eq!(other::C3(), ());
- assert_eq!(other::C2.fetch_add(1, atomic::SeqCst), 0);
- assert_eq!(other::C2.fetch_add(1, atomic::SeqCst), 0);
+ assert_eq!(other::C2.fetch_add(1, Ordering::SeqCst), 0);
+ assert_eq!(other::C2.fetch_add(1, Ordering::SeqCst), 0);
assert_eq!(other::C4, 2);
assert_eq!(*other::C5, 2);
assert_eq!(other::S1, 3);
- assert_eq!(other::S2.fetch_add(1, atomic::SeqCst), 0);
- assert_eq!(other::S2.fetch_add(1, atomic::SeqCst), 1);
+ assert_eq!(other::S2.fetch_add(1, Ordering::SeqCst), 0);
+ assert_eq!(other::S2.fetch_add(1, Ordering::SeqCst), 1);
let _a = other::C1;
let _a = other::C2;
pub fn main() {
let mut q = RingBuf::new();
- q.push(10i);
+ q.push_front(10i);
}
use std::mem::{forget, transmute};
use std::mem::{replace, swap};
use std::mem;
- use std::task;
+ use std::thread::Thread;
use std::kinds::Send;
pub struct Stuff<T> {
let old_state = swap_state_acq(&mut (*p).state,
blocked);
match old_state {
- empty | blocked => { task::deschedule(); }
+ empty | blocked => { Thread::yield_now(); }
full => {
let payload = replace(&mut p.payload, None);
return Some(payload.unwrap())
fn lookup(table: json::Object, key: String, default: String) -> String
{
- match table.find(&key.to_string()) {
+ match table.get(&key) {
option::Option::Some(&Json::String(ref s)) => {
s.to_string()
}
impl methods for () {
fn to_bytes(&self) -> Vec<u8> {
- Vec::from_elem(0, 0u8)
+ Vec::new()
}
}
// the position of this function is significant! - if it comes before methods
// then it works, if it comes after it then it doesn't!
fn to_bools(bitv: Storage) -> Vec<bool> {
- Vec::from_fn(8, |i| {
+ range(0, 8).map(|i| {
let w = i / 64;
let b = i % 64;
let x = 1u64 & (bitv.storage[w] >> b);
x == 1u64
- })
+ }).collect()
}
struct Storage { storage: Vec<u64> }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// ASCII art shape renderer.
-// Demonstrates traits, impls, operator overloading, non-copyable struct, unit testing.
-// To run execute: rustc --test shapes.rs && ./shapes
+// ASCII art shape renderer. Demonstrates traits, impls, operator overloading,
+// non-copyable struct, unit testing. To run execute: rustc --test shapes.rs &&
+// ./shapes
-// Rust's std library is tightly bound to the language itself so it is automatically linked in.
-// However the extra library is designed to be optional (for code that must run on constrained
-// environments like embedded devices or special environments like kernel code) so it must
-// be explicitly linked in.
+// Rust's std library is tightly bound to the language itself so it is
+// automatically linked in. However the extra library is designed to be
+// optional (for code that must run on constrained environments like embedded
+// devices or special environments like kernel code) so it must be explicitly
+// linked in.
-// Extern mod controls linkage. Use controls the visibility of names to modules that are
-// already linked in. Using WriterUtil allows us to use the write_line method.
+// Extern mod controls linkage. Use controls the visibility of names to modules
+// that are already linked in. Using WriterUtil allows us to use the write_line
+// method.
-use std::slice;
use std::fmt;
+use std::iter::repeat;
+use std::slice;
// Represents a position on a canvas.
struct Point {
// blank characters for each position in our canvas.
let mut lines = Vec::new();
for _ in range(0, height) {
- lines.push(Vec::from_elem(width, '.'));
+ lines.push(repeat('.').take(width).collect::<Vec<_>>());
}
// Rust code often returns values by omitting the trailing semi-colon
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Convert each line into a string.
let lines = self.lines.iter()
- .map(|line| String::from_chars(line.as_slice()))
+ .map(|line| line.iter().cloned().collect())
.collect::<Vec<String>>();
// Concatenate the lines together using a new-line.
#![feature(default_type_params)]
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::Sender;
use std::thunk::Invoke;
}
fn foo(name: String, samples_chan: Sender<Msg>) {
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
let mut samples_chan = samples_chan;
// `box() (...)` syntax is needed to make pretty printer converge in one try:
// except according to those terms.
use std::{int, i8, i16, i32, i64};
-use std::task;
+use std::thread::Thread;
fn main() {
- assert!(task::try(move|| int::MIN / -1).is_err());
- assert!(task::try(move|| i8::MIN / -1).is_err());
- assert!(task::try(move|| i16::MIN / -1).is_err());
- assert!(task::try(move|| i32::MIN / -1).is_err());
- assert!(task::try(move|| i64::MIN / -1).is_err());
- assert!(task::try(move|| 1i / 0).is_err());
- assert!(task::try(move|| 1i8 / 0).is_err());
- assert!(task::try(move|| 1i16 / 0).is_err());
- assert!(task::try(move|| 1i32 / 0).is_err());
- assert!(task::try(move|| 1i64 / 0).is_err());
- assert!(task::try(move|| int::MIN % -1).is_err());
- assert!(task::try(move|| i8::MIN % -1).is_err());
- assert!(task::try(move|| i16::MIN % -1).is_err());
- assert!(task::try(move|| i32::MIN % -1).is_err());
- assert!(task::try(move|| i64::MIN % -1).is_err());
- assert!(task::try(move|| 1i % 0).is_err());
- assert!(task::try(move|| 1i8 % 0).is_err());
- assert!(task::try(move|| 1i16 % 0).is_err());
- assert!(task::try(move|| 1i32 % 0).is_err());
- assert!(task::try(move|| 1i64 % 0).is_err());
+ assert!(Thread::spawn(move|| int::MIN / -1).join().is_err());
+ assert!(Thread::spawn(move|| i8::MIN / -1).join().is_err());
+ assert!(Thread::spawn(move|| i16::MIN / -1).join().is_err());
+ assert!(Thread::spawn(move|| i32::MIN / -1).join().is_err());
+ assert!(Thread::spawn(move|| i64::MIN / -1).join().is_err());
+ assert!(Thread::spawn(move|| 1i / 0).join().is_err());
+ assert!(Thread::spawn(move|| 1i8 / 0).join().is_err());
+ assert!(Thread::spawn(move|| 1i16 / 0).join().is_err());
+ assert!(Thread::spawn(move|| 1i32 / 0).join().is_err());
+ assert!(Thread::spawn(move|| 1i64 / 0).join().is_err());
+ assert!(Thread::spawn(move|| int::MIN % -1).join().is_err());
+ assert!(Thread::spawn(move|| i8::MIN % -1).join().is_err());
+ assert!(Thread::spawn(move|| i16::MIN % -1).join().is_err());
+ assert!(Thread::spawn(move|| i32::MIN % -1).join().is_err());
+ assert!(Thread::spawn(move|| i64::MIN % -1).join().is_err());
+ assert!(Thread::spawn(move|| 1i % 0).join().is_err());
+ assert!(Thread::spawn(move|| 1i8 % 0).join().is_err());
+ assert!(Thread::spawn(move|| 1i16 % 0).join().is_err());
+ assert!(Thread::spawn(move|| 1i32 % 0).join().is_err());
+ assert!(Thread::spawn(move|| 1i64 % 0).join().is_err());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
fn producer(tx: &Sender<Vec<u8>>) {
pub fn main() {
let (tx, rx) = channel::<Vec<u8>>();
- let _prod = task::spawn(move|| {
+ let _prod = Thread::spawn(move|| {
producer(&tx)
});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
fn user(_i: int) {}
// Here, i is *copied* into the proc (heap closure).
// Requires allocation. The proc's copy is not mutable.
let mut i = 0;
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
user(i);
println!("spawned {}", i)
});
// mutable outside of the proc.
let mut i = 0;
while i < 10 {
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
user(i);
});
i += 1;
// Here, i must be shadowed in the proc to be mutable.
let mut i = 0;
while i < 10 {
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
let mut i = i;
i += 1;
user(i);
// except according to those terms.
use std::uint;
-use std::str::from_str;
pub fn main() {
// sometimes we have had trouble finding
// the right type for f, as we unified
// bot and u32 here
- let f = match from_str::<uint>("1234") {
+ let f = match "1234".parse::<uint>() {
None => return (),
Some(num) => num as u32
};
// begin failing.
mod m {
- pub fn f() -> Vec<int> { Vec::from_elem(1u, 0i) }
+ pub fn f() -> Vec<int> { Vec::new() }
}
pub fn main() { let _x = m::f(); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
pub fn main() {
let x = "Hello world!".to_string();
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
println!("{}", x);
});
}
// compile-flags: -Z no-landing-pads
-use std::task;
+use std::thread::Thread;
static mut HIT: bool = false;
}
fn main() {
- task::try(move|| -> () {
+ Thread::spawn(move|| -> () {
let _a = A;
panic!();
- });
+ }).join().unwrap_err();
assert!(unsafe { !HIT });
}
// traits.
use std::any::Any;
-use std::any::AnyRefExt;
trait Wrap {
fn get(&self) -> int;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
static mut dropped: bool = false;
}
pub fn main() {
- let ret = task::try(move|| {
+ let ret = Thread::spawn(move|| {
let _a = A { b: B { foo: 3 } };
- });
+ }).join();
assert!(ret.is_err());
unsafe { assert!(dropped); }
}
use alloc::heap;
use std::ptr;
+use std::iter::repeat;
fn main() {
unsafe {
unsafe fn test_triangle() -> bool {
static COUNT : uint = 16;
- let mut ascend = Vec::from_elem(COUNT, ptr::null_mut());
+ let mut ascend = repeat(ptr::null_mut()).take(COUNT).collect::<Vec<_>>();
let ascend = ascend.as_mut_slice();
static ALIGN : uint = 1;
}
let args = unsafe {
- Vec::from_fn(argc as uint, |i| {
+ range(0, argc as uint).map(|i| {
String::from_raw_buf(*argv.offset(i as int)).into_bytes()
- })
+ }).collect::<Vec<_>>()
};
let me = args[0].as_slice();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::channel;
struct test {
pub fn main() {
let (tx, rx) = channel();
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
let (tx2, rx2) = channel();
tx.send(tx2).unwrap();
extern crate collections;
use std::collections::HashMap;
-use std::str::SendStr;
-use std::borrow::IntoCow;
+use std::borrow::{Cow, IntoCow};
+
+type SendStr = Cow<'static, String, str>;
pub fn main() {
let mut map: HashMap<SendStr, uint> = HashMap::new();
extern crate collections;
use self::collections::BTreeMap;
-use std::str::SendStr;
-use std::borrow::IntoCow;
+use std::borrow::{Cow, IntoCow};
+
+type SendStr = Cow<'static, String, str>;
pub fn main() {
let mut map: BTreeMap<SendStr, uint> = BTreeMap::new();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
pub fn main() { test05(); }
println!("{}", *three + n); // will copy x into the closure
assert_eq!(*three, 3);
};
- task::spawn(move|| {
+ Thread::spawn(move|| {
test05_start(fn_to_send);
- });
+ }).join().ok().unwrap();
}
// In any case, this test should let us know if enabling parallel codegen ever
// breaks unwinding.
+use std::thread::Thread;
+
fn pad() -> uint { 0 }
mod a {
}
fn main() {
- std::task::try(move|| { ::b::g() }).unwrap_err();
+ Thread::spawn(move|| { ::b::g() }).join().unwrap_err();
}
#![feature(slicing_syntax)]
-use std::task;
+use std::thread::Thread;
struct Foo;
}
fn main() {
- let _ = task::try(move|| foo());
+ let _ = Thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
#![feature(slicing_syntax)]
-use std::task;
+use std::thread::Thread;
struct Foo;
}
fn main() {
- let _ = task::try(move|| foo());
+ let _ = Thread::spawn(move|| foo()).join();
unsafe { assert!(DTOR_COUNT == 2); }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
fn x(s: String, n: int) {
println!("{}", s);
}
pub fn main() {
- task::spawn(move|| x("hello from first spawned fn".to_string(), 65) );
- task::spawn(move|| x("hello from second spawned fn".to_string(), 66) );
- task::spawn(move|| x("hello from third spawned fn".to_string(), 67) );
+ let _t = Thread::spawn(|| x("hello from first spawned fn".to_string(), 65) );
+ let _t = Thread::spawn(|| x("hello from second spawned fn".to_string(), 66) );
+ let _t = Thread::spawn(|| x("hello from third spawned fn".to_string(), 67) );
let mut i: int = 30;
while i > 0 {
i = i - 1;
println!("parent sleeping");
- task::deschedule();
+ Thread::yield_now();
}
}
Arnold.
*/
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
type ctx = Sender<int>;
pub fn main() {
let (tx, _rx) = channel::<int>();
- task::spawn(move|| iotask(&tx, "localhost".to_string()) );
+ let t = Thread::spawn(move|| iotask(&tx, "localhost".to_string()) );
+ t.join().ok().unwrap();
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
pub fn main() {
- task::spawn(move|| child(10) );
+ Thread::spawn(move|| child(10)).join().ok().unwrap();
}
fn child(i: int) { println!("{}", i); assert!((i == 10)); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
-pub fn main() { task::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) ); }
+pub fn main() {
+ let t = Thread::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) );
+ t.join().ok().unwrap();
+}
fn child(args: (int, int, int, int, int, int, int, int, int)) {
let (i1, i2, i3, i4, i5, i6, i7, i8, i9) = args;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
pub fn main() { test05(); }
fn test05() {
let (tx, rx) = channel();
- task::spawn(move|| { test05_start(&tx) });
+ let _t = Thread::spawn(move|| { test05_start(&tx) });
let mut value: int = rx.recv().unwrap();
println!("{}", value);
value = rx.recv().unwrap();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
pub fn main() { test00(); }
fn start() { println!("Started / Finished task."); }
fn test00() {
- task::try(move|| start() );
+ let _ = Thread::spawn(move|| start() ).join();
println!("Completing.");
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
fn start(tx: &Sender<Sender<String>>) {
pub fn main() {
let (tx, rx) = channel();
- let _child = task::spawn(move|| { start(&tx) });
+ let _child = Thread::spawn(move|| { start(&tx) });
let mut c = rx.recv().unwrap();
c.send("A".to_string()).unwrap();
c.send("B".to_string()).unwrap();
- task::deschedule();
+ Thread::yield_now();
}
// except according to those terms.
use std::sync::mpsc::{channel, Sender};
-use std::task;
+use std::thread::Thread;
fn start(tx: &Sender<Sender<int>>) {
let (tx2, _rx) = channel();
- tx.send(tx2);
+ tx.send(tx2).unwrap();
}
pub fn main() {
let (tx, rx) = channel();
- let _child = task::spawn(move|| {
+ let _child = Thread::spawn(move|| {
start(&tx)
});
- let _tx = rx.recv();
+ let _tx = rx.recv().unwrap();
}
// except according to those terms.
use std::sync::mpsc::{channel, Sender};
-use std::task;
+use std::thread::Thread;
fn start(tx: &Sender<int>, start: int, number_of_messages: int) {
let mut i: int = 0;
- while i < number_of_messages { tx.send(start + i); i += 1; }
+ while i< number_of_messages { tx.send(start + i).unwrap(); i += 1; }
}
pub fn main() {
println!("Check that we don't deadlock.");
let (tx, rx) = channel();
- task::try(move|| { start(&tx, 0, 10) });
+ let _ = Thread::spawn(move|| { start(&tx, 0, 10) }).join();
println!("Joined task");
}
// except according to those terms.
use std::sync::mpsc::{channel, Sender};
-use std::task;
+use std::thread::Thread;
pub fn main() {
let (tx, rx) = channel();
while (i > 0) {
println!("{}", i);
let tx = tx.clone();
- task::spawn({let i = i; move|| { child(i, &tx) }});
+ Thread::spawn({let i = i; move|| { child(i, &tx) }}).detach();
i = i - 1;
}
i = 10;
while (i > 0) {
println!("{}", i);
- rx.recv();
+ rx.recv().unwrap();
i = i - 1;
}
fn child(x: int, tx: &Sender<int>) {
println!("{}", x);
- tx.send(x);
+ tx.send(x).unwrap();
}
// except according to those terms.
use std::sync::mpsc::{channel, Sender};
-use std::task;
+use std::thread::Thread;
fn start(tx: &Sender<int>, i0: int) {
let mut i = i0;
while i > 0 {
- tx.send(0);
+ tx.send(0).unwrap();
i = i - 1;
}
}
// the child's point of view the receiver may die. We should
// drop messages on the floor in this case, and not crash!
let (tx, rx) = channel();
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
start(&tx, 10)
});
rx.recv();
// This test is specifically about spawning temporary closures.
-use std::task;
+use std::thread::Thread;
fn f() {
}
pub fn main() {
- task::spawn(move|| f() );
+ let _t = Thread::spawn(move|| f() ).join();
}
#![allow(dead_assignment)]
use std::sync::mpsc::{channel, Sender};
-use std::task;
+use std::thread::Thread;
pub fn main() { test00(); }
let number_of_messages: int = 10;
let tx2 = tx.clone();
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 0, number_of_messages);
});
let tx2 = tx.clone();
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 1, number_of_messages);
});
let tx2 = tx.clone();
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 2, number_of_messages);
});
let tx2 = tx.clone();
- task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
test00_start(&tx2, number_of_messages * 3, number_of_messages);
});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
pub fn main() {
- task::spawn(move|| child("Hello".to_string()) );
+ let _t = Thread::spawn(move|| child("Hello".to_string()) );
}
fn child(_s: String) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
use std::sync::mpsc::channel;
pub fn main() {
let x = box 1;
let x_in_parent = &(*x) as *const int as uint;
- task::spawn(move || {
+ let _t = Thread::spawn(move || {
let x_in_child = &(*x) as *const int as uint;
tx.send(x_in_child).unwrap();
});
// quite quickly and it takes a few seconds for the sockets to get
// recycled.
-use std::sync::mpsc::channel;
use std::io::{TcpListener, Listener, Acceptor, EndOfFile, TcpStream};
-use std::sync::{atomic, Arc};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUint, Ordering};
+use std::sync::mpsc::channel;
use std::thread::Thread;
static N: uint = 8;
let mut l = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = l.socket_name().unwrap();
let mut a = l.listen().unwrap();
- let cnt = Arc::new(atomic::AtomicUint::new(0));
+ let cnt = Arc::new(AtomicUint::new(0));
let (srv_tx, srv_rx) = channel();
let (cli_tx, cli_rx) = channel();
loop {
match a.accept() {
Ok(..) => {
- if cnt.fetch_add(1, atomic::SeqCst) == N * M - 1 {
+ if cnt.fetch_add(1, Ordering::SeqCst) == N * M - 1 {
break
}
}
assert_eq!(srv_rx.iter().take(N - 1).count(), N - 1);
// Everything should have been accepted.
- assert_eq!(cnt.load(atomic::SeqCst), N * M);
+ assert_eq!(cnt.load(Ordering::SeqCst), N * M);
}
use std::io;
use std::time::Duration;
use std::sync::mpsc::channel;
+use std::thread::Thread;
#[cfg_attr(target_os = "freebsd", ignore)]
fn eventual_timeout() {
let (tx1, rx1) = channel();
let (_tx2, rx2) = channel::<()>();
- std::task::spawn(move|| {
+ let _t = Thread::spawn(move|| {
let _l = TcpListener::bind(addr).unwrap().listen();
tx1.send(()).unwrap();
let _ = rx2.recv();
use std::io::{fs, TempDir};
use std::io;
use std::os;
-use std::task;
use std::sync::mpsc::channel;
+use std::thread::Thread;
fn test_tempdir() {
let path = {
tx.send(tmp.path().clone()).unwrap();
panic!("panic to unwind past `tmp`");
};
- task::try(f);
+ let _ = Thread::spawn(f).join();
let path = rx.recv().unwrap();
assert!(!path.exists());
let _tmp = tmp;
panic!("panic to unwind past `tmp`");
};
- task::try(f);
+ let _ = Thread::spawn(f).join();
assert!(!path.exists());
let path;
let f = move|:| {
TempDir::new("test_rm_tempdir").unwrap()
};
- let tmp = task::try(f).ok().expect("test_rm_tmdir");
+ let tmp = Thread::spawn(f).join().ok().expect("test_rm_tmdir");
path = tmp.path().clone();
assert!(path.exists());
}
let path;
{
let tmp = TempDir::new("test_rm_tempdir").unwrap();
- path = tmp.unwrap();
+ path = tmp.into_inner();
}
assert!(path.exists());
fs::rmdir_recursive(&path);
tmp.close();
panic!("panic when unwinding past `tmp`");
};
- task::try(f);
+ let _ = Thread::spawn(f).join();
let path = rx.recv().unwrap();
assert!(!path.exists());
tmp.close();
panic!("panic when unwinding past `tmp`");
};
- task::try(f);
+ let _ = Thread::spawn(f).join();
assert!(!path.exists());
let path;
let f = move|:| {
TempDir::new("test_rm_tempdir").unwrap()
};
- let tmp = task::try(f).ok().expect("test_rm_tmdir");
+ let tmp = Thread::spawn(f).join().ok().expect("test_rm_tmdir");
path = tmp.path().clone();
assert!(path.exists());
tmp.close();
let path;
{
let tmp = TempDir::new("test_rm_tempdir").unwrap();
- path = tmp.unwrap();
+ path = tmp.into_inner();
}
assert!(path.exists());
fs::rmdir_recursive(&path);
}
pub fn dont_double_panic() {
- let r: Result<(), _> = task::try(move|| {
+ let r: Result<(), _> = Thread::spawn(move|| {
let tmpdir = TempDir::new("test").unwrap();
// Remove the temporary directory so that TempDir sees
// an error on drop
// Panic. If TempDir panics *again* due to the rmdir
// error then the process will abort.
panic!();
- });
+ }).join();
assert!(r.is_err());
}
// Issue #787
// Don't try to clean up uninitialized locals
-use std::task;
+use std::thread::Thread;
fn test_break() { loop { let _x: Box<int> = break; } }
fn test_panic() {
fn f() { let _x: Box<int> = panic!(); }
- task::try(move|| f() );
+ Thread::spawn(move|| f() ).join().err().unwrap();
}
fn test_panic_indirect() {
fn f() -> ! { panic!(); }
fn g() { let _x: Box<int> = f(); }
- task::try(move|| g() );
+ Thread::spawn(move|| g() ).join().err().unwrap();
}
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
pub fn main() {
let mut i = 10;
- while i > 0 { task::spawn({let i = i; move|| child(i)}); i = i - 1; }
+ while i > 0 {
+ Thread::spawn({let i = i; move|| child(i)}).detach();
+ i = i - 1;
+ }
println!("main thread exiting");
}
use std::sync::Arc;
use std::sync::mpsc::channel;
-use std::task;
+use std::thread::Thread;
trait Pet {
fn name(&self, blk: |&str|);
box dogge2 as Box<Pet+Sync+Send>));
let (tx1, rx1) = channel();
let arc1 = arc.clone();
- task::spawn(move|| { check_legs(arc1); tx1.send(()); });
+ let _t1 = Thread::spawn(move|| { check_legs(arc1); tx1.send(()); });
let (tx2, rx2) = channel();
let arc2 = arc.clone();
- task::spawn(move|| { check_names(arc2); tx2.send(()); });
+ let _t2 = Thread::spawn(move|| { check_names(arc2); tx2.send(()); });
let (tx3, rx3) = channel();
let arc3 = arc.clone();
- task::spawn(move|| { check_pedigree(arc3); tx3.send(()); });
+ let _t3 = Thread::spawn(move|| { check_pedigree(arc3); tx3.send(()); });
rx1.recv();
rx2.recv();
rx3.recv();
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that the call operator autoderefs when calling a bounded type parameter.
+
+#![feature(unboxed_closures)]
+
+use std::ops::FnMut;
+
+fn call_with_2(x: &fn(int) -> int) -> int
+{
+ x(2) // look ma, no `*`
+}
+
+fn subtract_22(x: int) -> int { x - 22 }
+
+pub fn main() {
+ let subtract_22: fn(int) -> int = subtract_22;
+ let z = call_with_2(&subtract_22);
+ assert_eq!(z, -20);
+}
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that the call operator autoderefs when calling a bounded type parameter.
+
+#![feature(unboxed_closures)]
+
+use std::ops::FnMut;
+
+fn call_with_2<F>(x: &mut F) -> int
+ where F : FnMut(int) -> int
+{
+ x(2) // look ma, no `*`
+}
+
+pub fn main() {
+ let z = call_with_2(&mut |x| x - 22);
+ assert_eq!(z, -20);
+}
--- /dev/null
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that the call operator autoderefs when calling to an object type.
+
+#![feature(unboxed_closures)]
+
+use std::ops::FnMut;
+
+fn make_adder(x: int) -> Box<FnMut(int)->int + 'static> {
+ box move |y| { x + y }
+}
+
+pub fn main() {
+ let mut adder = make_adder(3);
+ let z = adder(2);
+ println!("{}", z);
+ assert_eq!(z, 5);
+}
+
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
use std::sync::mpsc::{channel, Sender};
+use std::thread::Thread;
fn child(tx: &Sender<Box<uint>>, i: uint) {
tx.send(box i).unwrap();
let mut expected = 0u;
for i in range(0u, n) {
let tx = tx.clone();
- task::spawn(move|| {
+ Thread::spawn(move|| {
child(&tx, i)
- });
+ }).detach();
expected += i;
}
// Make sure the destructor is run for unit-like structs.
use std::boxed::BoxAny;
-use std::task;
+use std::thread::Thread;
struct Foo;
}
pub fn main() {
- let x = task::try(move|| {
+ let x = Thread::spawn(move|| {
let _b = Foo;
- });
+ }).join();
let s = x.unwrap_err().downcast::<&'static str>().unwrap();
assert_eq!(s.as_slice(), "This panic should happen.");
// except according to those terms.
use std::sync::mpsc::{channel, Sender};
-use std::task;
+use std::thread::Thread;
struct complainer {
tx: Sender<bool>,
pub fn main() {
let (tx, rx) = channel();
- task::spawn(move|| f(tx.clone()));
+ let _t = Thread::spawn(move|| f(tx.clone()));
println!("hiiiiiiiii");
assert!(rx.recv().unwrap());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
fn f() {
let _a = box 0i;
}
pub fn main() {
- task::spawn(f);
+ let _t = Thread::spawn(f);
}
}
mod baz {
- use super::foo::{bar, mod};
+ use super::foo::{bar, self};
pub use foo::Third;
}
pub fn main() {
// Chars of 1, 2, 3, and 4 bytes
let chs: Vec<char> = vec!('e', 'é', '€', '\U00010000');
- let s: String = String::from_chars(chs.as_slice()).to_string();
- let schs: Vec<char> = s.as_slice().chars().collect();
+ let s: String = chs.iter().cloned().collect();
+ let schs: Vec<char> = s.chars().collect();
assert!(s.len() == 10u);
- assert!(s.as_slice().char_len() == 4u);
+ assert!(s.chars().count() == 4u);
assert!(schs.len() == 4u);
- assert!(String::from_chars(schs.as_slice()) == s);
- assert!(s.as_slice().char_at(0u) == 'e');
- assert!(s.as_slice().char_at(1u) == 'é');
+ assert!(schs.iter().cloned().collect::<String>() == s);
+ assert!(s.char_at(0u) == 'e');
+ assert!(s.char_at(1u) == 'é');
- assert!((str::is_utf8(s.as_bytes())));
+ assert!((str::from_utf8(s.as_bytes()).is_ok()));
// invalid prefix
- assert!((!str::is_utf8(&[0x80_u8])));
+ assert!((!str::from_utf8(&[0x80_u8]).is_ok()));
// invalid 2 byte prefix
- assert!((!str::is_utf8(&[0xc0_u8])));
- assert!((!str::is_utf8(&[0xc0_u8, 0x10_u8])));
+ assert!((!str::from_utf8(&[0xc0_u8]).is_ok()));
+ assert!((!str::from_utf8(&[0xc0_u8, 0x10_u8]).is_ok()));
// invalid 3 byte prefix
- assert!((!str::is_utf8(&[0xe0_u8])));
- assert!((!str::is_utf8(&[0xe0_u8, 0x10_u8])));
- assert!((!str::is_utf8(&[0xe0_u8, 0xff_u8, 0x10_u8])));
+ assert!((!str::from_utf8(&[0xe0_u8]).is_ok()));
+ assert!((!str::from_utf8(&[0xe0_u8, 0x10_u8]).is_ok()));
+ assert!((!str::from_utf8(&[0xe0_u8, 0xff_u8, 0x10_u8]).is_ok()));
// invalid 4 byte prefix
- assert!((!str::is_utf8(&[0xf0_u8])));
- assert!((!str::is_utf8(&[0xf0_u8, 0x10_u8])));
- assert!((!str::is_utf8(&[0xf0_u8, 0xff_u8, 0x10_u8])));
- assert!((!str::is_utf8(&[0xf0_u8, 0xff_u8, 0xff_u8, 0x10_u8])));
+ assert!((!str::from_utf8(&[0xf0_u8]).is_ok()));
+ assert!((!str::from_utf8(&[0xf0_u8, 0x10_u8]).is_ok()));
+ assert!((!str::from_utf8(&[0xf0_u8, 0xff_u8, 0x10_u8]).is_ok()));
+ assert!((!str::from_utf8(&[0xf0_u8, 0xff_u8, 0xff_u8, 0x10_u8]).is_ok()));
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
-use std::sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Relaxed};
+use std::sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering};
use std::rand::{thread_rng, Rng, Rand};
+use std::thread::Thread;
const REPEATS: uint = 5;
const MAX_LEN: uint = 32;
impl Rand for DropCounter {
fn rand<R: Rng>(rng: &mut R) -> DropCounter {
// (we're not using this concurrently, so Relaxed is fine.)
- let num = creation_count.fetch_add(1, Relaxed);
+ let num = creation_count.fetch_add(1, Ordering::Relaxed);
DropCounter {
x: rng.gen(),
creation_id: num
impl Drop for DropCounter {
fn drop(&mut self) {
- drop_counts[self.creation_id].fetch_add(1, Relaxed);
+ drop_counts[self.creation_id].fetch_add(1, Ordering::Relaxed);
}
}
for _ in range(0, REPEATS) {
// reset the count for these new DropCounters, so their
// IDs start from 0.
- creation_count.store(0, Relaxed);
+ creation_count.store(0, Ordering::Relaxed);
let main = thread_rng().gen_iter::<DropCounter>()
.take(len)
for panic_countdown in range(0i, count) {
// refresh the counters.
for c in drop_counts.iter() {
- c.store(0, Relaxed);
+ c.store(0, Ordering::Relaxed);
}
let v = main.clone();
- let _ = task::try(move|| {
- let mut v = v;
- let mut panic_countdown = panic_countdown;
- v.as_mut_slice().sort_by(|a, b| {
- if panic_countdown == 0 {
- panic!()
- }
- panic_countdown -= 1;
- a.cmp(b)
- })
- });
+ let _ = Thread::spawn(move|| {
+ let mut v = v;
+ let mut panic_countdown = panic_countdown;
+ v.as_mut_slice().sort_by(|a, b| {
+ if panic_countdown == 0 {
+ panic!()
+ }
+ panic_countdown -= 1;
+ a.cmp(b)
+ })
+ }).join();
// check that the number of things dropped is exactly
// what we expect (i.e. the contents of `v`).
for (i, c) in drop_counts.iter().enumerate().take(len) {
- let count = c.load(Relaxed);
+ let count = c.load(Ordering::Relaxed);
assert!(count == 1,
"found drop count == {} for i == {}, len == {}",
count, i, len);
extern crate libc;
use std::io::process::Command;
-use std::iter::IteratorExt;
-use std::str::from_str;
use libc::funcs::posix88::unistd;
for (line_no, line) in ps_output.split('\n').enumerate() {
if 0 < line_no && 0 < line.len() &&
- my_pid == from_str(line.split(' ').filter(|w| 0 < w.len()).nth(1)
- .expect("1st column should be PPID")
- ).expect("PPID string into integer") &&
+ my_pid == line.split(' ').filter(|w| 0 < w.len()).nth(1)
+ .expect("1st column should be PPID")
+ .parse()
+ .expect("PPID string into integer") &&
line.contains("defunct") {
panic!("Zombie child {}", line);
}
fn main() {
let too_long = format!("/NoSuchCommand{:0300}", 0u8);
- let _failures = Vec::from_fn(100, |_i| {
+ let _failures = range(0, 100).map(|_| {
let cmd = Command::new(too_long.as_slice());
let failed = cmd.spawn();
assert!(failed.is_err(), "Make sure the command fails to spawn(): {}", cmd);
failed
- });
+ }).collect::<Vec<_>>();
find_zombies();
// then _failures goes out of scope
extern crate "weak-lang-items" as other;
-use std::task;
+use std::thread::Thread;
fn main() {
- let _ = task::try(move|| {
+ let _ = Thread::spawn(move|| {
other::foo()
});
}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that the `wf` checker properly handles bound regions in object
+// types. Compiling this code used to trigger an ICE.
+
+pub struct Context<'tcx> {
+ vec: &'tcx Vec<int>
+}
+
+pub type Cmd<'a> = &'a int;
+
+pub type DecodeInlinedItem<'a> =
+ Box<for<'tcx> FnMut(Cmd, &Context<'tcx>) -> Result<&'tcx int, ()> + 'a>;
+
+fn foo(d: DecodeInlinedItem) {
+}
+
+fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::task;
+use std::thread::Thread;
pub fn main() {
let mut i: int = 0;
- while i < 100 { i = i + 1; println!("{}", i); task::deschedule(); }
+ while i < 100 { i = i + 1; println!("{}", i); Thread::yield_now(); }
}