I assume since both shifts say the same thing, I should fix both of them, but then I realized I don't strictly know about left shift.
Fixes #23421
r? @pnkfelix
# Detect 64 bit linux systems with 32 bit userland and force 32 bit compilation
if [ $CFG_OSTYPE = unknown-linux-gnu -a $CFG_CPUTYPE = x86_64 ]
then
- file -L "$SHELL" | grep -q "x86[_-]64"
- if [ $? != 0 ]; then
- CFG_CPUTYPE=i686
+ # $SHELL does not exist in standard 'sh', so probably only exists
+ # if configure is running in an interactive bash shell. /usr/bin/env
+ # exists *everywhere*.
+ BIN_TO_PROBE="$SHELL"
+ if [ -z "$BIN_TO_PROBE" -a -e "/usr/bin/env" ]; then
+ BIN_TO_PROBE="/usr/bin/env"
fi
+ if [ -n "$BIN_TO_PROBE" ]; then
+ file -L "$BIN_TO_PROBE" | grep -q "x86[_-]64"
+ if [ $? != 0 ]; then
+ CFG_CPUTYPE=i686
+ fi
+ fi
fi
#![feature(std_misc)]
#![feature(test)]
#![feature(path_ext)]
+#![feature(convert)]
+#![feature(str_char)]
#![deny(warnings)]
fn opt_path(m: &getopts::Matches, nm: &str) -> PathBuf {
match m.opt_str(nm) {
- Some(s) => PathBuf::new(&s),
+ Some(s) => PathBuf::from(&s),
None => panic!("no option (=path) found for {}", nm),
}
}
compile_lib_path: matches.opt_str("compile-lib-path").unwrap(),
run_lib_path: matches.opt_str("run-lib-path").unwrap(),
rustc_path: opt_path(matches, "rustc-path"),
- clang_path: matches.opt_str("clang-path").map(|s| PathBuf::new(&s)),
+ clang_path: matches.opt_str("clang-path").map(|s| PathBuf::from(&s)),
valgrind_path: matches.opt_str("valgrind-path"),
force_valgrind: matches.opt_present("force-valgrind"),
- llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| PathBuf::new(&s)),
+ llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| PathBuf::from(&s)),
src_base: opt_path(matches, "src-base"),
build_base: opt_path(matches, "build-base"),
aux_base: opt_path(matches, "aux-base"),
mode: matches.opt_str("mode").unwrap().parse().ok().expect("invalid mode"),
run_ignored: matches.opt_present("ignored"),
filter: filter,
- logfile: matches.opt_str("logfile").map(|s| PathBuf::new(&s)),
+ logfile: matches.opt_str("logfile").map(|s| PathBuf::from(&s)),
runtool: matches.opt_str("runtool"),
host_rustcflags: matches.opt_str("host-rustcflags"),
target_rustcflags: matches.opt_str("target-rustcflags"),
pub check_stdout: bool,
// Don't force a --crate-type=dylib flag on the command line
pub no_prefer_dynamic: bool,
- // Don't run --pretty expanded when running pretty printing tests
- pub no_pretty_expanded: bool,
+ // Run --pretty expanded when running pretty printing tests
+ pub pretty_expanded: bool,
// Which pretty mode are we testing with, default to 'normal'
pub pretty_mode: String,
// Only compare pretty output and don't try compiling
let mut force_host = false;
let mut check_stdout = false;
let mut no_prefer_dynamic = false;
- let mut no_pretty_expanded = false;
+ let mut pretty_expanded = false;
let mut pretty_mode = None;
let mut pretty_compare_only = false;
let mut forbid_output = Vec::new();
no_prefer_dynamic = parse_no_prefer_dynamic(ln);
}
- if !no_pretty_expanded {
- no_pretty_expanded = parse_no_pretty_expanded(ln);
+ if !pretty_expanded {
+ pretty_expanded = parse_pretty_expanded(ln);
}
if pretty_mode.is_none() {
force_host: force_host,
check_stdout: check_stdout,
no_prefer_dynamic: no_prefer_dynamic,
- no_pretty_expanded: no_pretty_expanded,
+ pretty_expanded: pretty_expanded,
pretty_mode: pretty_mode.unwrap_or("normal".to_string()),
pretty_compare_only: pretty_compare_only,
forbid_output: forbid_output,
parse_name_directive(line, "no-prefer-dynamic")
}
-fn parse_no_pretty_expanded(line: &str) -> bool {
- parse_name_directive(line, "no-pretty-expanded")
+fn parse_pretty_expanded(line: &str) -> bool {
+ parse_name_directive(line, "pretty-expanded")
}
fn parse_pretty_mode(line: &str) -> Option<String> {
fn parse_pp_exact(line: &str, testfile: &Path) -> Option<PathBuf> {
match parse_name_value_directive(line, "pp-exact") {
- Some(s) => Some(PathBuf::new(&s)),
+ Some(s) => Some(PathBuf::from(&s)),
None => {
if parse_name_directive(line, "pp-exact") {
- testfile.file_name().map(|s| PathBuf::new(s))
+ testfile.file_name().map(|s| PathBuf::from(s))
} else {
None
}
}
fn parse_name_directive(line: &str, directive: &str) -> bool {
- line.contains(directive)
+ // This 'no-' rule is a quick hack to allow pretty-expanded and no-pretty-expanded to coexist
+ line.contains(directive) && !line.contains(&("no-".to_string() + directive))
}
pub fn parse_name_value_directive(line: &str, directive: &str)
if !proc_res.status.success() {
fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
}
- if props.no_pretty_expanded { return }
+ if !props.pretty_expanded { return }
// additionally, run `--pretty expanded` and try to build it.
let proc_res = print_source(config, props, testfile, srcs[round].clone(), "expanded");
}
fn output_testname(testfile: &Path) -> PathBuf {
- PathBuf::new(testfile.file_stem().unwrap())
+ PathBuf::from(testfile.file_stem().unwrap())
}
fn output_base_name(config: &Config, testfile: &Path) -> PathBuf {
error: aborting due to previous error
```
-It mentions that "captured outer variable in an `FnMut` closure".
-Because we declared the closure as a moving closure, and it referred
-to `numbers`, the closure will try to take ownership of the
-vector. But the closure itself is created in a loop, and hence we will
-actually create three closures, one for every iteration of the
-loop. This means that all three of those closures would try to own
-`numbers`, which is impossible -- `numbers` must have just one
-owner. Rust detects this and gives us the error: we claim that
-`numbers` has ownership, but our code tries to make three owners. This
-may cause a safety problem, so Rust disallows it.
+This is a little confusing because there are two closures here: the one passed
+to `map`, and the one passed to `thread::scoped`. In this case, the closure for
+`thread::scoped` is attempting to reference `numbers`, a `Vec<i32>`. This
+closure is a `FnOnce` closure, as that’s what `thread::scoped` takes as an
+argument. `FnOnce` closures take ownership of their environment. That’s fine,
+but there’s one detail: because of `map`, we’re going to make three of these
+closures. And since all three try to take ownership of `numbers`, that would be
+a problem. That’s what it means by ‘cannot move out of captured outer
+variable’: our `thread::scoped` closure wants to take ownership, and it can’t,
+because the closure for `map` won’t let it.
What to do here? Rust has two types that helps us: `Arc<T>` and `Mutex<T>`.
*Arc* stands for "atomically reference counted". In other words, an Arc will
containing module. Attributes on the anonymous crate module define important
metadata that influences the behavior of the compiler.
-```{.rust}
-# #![allow(unused_attribute)]
+```no_run
// Crate name
#![crate_name = "projx"]
An example of `use` declarations:
```
+# #![feature(core)]
use std::iter::range_step;
use std::option::Option::{Some, None};
use std::collections::hash_map::{self, HashMap};
An example of what will and will not work for `use` items:
```
+# #![feature(core)]
# #![allow(unused_imports)]
use foo::core::iter; // good: foo is at the root of the crate
use foo::baz::foobaz; // good: foo is at the root of the crate
terminated by a semicolon.
```
+# #![feature(libc)]
extern crate libc;
use libc::{c_char, FILE};
* [More Strings](more-strings.md)
* [Patterns](patterns.md)
* [Method Syntax](method-syntax.md)
+ * [Associated Types](associated-types.md)
* [Closures](closures.md)
* [Iterators](iterators.md)
* [Generics](generics.md)
--- /dev/null
+% Associated Types
+
+Associated types are a powerful part of Rust's type system. They're related to
+the idea of a 'type family', in other words, grouping multiple types together. That
+description is a bit abstract, so let's dive right into an example. If you want
+to write a `Graph` trait, you have two types to be generic over: the node type
+and the edge type. So you might write a trait, `Graph<N, E>`, that looks like
+this:
+
+```rust
+trait Graph<N, E> {
+ fn has_edge(&self, &N, &N) -> bool;
+ fn edges(&self, &N) -> Vec<E>;
+ // etc
+}
+```
+
+While this sort of works, it ends up being awkward. For example, any function
+that wants to take a `Graph` as a parameter now _also_ needs to be generic over
+the `N`ode and `E`dge types too:
+
+```rust,ignore
+fn distance<N, E, G: Graph<N, E>>(graph: &G, start: &N, end: &N) -> u32 { ... }
+```
+
+Our distance calculation works regardless of our `Edge` type, so the `E` stuff in
+this signature is just a distraction.
+
+What we really want to say is that a certain `E`dge and `N`ode type come together
+to form each kind of `Graph`. We can do that with associated types:
+
+```rust
+trait Graph {
+ type N;
+ type E;
+
+ fn has_edge(&self, &Self::N, &Self::N) -> bool;
+ fn edges(&self, &Self::N) -> Vec<Self::E>;
+ // etc
+}
+```
+
+Now, our clients can be abstract over a given `Graph`:
+
+```rust,ignore
+fn distance<G: Graph>(graph: &G, start: &G::N, end: &G::N) -> uint { ... }
+```
+
+No need to deal with the `E`dge type here!
+
+Let's go over all this in more detail.
+
+## Defining associated types
+
+Let's build that `Graph` trait. Here's the definition:
+
+```rust
+trait Graph {
+ type N;
+ type E;
+
+ fn has_edge(&self, &Self::N, &Self::N) -> bool;
+ fn edges(&self, &Self::N) -> Vec<Self::E>;
+}
+```
+
+Simple enough. Associated types use the `type` keyword, and go inside the body
+of the trait, with the functions.
+
+These `type` declarations can have all the same thing as functions do. For example,
+if we wanted our `N` type to implement `Display`, so we can print the nodes out,
+we could do this:
+
+```rust
+use std::fmt;
+
+trait Graph {
+ type N: fmt::Display;
+ type E;
+
+ fn has_edge(&self, &Self::N, &Self::N) -> bool;
+ fn edges(&self, &Self::N) -> Vec<Self::E>;
+}
+```
+
+## Implementing associated types
+
+Just like any trait, traits that use associated types use the `impl` keyword to
+provide implementations. Here's a simple implementation of Graph:
+
+```rust
+# trait Graph {
+# type N;
+# type E;
+# fn has_edge(&self, &Self::N, &Self::N) -> bool;
+# fn edges(&self, &Self::N) -> Vec<Self::E>;
+# }
+struct Node;
+
+struct Edge;
+
+struct MyGraph;
+
+impl Graph for MyGraph {
+ type N = Node;
+ type E = Edge;
+
+ fn has_edge(&self, n1: &Node, n2: &Node) -> bool {
+ true
+ }
+
+ fn edges(&self, n: &Node) -> Vec<Edge> {
+ Vec::new()
+ }
+}
+```
+
+This silly implementation always returns `true` and an empty `Vec<Edge>`, but it
+gives you an idea of how to implement this kind of thing. We first need three
+`struct`s, one for the graph, one for the node, and one for the edge. If it made
+more sense to use a different type, that would work as well, we're just going to
+use `struct`s for all three here.
+
+Next is the `impl` line, which is just like implementing any other trait.
+
+From here, we use `=` to define our associated types. The name the trait uses
+goes on the left of the `=`, and the concrete type we're `impl`ementing this
+for goes on the right. Finally, we use the concrete types in our function
+declarations.
+
+## Trait objects with associated types
+
+There’s one more bit of syntax we should talk about: trait objects. If you
+try to create a trait object from an associated type, like this:
+
+```rust,ignore
+# trait Graph {
+# type N;
+# type E;
+# fn has_edge(&self, &Self::N, &Self::N) -> bool;
+# fn edges(&self, &Self::N) -> Vec<Self::E>;
+# }
+# struct Node;
+# struct Edge;
+# struct MyGraph;
+# impl Graph for MyGraph {
+# type N = Node;
+# type E = Edge;
+# fn has_edge(&self, n1: &Node, n2: &Node) -> bool {
+# true
+# }
+# fn edges(&self, n: &Node) -> Vec<Edge> {
+# Vec::new()
+# }
+# }
+let graph = MyGraph;
+let obj = Box::new(graph) as Box<Graph>;
+```
+
+You’ll get two errors:
+
+```text
+error: the value of the associated type `E` (from the trait `main::Graph`) must
+be specified [E0191]
+let obj = Box::new(graph) as Box<Graph>;
+ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+24:44 error: the value of the associated type `N` (from the trait
+`main::Graph`) must be specified [E0191]
+let obj = Box::new(graph) as Box<Graph>;
+ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+```
+
+We can’t create a trait object like this, becuase we don’t know the associated
+types. Instead, we can write this:
+
+```rust
+# trait Graph {
+# type N;
+# type E;
+# fn has_edge(&self, &Self::N, &Self::N) -> bool;
+# fn edges(&self, &Self::N) -> Vec<Self::E>;
+# }
+# struct Node;
+# struct Edge;
+# struct MyGraph;
+# impl Graph for MyGraph {
+# type N = Node;
+# type E = Edge;
+# fn has_edge(&self, n1: &Node, n2: &Node) -> bool {
+# true
+# }
+# fn edges(&self, n: &Node) -> Vec<Edge> {
+# Vec::new()
+# }
+# }
+let graph = MyGraph;
+let obj = Box::new(graph) as Box<Graph<N=Node, E=Edge>>;
+```
+
+The `N=Node` syntax allows us to provide a concrete type, `Node`, for the `N`
+type parameter. Same with `E=Edge`. If we didn’t proide this constraint, we
+couldn’t be sure which `impl` to match this trait object to.
There are also a few things you can do with a tuple as a whole, without
destructuring. You can assign one tuple into another, if they have the same
-contained types and arity. Tuples have the same arity when they have the same
+contained types and [arity]. Tuples have the same arity when they have the same
length.
```rust
and with a struct, we have actual names.
There _is_ one case when a tuple struct is very useful, though, and that's a
-tuple struct with only one element. We call this a *newtype*, because it lets
-you create a new type that's similar to another one:
+tuple struct with only one element. We call this the *newtype* pattern, because
+it allows you to create a new type, distinct from that of its contained value
+and expressing its own semantic meaning:
```{rust}
struct Inches(i32);
Finally, Rust has a "sum type", an *enum*. Enums are an incredibly useful
feature of Rust, and are used throughout the standard library. An `enum` is
-a type which ties a set of alternates to a specific name. For example, below
+a type which relates a set of alternates to a specific name. For example, below
we define `Character` to be either a `Digit` or something else. These
can be used via their fully scoped names: `Character::Other` (more about `::`
below).
}
```
-An `enum` variant can be defined as most normal types. Below are some example
-types which also would be allowed in an `enum`.
+Most normal types are allowed as the variant components of an `enum`. Here are
+some examples:
```rust
struct Empty;
struct HeightDatabase(Vec<i32>);
```
-So you see that depending on the sub-datastructure, the `enum` variant, same as
-a struct, may or may not hold data. That is, in `Character`, `Digit` is a name
-tied to an `i32` where `Other` is just a name. However, the fact that they are
-distinct makes this very useful.
+You see that, depending on its type, an `enum` variant may or may not hold data.
+In `Character`, for instance, `Digit` gives a meaningful name for an `i32`
+value, where `Other` is only a name. However, the fact that they represent
+distinct categories of `Character` is a very useful property.
-As with structures, enums don't by default have access to operators such as
-compare ( `==` and `!=`), binary operations (`*` and `+`), and order
-(`<` and `>=`). As such, using the previous `Character` type, the
-following code is invalid:
+As with structures, the variants of an enum by default are not comparable with
+equality operators (`==`, `!=`), have no ordering (`<`, `>=`, etc.), and do not
+support other binary operations such as `*` and `+`. As such, the following code
+is invalid for the example `Character` type:
```{rust,ignore}
// These assignments both succeed
```
This may seem rather limiting, but it's a limitation which we can overcome.
-There are two ways: by implementing equality ourselves, or by using the
-[`match`][match] keyword. We don't know enough about Rust to implement equality
-yet, but we can use the `Ordering` enum from the standard library, which does:
+There are two ways: by implementing equality ourselves, or by pattern matching
+variants with [`match`][match] expressions, which you'll learn in the next
+chapter. We don't know enough about Rust to implement equality yet, but we can
+use the `Ordering` enum from the standard library, which does:
```
enum Ordering {
}
```
-Because we did not define `Ordering`, we must import it (from the std
-library) with the `use` keyword. Here's an example of how `Ordering` is
-used:
+Because `Ordering` has already been defined for us, we will import it with the
+`use` keyword. Here's an example of how it is used:
```{rust}
use std::cmp::Ordering;
Okay, let's talk about the actual code in the example. `cmp` is a function that
compares two things, and returns an `Ordering`. We return either
-`Ordering::Less`, `Ordering::Greater`, or `Ordering::Equal`, depending on if
-the two values are less, greater, or equal. Note that each variant of the
-`enum` is namespaced under the `enum` itself: it's `Ordering::Greater` not
-`Greater`.
+`Ordering::Less`, `Ordering::Greater`, or `Ordering::Equal`, depending on
+whether the first value is less than, greater than, or equal to the second. Note
+that each variant of the `enum` is namespaced under the `enum` itself: it's
+`Ordering::Greater`, not `Greater`.
The `ordering` variable has the type `Ordering`, and so contains one of the
three values. We then do a bunch of `if`/`else` comparisons to check which
one it is.
-This `Ordering::Greater` notation is too long. Let's use `use` to import the
-`enum` variants instead. This will avoid full scoping:
+This `Ordering::Greater` notation is too long. Let's use another form of `use`
+to import the `enum` variants instead. This will avoid full scoping:
```{rust}
use std::cmp::Ordering::{self, Equal, Less, Greater};
```
Importing variants is convenient and compact, but can also cause name conflicts,
-so do this with caution. It's considered good style to rarely import variants
-for this reason.
+so do this with caution. For this reason, it's normally considered better style
+to `use` an enum rather than its variants directly.
-As you can see, `enum`s are quite a powerful tool for data representation, and are
-even more useful when they're [generic][generics] across types. Before we
-get to generics, though, let's talk about how to use them with pattern matching, a
-tool that will let us deconstruct this sum type (the type theory term for enums)
-in a very elegant way and avoid all these messy `if`/`else`s.
+As you can see, `enum`s are quite a powerful tool for data representation, and
+are even more useful when they're [generic][generics] across types. Before we
+get to generics, though, let's talk about how to use enums with pattern
+matching, a tool that will let us deconstruct sum types (the type theory term
+for enums) like `Ordering` in a very elegant way that avoids all these messy
+and brittle `if`/`else`s.
+[arity]: ./glossary.html#arity
[match]: ./match.html
[game]: ./guessing-game.html#comparing-guesses
[generics]: ./generics.html
### `Sync`
-The second of these two trait is called [`Sync`](../std/marker/trait.Sync.html).
+The second of these traits is called [`Sync`](../std/marker/trait.Sync.html).
When a type `T` implements `Sync`, it indicates to the compiler that something
of this type has no possibility of introducing memory unsafety when used from
multiple threads concurrently.
For example, sharing immutable data with an atomic reference count is
threadsafe. Rust provides a type like this, `Arc<T>`, and it implements `Sync`,
-so that it could be safely shared between threads.
+so it is safe to share between threads.
These two traits allow you to use the type system to make strong guarantees
about the properties of your code under concurrency. Before we demonstrate
}
```
-The `Thread::scoped()` method accepts a closure, which is executed in a new
+The `thread::scoped()` method accepts a closure, which is executed in a new
thread. It's called `scoped` because this thread returns a join guard:
```
finished. If we didn't want this behaviour, we could use `thread::spawn()`:
```
+# #![feature(old_io, std_misc)]
use std::thread;
use std::old_io::timer;
use std::time::Duration;
languages. It will not compile:
```ignore
+# #![feature(old_io, std_misc)]
use std::thread;
use std::old_io::timer;
use std::time::Duration;
but for a different reason:
```ignore
+# #![feature(old_io, std_misc)]
use std::thread;
use std::old_io::timer;
use std::time::Duration;
```text
<anon>:11:9: 11:22 error: the trait `core::marker::Send` is not implemented for the type `std::sync::mutex::MutexGuard<'_, collections::vec::Vec<u32>>` [E0277]
-<anon>:11 Thread::spawn(move || {
+<anon>:11 thread::spawn(move || {
^~~~~~~~~~~~~
<anon>:11:9: 11:22 note: `std::sync::mutex::MutexGuard<'_, collections::vec::Vec<u32>>` cannot be sent between threads safely
-<anon>:11 Thread::spawn(move || {
+<anon>:11 thread::spawn(move || {
^~~~~~~~~~~~~
```
We can use `Arc<T>` to fix this. Here's the working version:
```
+# #![feature(old_io, std_misc)]
use std::sync::{Arc, Mutex};
use std::thread;
use std::old_io::timer;
thread more closely:
```
+# #![feature(old_io, std_misc)]
# use std::sync::{Arc, Mutex};
# use std::thread;
# use std::old_io::timer;
is `Send` over the channel!
```
-use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;
% Crates and Modules
-When a project starts getting large, it's considered a good software
+When a project starts getting large, it's considered good software
engineering practice to split it up into a bunch of smaller pieces, and then
fit them together. It's also important to have a well-defined interface, so
that some of your functionality is private, and some is public. To facilitate
two languages for those phrases to be in. We'll use this module layout:
```text
- +-----------+
- +---| greetings |
- | +-----------+
- +---------+ |
- | english |---+
- +---------+ | +-----------+
- | +---| farewells |
-+---------+ | +-----------+
+ +-----------+
+ +---| greetings |
+ | +-----------+
+ +---------+ |
+ +---| english |---+
+ | +---------+ | +-----------+
+ | +---| farewells |
++---------+ | +-----------+
| phrases |---+
-+---------+ | +-----------+
- | +---| greetings |
- +----------+ | +-----------+
- | japanese |---+
- +----------+ |
- | +-----------+
- +---| farewells |
- +-----------+
++---------+ | +-----------+
+ | +---| greetings |
+ | +----------+ | +-----------+
+ +---| japanese |--+
+ +----------+ |
+ | +-----------+
+ +---| farewells |
+ +-----------+
```
In this example, `phrases` is the name of our crate. All of the rest are
`src/lib.rs` look like this:
```
-// in src/lib.rs
-
mod english {
mod greetings {
-
}
mod farewells {
-
}
}
mod japanese {
mod greetings {
-
}
mod farewells {
-
}
}
```
```
If we do that, Rust will expect to find either a `english.rs` file, or a
-`english/mod.rs` file with the contents of our module:
-
-```{rust,ignore}
-// contents of our module go here
-```
+`english/mod.rs` file with the contents of our module.
Note that in these files, you don't need to re-declare the module: that's
already been done with the initial `mod` declaration.
`src/lib.rs` is our crate root, and looks like this:
```{rust,ignore}
-// in src/lib.rs
-
mod english;
-
mod japanese;
```
like this:
```{rust,ignore}
-// both src/english/mod.rs and src/japanese/mod.rs
-
mod greetings;
-
mod farewells;
```
Put this in `src/english/greetings.rs`:
```rust
-// in src/english/greetings.rs
-
fn hello() -> String {
"Hello!".to_string()
}
Put this in `src/english/farewells.rs`:
```rust
-// in src/english/farewells.rs
-
fn goodbye() -> String {
"Goodbye.".to_string()
}
Put this in `src/japanese/farewells.rs`:
```rust
-// in src/japanese/farewells.rs
-
fn goodbye() -> String {
"さようなら".to_string()
}
We have a library crate. Let's make an executable crate that imports and uses
our library.
-Make a `src/main.rs` and put this in it: (it won't quite compile yet)
+Make a `src/main.rs` and put this in it (it won't quite compile yet):
```rust,ignore
-// in src/main.rs
-
extern crate phrases;
fn main() {
to just this:
```{rust,ignore}
-// in src/main.rs
-
extern crate phrases;
fn main() {
In our `src/lib.rs`, let's add `pub` to the `english` module declaration:
```{rust,ignore}
-// in src/lib.rs
-
pub mod english;
-
mod japanese;
```
And in our `src/english/mod.rs`, let's make both `pub`:
```{rust,ignore}
-// in src/english/mod.rs
-
pub mod greetings;
-
pub mod farewells;
```
In our `src/english/greetings.rs`, let's add `pub` to our `fn` declaration:
```{rust,ignore}
-// in src/english/greetings.rs
-
pub fn hello() -> String {
"Hello!".to_string()
}
And also in `src/english/farewells.rs`:
```{rust,ignore}
-// in src/english/farewells.rs
-
pub fn goodbye() -> String {
"Goodbye.".to_string()
}
Let's change our `src/main.rs` to look like this:
```{rust,ignore}
-// in src/main.rs
-
extern crate phrases;
use phrases::english::greetings;
}
```
-But it is not idiomatic. This is significantly more likely to introducing a
+But it is not idiomatic. This is significantly more likely to introduce a
naming conflict. In our short program, it's not a big deal, but as it grows, it
becomes a problem. If we have conflicting names, Rust will give a compilation
error. For example, if we made the `japanese` functions public, and tried to do
```
If we're importing multiple names from the same module, we don't have to type it out
-twice. Rust has a shortcut syntax for writing this:
+twice. Instead of this:
```{rust,ignore}
use phrases::english::greetings;
use phrases::english::farewells;
```
-You use curly braces:
+We can use this shortcut:
```{rust,ignore}
use phrases::english::{greetings, farewells};
```
-These two declarations are equivalent, but the second is a lot less typing.
-
## Re-exporting with `pub use`
You don't just use `use` to shorten identifiers. You can also use it inside of your crate
Let's look at an example. Modify your `src/main.rs` to read like this:
```{rust,ignore}
-// in src/main.rs
-
extern crate phrases;
use phrases::english::{greetings,farewells};
Then, modify your `src/lib.rs` to make the `japanese` mod public:
```{rust,ignore}
-// in src/lib.rs
-
pub mod english;
-
pub mod japanese;
```
Next, make the two functions public, first in `src/japanese/greetings.rs`:
```{rust,ignore}
-// in src/japanese/greetings.rs
-
pub fn hello() -> String {
"こんにちは".to_string()
}
And then in `src/japanese/farewells.rs`:
```{rust,ignore}
-// in src/japanese/farewells.rs
-
pub fn goodbye() -> String {
"さようなら".to_string()
}
Finally, modify your `src/japanese/mod.rs` to read like this:
```{rust,ignore}
-// in src/japanese/mod.rs
-
pub use self::greetings::hello;
pub use self::farewells::goodbye;
mod greetings;
-
mod farewells;
```
}
```
-Here's the full algorithm:
-
-1. Given a code block, if it does not contain `fn main()`, it is wrapped in
- `fn main() { your_code }`
-2. Given that result, if it contains no `extern crate` directives but it also
- contains the name of the crate being tested, then `extern crate <name>` is
- injected at the top.
-3. Some common allow attributes are added for documentation examples at the top.
+Here's the full algorithm rustdoc uses to postprocess examples:
+
+1. Any leading `#![foo]` attributes are left intact as crate attributes.
+2. Some common `allow` attributes are inserted, including
+ `unused_variables`, `unused_assignments`, `unused_mut`,
+ `unused_attributes`, and `dead_code`. Small examples often trigger
+ these lints.
+3. If the example does not contain `extern crate`, then `extern crate
+ <mycrate>;` is inserted.
+2. Finally, if the example does not contain `fn main`, the remainder of the
+ text is wrapped in `fn main() { your_code }`
Sometimes, this isn't enough, though. For example, all of these code samples
with `///` we've been talking about? The raw text:
compiles, while only showing the parts that are relevant to that part of your
explanation.
+### Documenting macros
+
+Here’s an example of documenting a macro:
+
+```
+/// Panic with a given message unless an expression evaluates to true.
+///
+/// # Examples
+///
+/// ```
+/// # #[macro_use] extern crate foo;
+/// # fn main() {
+/// panic_unless!(1 + 1 == 2, “Math is broken.”);
+/// # }
+/// ```
+///
+/// ```should_fail
+/// # #[macro_use] extern crate foo;
+/// # fn main() {
+/// panic_unless!(true == false, “I’m broken.”);
+/// # }
+/// ```
+#[macro_export]
+macro_rules! panic_unless {
+ ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });
+}
+# fn main() {}
+```
+
+You’ll note three things: we need to add our own `extern crate` line, so that
+we can add the `#[macro_use]` attribute. Second, we’ll need to add our own
+`main()` as well. Finally, a judicious use of `#` to comment out those two
+things, so they don’t show up in the output.
+
+### Running documentation tests
+
To run the tests, either
```bash
compile if snappy is installed:
```no_run
+# #![feature(libc)]
extern crate libc;
use libc::size_t;
The `extern` block can be extended to cover the entire snappy API:
```no_run
+# #![feature(libc)]
extern crate libc;
use libc::{c_int, size_t};
the allocated memory. The length is less than or equal to the capacity.
```
+# #![feature(libc)]
# extern crate libc;
# use libc::{c_int, size_t};
# unsafe fn snappy_validate_compressed_buffer(_: *const u8, _: size_t) -> c_int { 0 }
the true length after compression for setting the length.
```
+# #![feature(libc)]
# extern crate libc;
# use libc::{size_t, c_int};
# unsafe fn snappy_compress(a: *const u8, b: size_t, c: *mut u8,
format and `snappy_uncompressed_length` will retrieve the exact buffer size required.
```
+# #![feature(libc)]
# extern crate libc;
# use libc::{size_t, c_int};
# unsafe fn snappy_uncompress(compressed: *const u8,
blocks with the `static` keyword:
```no_run
+# #![feature(libc)]
extern crate libc;
#[link(name = "readline")]
them.
```no_run
+# #![feature(libc)]
extern crate libc;
use std::ffi::CString;
conventions. Rust provides a way to tell the compiler which convention to use:
```
+# #![feature(libc)]
extern crate libc;
#[cfg(all(target_os = "win32", target_arch = "x86"))]
advanced iterators, including ones that are infinite. Like `count`:
```rust
+# #![feature(core)]
std::iter::count(1, 5);
```
iterator from before, `count()`:
```rust
+# #![feature(core)]
for i in std::iter::count(1, 5).take(5) {
println!("{}", i);
}
Here's how it works:
```{rust}
+# #![feature(core)]
struct Circle {
x: f64,
y: f64,
can do it by returning `self`.
```
+# #![feature(core)]
struct Circle {
x: f64,
y: f64,
the builder pattern instead. It looks like this:
```
+# #![feature(core)]
struct Circle {
x: f64,
y: f64,
Rust has two main types of strings: `&str` and `String`.
-# &str
+# `&str`
The first kind is a `&str`. This is pronounced a 'string slice'.
String literals are of the type `&str`:
means that they're a 'view' into an already-allocated string, such as a
string literal or a `String`.
-# String
+## `str`
+
+You may occasionally see references to a `str` type, without the `&`. While
+this type does exist, it’s not something you want to use yourself. Sometimes,
+people confuse `str` for `String`, and write this:
+
+```rust
+struct S {
+ s: str,
+}
+```
+
+This leads to ugly errors:
+
+```text
+error: the trait `core::marker::Sized` is not implemented for the type `str` [E0277]
+note: `str` does not have a constant size known at compile-time
+```
+
+Instead, this `struct` should be
+
+```rust
+struct S {
+ s: String,
+}
+```
+
+So let’s talk about `String`s.
+
+# `String`
A `String` is a heap-allocated string. This string is growable, and is
also guaranteed to be UTF-8. `String`s are commonly created by
Usually, the `graphemes()` method on `&str` is what you want:
```
+# #![feature(unicode)]
let s = "u͔n͈̰̎i̙̮͚̦c͚̉o̼̩̰͗d͔̆̓ͥé";
for l in s.graphemes(true) {
### Examples
-Here are some examples of functions with elided lifetimes, and the version of
-what the elided lifetimes are expand to:
+Here are some examples of functions with elided lifetimes. We've paired each
+example of an elided lifetime with its expanded form.
```{rust,ignore}
fn print(s: &str); // elided
However, boxes do _not_ use reference counting or garbage collection. Boxes are
what's called an *affine type*. This means that the Rust compiler, at compile
time, determines when the box comes into and goes out of scope, and inserts the
-appropriate calls there. Furthermore, boxes are a specific kind of affine type,
-known as a *region*. You can read more about regions [in this paper on the
-Cyclone programming
-language](http://www.cs.umd.edu/projects/cyclone/papers/cyclone-regions.pdf).
+appropriate calls there.
-You don't need to fully grok the theory of affine types or regions to grok
-boxes, though. As a rough approximation, you can treat this Rust code:
+You don't need to fully grok the theory of affine types to grok boxes, though.
+As a rough approximation, you can treat this Rust code:
```{rust}
{
and then prints it back out:
```{rust,ignore}
-fn main() {
+corefn main() {
println!("Type something!");
let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");
the `use` statement to import it in:
```{rust}
+# #![feature(old_io)]
use std::old_io::stdin;
stdin();
to import the module, and only use one level of qualification:
```{rust}
+# #![feature(old_io)]
use std::old_io;
old_io::stdin();
the error case explicitly. `expect()` allows us to give an error message if
this crash happens.
-We will cover the exact details of how all of this works later in the Guide.
-For now, this gives you enough of a basic understanding to work with.
+We will cover the exact details of how all of this works later in the Guide in
+[Error Handling]. For now, this gives you enough of a basic understanding to
+work with.
Back to the code we were working on! Here's a refresher:
That's all you need to get basic input from the standard input! It's not too
complicated, but there are a number of small parts.
+
+
+[Error Handling]: ./error-handling.html
argument as used.
```rust
+# #![feature(test)]
+
extern crate test;
# fn main() {
syntax?
```{rust}
+# #![feature(core)]
struct Circle {
x: f64,
y: f64,
signature, then implement the trait for that struct. Like this:
```{rust}
+# #![feature(core)]
struct Circle {
x: f64,
y: f64,
Here's an extended example of how this works:
```{rust}
+# #![feature(core)]
trait HasArea {
fn area(&self) -> f64;
}
everything is fine:
```{rust}
+# #![feature(core)]
use shapes::HasArea;
mod shapes {
to the rescue:
```
+# #![feature(std_misc)]
use std::num::Float;
fn inverse<T: Float>(x: T) -> Result<T, String> {
works just fine:
```
+# #![feature(std_misc)]
# use std::num::Float;
# fn inverse<T: Float>(x: T) -> Result<T, String> {
# if x == Float::zero() { return Err("x cannot be zero!".to_string()) }
reimplementation is as safe as the `Box` type.
```
+# #![feature(libc)]
#![feature(unsafe_destructor)]
extern crate libc;
in the same format as C:
```
+# #![feature(libc)]
#![feature(lang_items, start, no_std)]
#![no_std]
compiler's name mangling too:
```ignore
+# #![feature(libc)]
#![feature(no_std)]
#![no_std]
#![no_main]
vectors provided from C, using idiomatic Rust practices.
```
+# #![feature(libc, core)]
#![feature(lang_items, start, no_std)]
#![no_std]
sugar for dynamic allocations via `malloc` and `free`:
```
+# #![feature(libc)]
#![feature(lang_items, box_syntax, start, no_std)]
#![no_std]
put_const(S_IWUSR, int);
put_const(S_IRUSR, int);
+ put_const(S_IRWXG, int);
+ put_const(S_IXGRP, int);
+ put_const(S_IWGRP, int);
+ put_const(S_IRGRP, int);
+
+ put_const(S_IRWXO, int);
+ put_const(S_IXOTH, int);
+ put_const(S_IWOTH, int);
+ put_const(S_IROTH, int);
+
#ifdef F_OK
put_const(F_OK, int);
#endif
/// task.
///
/// ```
+/// # #![feature(alloc, core)]
/// use std::sync::Arc;
/// use std::thread;
///
/// A weak pointer to an `Arc`.
///
-/// Weak pointers will not keep the data inside of the `Arc` alive, and can be used to break cycles
-/// between `Arc` pointers.
+/// Weak pointers will not keep the data inside of the `Arc` alive, and can be
+/// used to break cycles between `Arc` pointers.
#[unsafe_no_drop_flag]
#[unstable(feature = "alloc",
reason = "Weak pointers may not belong in this module.")]
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::sync::Arc;
///
/// let five = Arc::new(5);
unsafe fn drop_slow(&mut self) {
let ptr = *self._ptr;
- // Destroy the data at this time, even though we may not free the box allocation itself
- // (there may still be weak pointers lying around).
+ // Destroy the data at this time, even though we may not free the box
+ // allocation itself (there may still be weak pointers lying around).
drop(ptr::read(&self.inner().data));
if self.inner().weak.fetch_sub(1, Release) == 1 {
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::sync::Arc;
///
/// let five = Arc::new(5);
impl<T: Send + Sync + Clone> Arc<T> {
/// Make a mutable reference from the given `Arc<T>`.
///
- /// This is also referred to as a copy-on-write operation because the inner data is cloned if
- /// the reference count is greater than one.
+ /// This is also referred to as a copy-on-write operation because the inner
+ /// data is cloned if the reference count is greater than one.
///
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::sync::Arc;
///
/// let mut five = Arc::new(5);
#[inline]
#[unstable(feature = "alloc")]
pub fn make_unique(&mut self) -> &mut T {
- // Note that we hold a strong reference, which also counts as a weak reference, so we only
- // clone if there is an additional reference of either kind.
+ // Note that we hold a strong reference, which also counts as a weak
+ // reference, so we only clone if there is an additional reference of
+ // either kind.
if self.inner().strong.load(SeqCst) != 1 ||
self.inner().weak.load(SeqCst) != 1 {
*self = Arc::new((**self).clone())
}
- // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
- // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
- // this point, and we required the Arc itself to be `mut`, so we're returning the only
- // possible reference to the inner data.
+ // This unsafety is ok because we're guaranteed that the pointer
+ // returned is the *only* pointer that will ever be returned to T. Our
+ // reference count is guaranteed to be 1 at this point, and we required
+ // the Arc itself to be `mut`, so we're returning the only possible
+ // reference to the inner data.
let inner = unsafe { &mut **self._ptr };
&mut inner.data
}
impl<T: Sync + Send> Drop for Arc<T> {
/// Drops the `Arc<T>`.
///
- /// This will decrement the strong reference count. If the strong reference count becomes zero
- /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
+ /// This will decrement the strong reference count. If the strong reference
+ /// count becomes zero and the only other references are `Weak<T>` ones,
+ /// `drop`s the inner value.
///
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::sync::Arc;
///
/// {
/// ```
#[inline]
fn drop(&mut self) {
- // This structure has #[unsafe_no_drop_flag], so this drop glue may run more than once (but
- // it is guaranteed to be zeroed after the first if it's run more than once)
+ // This structure has #[unsafe_no_drop_flag], so this drop glue may run
+ // more than once (but it is guaranteed to be zeroed after the first if
+ // it's run more than once)
let ptr = *self._ptr;
if ptr.is_null() { return }
- // Because `fetch_sub` is already atomic, we do not need to synchronize with other threads
- // unless we are going to delete the object. This same logic applies to the below
- // `fetch_sub` to the `weak` count.
+ // Because `fetch_sub` is already atomic, we do not need to synchronize
+ // with other threads unless we are going to delete the object. This
+ // same logic applies to the below `fetch_sub` to the `weak` count.
if self.inner().strong.fetch_sub(1, Release) != 1 { return }
- // This fence is needed to prevent reordering of use of the data and deletion of the data.
- // Because it is marked `Release`, the decreasing of the reference count synchronizes with
- // this `Acquire` fence. This means that use of the data happens before decreasing the
- // reference count, which happens before this fence, which happens before the deletion of
- // the data.
+ // This fence is needed to prevent reordering of use of the data and
+ // deletion of the data. Because it is marked `Release`, the decreasing
+ // of the reference count synchronizes with this `Acquire` fence. This
+ // means that use of the data happens before decreasing the reference
+ // count, which happens before this fence, which happens before the
+ // deletion of the data.
//
// As explained in the [Boost documentation][1],
//
- // > It is important to enforce any possible access to the object in one thread (through an
- // > existing reference) to *happen before* deleting the object in a different thread. This
- // > is achieved by a "release" operation after dropping a reference (any access to the
- // > object through this reference must obviously happened before), and an "acquire"
- // > operation before deleting the object.
+ // > It is important to enforce any possible access to the object in one
+ // > thread (through an existing reference) to *happen before* deleting
+ // > the object in a different thread. This is achieved by a "release"
+ // > operation after dropping a reference (any access to the object
+ // > through this reference must obviously happened before), and an
+ // > "acquire" operation before deleting the object.
//
// [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
atomic::fence(Acquire);
///
/// Upgrades the `Weak<T>` reference to an `Arc<T>`, if possible.
///
- /// Returns `None` if there were no strong references and the data was destroyed.
+ /// Returns `None` if there were no strong references and the data was
+ /// destroyed.
///
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::sync::Arc;
///
/// let five = Arc::new(5);
/// let strong_five: Option<Arc<_>> = weak_five.upgrade();
/// ```
pub fn upgrade(&self) -> Option<Arc<T>> {
- // We use a CAS loop to increment the strong count instead of a fetch_add because once the
- // count hits 0 is must never be above 0.
+ // We use a CAS loop to increment the strong count instead of a
+ // fetch_add because once the count hits 0 is must never be above 0.
let inner = self.inner();
loop {
let n = inner.strong.load(SeqCst);
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::sync::Arc;
///
/// let weak_five = Arc::new(5).downgrade();
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::sync::Arc;
///
/// {
// see comments above for why this check is here
if ptr.is_null() { return }
- // If we find out that we were the last weak pointer, then its time to deallocate the data
- // entirely. See the discussion in Arc::drop() about the memory orderings
+ // If we find out that we were the last weak pointer, then its time to
+ // deallocate the data entirely. See the discussion in Arc::drop() about
+ // the memory orderings
if self.inner().weak.fetch_sub(1, Release) == 1 {
atomic::fence(Acquire);
unsafe { deallocate(ptr as *mut u8, size_of::<ArcInner<T>>(),
/// The following two examples are equivalent:
///
/// ```
+/// # #![feature(alloc)]
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
///
/// # Examples
/// ```
+/// # #![feature(alloc)]
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// # Examples
///
/// ```
+ /// # #![feature(alloc, core)]
/// let x = Box::new(5);
/// let mut y = Box::new(10);
///
///
/// On failure, return a null pointer and leave the original allocation intact.
///
+/// If the allocation was relocated, the memory at the passed-in pointer is
+/// undefined after the call.
+///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
#![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/")]
+#![doc(test(no_crate_inject))]
#![feature(no_std)]
#![no_std]
//! and have the `Owner` remain allocated as long as any `Gadget` points at it.
//!
//! ```rust
+//! # #![feature(alloc, collections)]
//! use std::rc::Rc;
//!
//! struct Owner {
//!
//! drop(gadget_owner);
//!
-//! // Despite dropping gadget_owner, we're still able to print out the name of
-//! // the Owner of the Gadgets. This is because we've only dropped the
+//! // Despite dropping gadget_owner, we're still able to print out the name
+//! // of the Owner of the Gadgets. This is because we've only dropped the
//! // reference count object, not the Owner it wraps. As long as there are
-//! // other `Rc<T>` objects pointing at the same Owner, it will remain allocated. Notice
-//! // that the `Rc<T>` wrapper around Gadget.owner gets automatically dereferenced
-//! // for us.
+//! // other `Rc<T>` objects pointing at the same Owner, it will remain
+//! // allocated. Notice that the `Rc<T>` wrapper around Gadget.owner gets
+//! // automatically dereferenced for us.
//! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
//! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
//!
//! }
//! ```
//!
-//! If our requirements change, and we also need to be able to traverse from Owner → Gadget, we
-//! will run into problems: an `Rc<T>` pointer from Owner → Gadget introduces a cycle between the
-//! objects. This means that their reference counts can never reach 0, and the objects will remain
-//! allocated: a memory leak. In order to get around this, we can use `Weak<T>` pointers. These
-//! pointers don't contribute to the total count.
+//! If our requirements change, and we also need to be able to traverse from
+//! Owner → Gadget, we will run into problems: an `Rc<T>` pointer from Owner
+//! → Gadget introduces a cycle between the objects. This means that their
+//! reference counts can never reach 0, and the objects will remain allocated: a
+//! memory leak. In order to get around this, we can use `Weak<T>` pointers.
+//! These pointers don't contribute to the total count.
//!
-//! Rust actually makes it somewhat difficult to produce this loop in the first place: in order to
-//! end up with two objects that point at each other, one of them needs to be mutable. This is
-//! problematic because `Rc<T>` enforces memory safety by only giving out shared references to the
-//! object it wraps, and these don't allow direct mutation. We need to wrap the part of the object
-//! we wish to mutate in a `RefCell`, which provides *interior mutability*: a method to achieve
-//! mutability through a shared reference. `RefCell` enforces Rust's borrowing rules at runtime.
-//! Read the `Cell` documentation for more details on interior mutability.
+//! Rust actually makes it somewhat difficult to produce this loop in the first
+//! place: in order to end up with two objects that point at each other, one of
+//! them needs to be mutable. This is problematic because `Rc<T>` enforces
+//! memory safety by only giving out shared references to the object it wraps,
+//! and these don't allow direct mutation. We need to wrap the part of the
+//! object we wish to mutate in a `RefCell`, which provides *interior
+//! mutability*: a method to achieve mutability through a shared reference.
+//! `RefCell` enforces Rust's borrowing rules at runtime. Read the `Cell`
+//! documentation for more details on interior mutability.
//!
//! ```rust
+//! # #![feature(alloc)]
//! use std::rc::Rc;
//! use std::rc::Weak;
//! use std::cell::RefCell;
//! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
//!
//! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
-//! // that their object is still allocated, we need to call upgrade() on them
-//! // to turn them into a strong reference. This returns an Option, which
-//! // contains a reference to our object if it still exists.
+//! // that their object is still allocated, we need to call upgrade()
+//! // on them to turn them into a strong reference. This returns an
+//! // Option, which contains a reference to our object if it still
+//! // exists.
//! let gadget = gadget_opt.upgrade().unwrap();
//! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
//! }
#[unsafe_no_drop_flag]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Rc<T> {
- // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained
- // type via Deref
+ // FIXME #12808: strange names to try to avoid interfering with field
+ // accesses of the contained type via Deref
_ptr: NonZero<*mut RcBox<T>>,
}
pub fn new(value: T) -> Rc<T> {
unsafe {
Rc {
- // there is an implicit weak pointer owned by all the strong pointers, which
- // ensures that the weak destructor never frees the allocation while the strong
- // destructor is running, even if the weak pointer is stored inside the strong one.
+ // there is an implicit weak pointer owned by all the strong
+ // pointers, which ensures that the weak destructor never frees
+ // the allocation while the strong destructor is running, even
+ // if the weak pointer is stored inside the strong one.
_ptr: NonZero::new(boxed::into_raw(box RcBox {
value: value,
strong: Cell::new(1),
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::rc::Rc;
///
/// let five = Rc::new(5);
#[unstable(feature = "alloc")]
pub fn strong_count<T>(this: &Rc<T>) -> usize { this.strong() }
-/// Returns true if there are no other `Rc` or `Weak<T>` values that share the same inner value.
+/// Returns true if there are no other `Rc` or `Weak<T>` values that share the
+/// same inner value.
///
/// # Examples
///
/// ```
+/// # #![feature(alloc)]
/// use std::rc;
/// use std::rc::Rc;
///
/// # Examples
///
/// ```
+/// # #![feature(alloc)]
/// use std::rc::{self, Rc};
///
/// let x = Rc::new(3);
/// # Examples
///
/// ```
+/// # #![feature(alloc)]
/// use std::rc::{self, Rc};
///
/// let mut x = Rc::new(3);
impl<T: Clone> Rc<T> {
/// Make a mutable reference from the given `Rc<T>`.
///
- /// This is also referred to as a copy-on-write operation because the inner data is cloned if
- /// the reference count is greater than one.
+ /// This is also referred to as a copy-on-write operation because the inner
+ /// data is cloned if the reference count is greater than one.
///
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::rc::Rc;
///
/// let mut five = Rc::new(5);
if !is_unique(self) {
*self = Rc::new((**self).clone())
}
- // This unsafety is ok because we're guaranteed that the pointer returned is the *only*
- // pointer that will ever be returned to T. Our reference count is guaranteed to be 1 at
- // this point, and we required the `Rc<T>` itself to be `mut`, so we're returning the only
- // possible reference to the inner value.
+ // This unsafety is ok because we're guaranteed that the pointer
+ // returned is the *only* pointer that will ever be returned to T. Our
+ // reference count is guaranteed to be 1 at this point, and we required
+ // the `Rc<T>` itself to be `mut`, so we're returning the only possible
+ // reference to the inner value.
let inner = unsafe { &mut **self._ptr };
&mut inner.value
}
impl<T> Drop for Rc<T> {
/// Drops the `Rc<T>`.
///
- /// This will decrement the strong reference count. If the strong reference count becomes zero
- /// and the only other references are `Weak<T>` ones, `drop`s the inner value.
+ /// This will decrement the strong reference count. If the strong reference
+ /// count becomes zero and the only other references are `Weak<T>` ones,
+ /// `drop`s the inner value.
///
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::rc::Rc;
///
/// {
if self.strong() == 0 {
ptr::read(&**self); // destroy the contained object
- // remove the implicit "strong weak" pointer now that we've destroyed the
- // contents.
+ // remove the implicit "strong weak" pointer now that we've
+ // destroyed the contents.
self.dec_weak();
if self.weak() == 0 {
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::rc::Rc;
///
/// let five = Rc::new(5);
/// A weak version of `Rc<T>`.
///
-/// Weak references do not count when determining if the inner value should be dropped.
+/// Weak references do not count when determining if the inner value should be
+/// dropped.
///
/// See the [module level documentation](./index.html) for more.
#[unsafe_no_drop_flag]
///
/// Upgrades the `Weak<T>` reference to an `Rc<T>`, if possible.
///
- /// Returns `None` if there were no strong references and the data was destroyed.
+ /// Returns `None` if there were no strong references and the data was
+ /// destroyed.
///
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::rc::Rc;
///
/// let five = Rc::new(5);
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::rc::Rc;
///
/// {
let ptr = *self._ptr;
if !ptr.is_null() {
self.dec_weak();
- // the weak count starts at 1, and will only go to zero if all the strong pointers
- // have disappeared.
+ // the weak count starts at 1, and will only go to zero if all
+ // the strong pointers have disappeared.
if self.weak() == 0 {
deallocate(ptr as *mut u8, size_of::<RcBox<T>>(),
min_align_of::<RcBox<T>>())
/// # Examples
///
/// ```
+ /// # #![feature(alloc)]
/// use std::rc::Rc;
///
/// let weak_five = Rc::new(5).downgrade();
// Destroy the next chunk.
let next = self.next;
let size = calculate_size::<T>(self.capacity);
- deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size,
+ let self_ptr: *mut TypedArenaChunk<T> = self;
+ deallocate(self_ptr as *mut u8, size,
mem::min_align_of::<TypedArenaChunk<T>>());
if !next.is_null() {
let capacity = (*next).capacity;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![9, 1, 2, 7, 3, 2]);
/// ```
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4]);
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::from_vec(vec![1, 3]);
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
/// heap.push(1);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let mut heap = BinaryHeap::new();
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BinaryHeap;
/// let heap = BinaryHeap::from_vec(vec![1, 2, 3, 4, 5, 6, 7]);
/// let vec = heap.into_vec();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BinaryHeap;
///
/// let mut heap = BinaryHeap::from_vec(vec![1, 2, 4, 5, 7]);
//! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
//!
//! ```
+//! # #![feature(collections, core)]
//! use std::collections::{BitSet, BitVec};
//! use std::num::Float;
//! use std::iter;
/// # Examples
///
/// ```
+/// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
impl Index<usize> for BitVec {
type Output = bool;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, i: &usize) -> &bool {
if self.get(*i).expect("index out of bounds") {
&FALSE
}
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, i: usize) -> &bool {
+ if self.get(i).expect("index out of bounds") {
+ &TRUE
+ } else {
+ &FALSE
+ }
+ }
}
/// Computes how many blocks are needed to store that many bits
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
/// let mut bv = BitVec::new();
/// ```
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b10100000, 0b00010010]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_fn(5, |i| { i % 2 == 0 });
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01100000]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(5, false);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let before = 0b01100000;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let before = 0b01100000;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let a = 0b01100100;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let a = 0b01100100;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let a = 0b01100100;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(5, true);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(3, true);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b10100000]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_bytes(&[0b01001011]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(3, false);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(3, false);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_bytes(&[0b01001011]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_bytes(&[0b01001001]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::new();
/// # Examples
///
/// ```
+/// # #![feature(collections)]
/// use std::collections::{BitSet, BitVec};
///
/// // It's a regular set
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitSet;
///
/// let mut s = BitSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitSet;
///
/// let mut s = BitSet::with_capacity(100);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitVec, BitSet};
///
/// let bv = BitVec::from_bytes(&[0b01100000]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitSet;
///
/// let mut s = BitSet::with_capacity(100);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitSet;
///
/// let mut s = BitSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitSet;
///
/// let mut s = BitSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitSet;
///
/// let mut s = BitSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitSet;
///
/// let mut s = BitSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BitSet;
///
/// let mut s = BitSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitVec, BitSet};
///
/// let s = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01001010]));
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitVec, BitSet};
///
/// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitVec, BitSet};
///
/// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitSet, BitVec};
///
/// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitSet, BitVec};
///
/// let a = BitSet::from_bit_vec(BitVec::from_bytes(&[0b01101000]));
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitSet, BitVec};
///
/// let a = 0b01101000;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitSet, BitVec};
///
/// let a = 0b01101000;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitSet, BitVec};
///
/// let a = 0b01101000;
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::{BitSet, BitVec};
///
/// let a = 0b01101000;
next_idx: usize
}
+#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Union<'a>(TwoBitPositions<'a>);
+#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Intersection<'a>(Take<TwoBitPositions<'a>>);
+#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Difference<'a>(TwoBitPositions<'a>);
+#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SymmetricDifference<'a>(TwoBitPositions<'a>);
use core::clone::Clone;
use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
+use core::convert::AsRef;
use core::hash::{Hash, Hasher};
use core::marker::Sized;
use core::ops::Deref;
}
/// Trait for moving into a `Cow`
-#[stable(feature = "rust1", since = "1.0.0")]
+#[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
pub trait IntoCow<'a, B: ?Sized> where B: ToOwned {
/// Moves `self` into `Cow`
- #[stable(feature = "rust1", since = "1.0.0")]
fn into_cow(self) -> Cow<'a, B>;
}
self
}
}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, T: Clone> AsRef<T> for Cow<'a, T> {
+ fn as_ref(&self) -> &T {
+ self
+ }
+}
}
/// An abstract base over-which all other BTree iterators are built.
+#[derive(Clone)]
struct AbsIter<T> {
traversals: VecDeque<T>,
size: usize,
}
/// A view into a single entry in a map, which may either be vacant or occupied.
-#[unstable(feature = "collections",
- reason = "precise API still under development")]
+#[stable(feature = "rust1", since = "1.0.0")]
pub enum Entry<'a, K:'a, V:'a> {
/// A vacant Entry
+ #[stable(feature = "rust1", since = "1.0.0")]
Vacant(VacantEntry<'a, K, V>),
+
/// An occupied Entry
+ #[stable(feature = "rust1", since = "1.0.0")]
Occupied(OccupiedEntry<'a, K, V>),
}
/// A vacant Entry.
-#[unstable(feature = "collections",
- reason = "precise API still under development")]
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct VacantEntry<'a, K:'a, V:'a> {
key: K,
stack: stack::SearchStack<'a, K, V, node::handle::Edge, node::handle::Leaf>,
}
/// An occupied Entry.
-#[unstable(feature = "collections",
- reason = "precise API still under development")]
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct OccupiedEntry<'a, K:'a, V:'a> {
stack: stack::SearchStack<'a, K, V, node::handle::KV, node::handle::LeafOrInternal>,
}
/// Some(x) => *x = "b",
/// None => (),
/// }
- /// assert_eq!(map[1], "b");
+ /// assert_eq!(map[&1], "b");
/// ```
// See `get` for implementation notes, this is basically a copy-paste with mut's added
#[stable(feature = "rust1", since = "1.0.0")]
///
/// map.insert(37, "b");
/// assert_eq!(map.insert(37, "c"), Some("b"));
- /// assert_eq!(map[37], "c");
+ /// assert_eq!(map[&37], "c");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn insert(&mut self, mut key: K, mut value: V) -> Option<V> {
}
}
+#[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Ord, Q: ?Sized, V> Index<Q> for BTreeMap<K, V>
where K: Borrow<Q>, Q: Ord
{
type Output = V;
+ #[inline]
+ fn index(&self, key: &Q) -> &V {
+ self.get(key).expect("no entry found for key")
+ }
+}
+
+#[cfg(not(stage0))]
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
+ where K: Borrow<Q>, Q: Ord
+{
+ type Output = V;
+
+ #[inline]
fn index(&self, key: &Q) -> &V {
self.get(key).expect("no entry found for key")
}
}
}
+impl<'a, K, V> Clone for Iter<'a, K, V> {
+ fn clone(&self) -> Iter<'a, K, V> { Iter { inner: self.inner.clone() } }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> ExactSizeIterator for IntoIter<K, V> {}
+impl<'a, K, V> Clone for Keys<'a, K, V> {
+ fn clone(&self) -> Keys<'a, K, V> { Keys { inner: self.inner.clone() } }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K, V> Iterator for Keys<'a, K, V> {
type Item = &'a K;
impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {}
+impl<'a, K, V> Clone for Values<'a, K, V> {
+ fn clone(&self) -> Values<'a, K, V> { Values { inner: self.inner.clone() } }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K, V> Iterator for Values<'a, K, V> {
type Item = &'a V;
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {}
+impl<'a, K, V> Clone for Range<'a, K, V> {
+ fn clone(&self) -> Range<'a, K, V> { Range { inner: self.inner.clone() } }
+}
impl<'a, K, V> Iterator for Range<'a, K, V> {
type Item = (&'a K, &'a V);
}
impl<'a, K: Ord, V> Entry<'a, K, V> {
- #[unstable(feature = "collections",
- reason = "matches collection reform v2 specification, waiting for dust to settle")]
/// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant
+ #[unstable(feature = "std_misc",
+ reason = "will soon be replaced by or_insert")]
pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
match self {
Occupied(entry) => Ok(entry.into_mut()),
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeMap;
///
/// let mut a = BTreeMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BTreeMap;
/// use std::collections::Bound::{Included, Unbounded};
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BTreeMap;
/// use std::collections::Bound::{Included, Excluded};
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BTreeMap;
/// use std::collections::btree_map::Entry;
///
/// A `TraversalImpl` that actually is backed by two iterators. This works in the non-moving case,
/// as no deallocation needs to be done.
+#[derive(Clone)]
struct ElemsAndEdges<Elems, Edges>(Elems, Edges);
impl<K, V, E, Elems: DoubleEndedIterator, Edges: DoubleEndedIterator>
}
/// An abstraction over all the different kinds of traversals a node supports
+#[derive(Clone)]
struct AbsTraversal<Impl> {
inner: Impl,
head_is_edge: bool,
}
/// Returns a sub-slice with elements starting with `min_key`.
+ #[cfg(stage0)]
pub fn slice_from(self, min_key: &K) -> $NodeSlice<'a, K, V> {
// _______________
// |_1_|_3_|_5_|_7_|
}
}
+ /// Returns a sub-slice with elements starting with `min_key`.
+ #[cfg(not(stage0))]
+ pub fn slice_from(self, min_key: &K) -> $NodeSlice<'a, K, V> {
+ // _______________
+ // |_1_|_3_|_5_|_7_|
+ // | | | | |
+ // 0 0 1 1 2 2 3 3 4 index
+ // | | | | |
+ // \___|___|___|___/ slice_from(&0); pos = 0
+ // \___|___|___/ slice_from(&2); pos = 1
+ // |___|___|___/ slice_from(&3); pos = 1; result.head_is_edge = false
+ // \___|___/ slice_from(&4); pos = 2
+ // \___/ slice_from(&6); pos = 3
+ // \|/ slice_from(&999); pos = 4
+ let (pos, pos_is_kv) = self.search_linear(min_key);
+ $NodeSlice {
+ has_edges: self.has_edges,
+ edges: if !self.has_edges {
+ self.edges
+ } else {
+ self.edges.$index(pos ..)
+ },
+ keys: &self.keys[pos ..],
+ vals: self.vals.$index(pos ..),
+ head_is_edge: !pos_is_kv,
+ tail_is_edge: self.tail_is_edge,
+ }
+ }
+
/// Returns a sub-slice with elements up to and including `max_key`.
+ #[cfg(stage0)]
pub fn slice_to(self, max_key: &K) -> $NodeSlice<'a, K, V> {
// _______________
// |_1_|_3_|_5_|_7_|
tail_is_edge: !pos_is_kv,
}
}
+
+ /// Returns a sub-slice with elements up to and including `max_key`.
+ #[cfg(not(stage0))]
+ pub fn slice_to(self, max_key: &K) -> $NodeSlice<'a, K, V> {
+ // _______________
+ // |_1_|_3_|_5_|_7_|
+ // | | | | |
+ // 0 0 1 1 2 2 3 3 4 index
+ // | | | | |
+ //\|/ | | | | slice_to(&0); pos = 0
+ // \___/ | | | slice_to(&2); pos = 1
+ // \___|___| | | slice_to(&3); pos = 1; result.tail_is_edge = false
+ // \___|___/ | | slice_to(&4); pos = 2
+ // \___|___|___/ | slice_to(&6); pos = 3
+ // \___|___|___|___/ slice_to(&999); pos = 4
+ let (pos, pos_is_kv) = self.search_linear(max_key);
+ let pos = pos + if pos_is_kv { 1 } else { 0 };
+ $NodeSlice {
+ has_edges: self.has_edges,
+ edges: if !self.has_edges {
+ self.edges
+ } else {
+ self.edges.$index(.. (pos + 1))
+ },
+ keys: &self.keys[..pos],
+ vals: self.vals.$index(.. pos),
+ head_is_edge: self.head_is_edge,
+ tail_is_edge: !pos_is_kv,
+ }
+ }
}
impl<'a, K: 'a, V: 'a> $NodeSlice<'a, K, V> {
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::BTreeSet;
/// use std::collections::Bound::{Included, Unbounded};
///
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let mut a = BTreeSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let mut a = BTreeSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let mut a = BTreeSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let mut a = BTreeSet::new();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let set: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let a: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let sup: BTreeSet<_> = [1, 2, 3].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::BTreeSet;
///
/// let sub: BTreeSet<_> = [1, 2].iter().cloned().collect();
}
}
+impl<'a, T> Clone for Iter<'a, T> {
+ fn clone(&self) -> Iter<'a, T> { Iter { iter: self.iter.clone() } }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
impl<T> ExactSizeIterator for IntoIter<T> {}
+impl<'a, T> Clone for Range<'a, T> {
+ fn clone(&self) -> Range<'a, T> { Range { iter: self.iter.clone() } }
+}
impl<'a, T> Iterator for Range<'a, T> {
type Item = &'a T;
}
}
+impl<'a, T> Clone for Difference<'a, T> {
+ fn clone(&self) -> Difference<'a, T> {
+ Difference { a: self.a.clone(), b: self.b.clone() }
+ }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: Ord> Iterator for Difference<'a, T> {
type Item = &'a T;
}
}
+impl<'a, T> Clone for SymmetricDifference<'a, T> {
+ fn clone(&self) -> SymmetricDifference<'a, T> {
+ SymmetricDifference { a: self.a.clone(), b: self.b.clone() }
+ }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> {
type Item = &'a T;
}
}
+impl<'a, T> Clone for Intersection<'a, T> {
+ fn clone(&self) -> Intersection<'a, T> {
+ Intersection { a: self.a.clone(), b: self.b.clone() }
+ }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: Ord> Iterator for Intersection<'a, T> {
type Item = &'a T;
}
}
+impl<'a, T> Clone for Union<'a, T> {
+ fn clone(&self) -> Union<'a, T> {
+ Union { a: self.a.clone(), b: self.b.clone() }
+ }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: Ord> Iterator for Union<'a, T> {
type Item = &'a T;
//! like:
//!
//! ```
+//! # #![feature(core, std_misc)]
//! use std::fmt;
//! use std::f64;
//! use std::num::Float;
//! Example usage is:
//!
//! ```
+//! # #![feature(old_io)]
//! # #![allow(unused_must_use)]
//! use std::io::Write;
//! let mut w = Vec::new();
//! off, some example usage is:
//!
//! ```
+//! # #![feature(old_io)]
//! use std::fmt;
//! use std::io::{self, Write};
//!
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/")]
+#![doc(test(no_crate_inject))]
+#![allow(trivial_casts)]
+#![allow(trivial_numeric_casts)]
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(box_patterns)]
#![feature(unsafe_no_drop_flag)]
#![feature(step_by)]
#![feature(str_char)]
-#![cfg_attr(test, feature(rand, rustc_private, test))]
+#![feature(convert)]
+#![cfg_attr(test, feature(rand, rustc_private, test, hash, collections))]
#![cfg_attr(test, allow(deprecated))] // rand
#![feature(no_std)]
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::LinkedList;
///
/// let mut a = LinkedList::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::LinkedList;
///
/// let mut dl = LinkedList::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::LinkedList;
///
/// let mut d = LinkedList::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::LinkedList;
///
/// let mut d = LinkedList::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::LinkedList;
///
/// let mut d = LinkedList::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::LinkedList;
///
/// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::LinkedList;
///
/// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
}
+impl<A> ExactSizeIterator for IntoIter<A> {}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> FromIterator<A> for LinkedList<A> {
fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> LinkedList<A> {
//! Slices are a view into a block of memory represented as a pointer and a length.
//!
//! ```rust
+//! # #![feature(core)]
//! // slicing a Vec
//! let vec = vec!(1, 2, 3);
//! let int_slice = vec.as_slice();
#![stable(feature = "rust1", since = "1.0.0")]
use alloc::boxed::Box;
+use core::convert::AsRef;
use core::clone::Clone;
use core::cmp::Ordering::{self, Greater, Less};
use core::cmp::{self, Ord, PartialEq};
/// # Examples
///
/// ```rust
+ /// # #![feature(collections)]
/// let mut a = [1, 2, 3, 4, 5];
/// let b = vec![6, 7, 8];
/// let num_moved = a.move_from(b, 0, 3);
/// found; the fourth could match any position in `[1,4]`.
///
/// ```rust
+ /// # #![feature(core)]
/// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
/// let s = s.as_slice();
///
/// # Examples
///
/// ```rust
+ /// # #![feature(collections)]
/// let v = [1, 2, 3];
/// let mut perms = v.permutations();
///
/// Iterating through permutations one by one.
///
/// ```rust
+ /// # #![feature(collections)]
/// let v = [1, 2, 3];
/// let mut perms = v.permutations();
///
/// # Example
///
/// ```rust
+ /// # #![feature(collections)]
/// let mut dst = [0, 0, 0];
/// let src = [1, 2];
///
/// found; the fourth could match any position in `[1,4]`.
///
/// ```rust
+ /// # #![feature(core)]
/// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
/// let s = s.as_slice();
///
/// # Example
///
/// ```rust
+ /// # #![feature(collections)]
/// let v: &mut [_] = &mut [0, 1, 2];
/// v.next_permutation();
/// let b: &mut [_] = &mut [0, 2, 1];
/// # Example
///
/// ```rust
+ /// # #![feature(collections)]
/// let v: &mut [_] = &mut [1, 0, 2];
/// v.prev_permutation();
/// let b: &mut [_] = &mut [0, 2, 1];
fn connect(&self, sep: &T) -> U;
}
-impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] {
+impl<T: Clone, V: AsRef<[T]>> SliceConcatExt<T, Vec<T>> for [V] {
fn concat(&self) -> Vec<T> {
- let size = self.iter().fold(0, |acc, v| acc + v.as_slice().len());
+ let size = self.iter().fold(0, |acc, v| acc + v.as_ref().len());
let mut result = Vec::with_capacity(size);
for v in self {
- result.push_all(v.as_slice())
+ result.push_all(v.as_ref())
}
result
}
fn connect(&self, sep: &T) -> Vec<T> {
- let size = self.iter().fold(0, |acc, v| acc + v.as_slice().len());
+ let size = self.iter().fold(0, |acc, v| acc + v.as_ref().len());
let mut result = Vec::with_capacity(size + self.len());
let mut first = true;
for v in self {
if first { first = false } else { result.push(sep.clone()) }
- result.push_all(v.as_slice())
+ result.push_all(v.as_ref())
}
result
}
use core::iter::{Iterator, IteratorExt, Extend};
use core::option::Option::{self, Some, None};
use core::result::Result;
-use core::slice::AsSlice;
use core::str as core_str;
use unicode::str::{UnicodeStr, Utf16Encoder};
+use core::convert::AsRef;
use vec_deque::VecDeque;
use borrow::{Borrow, ToOwned};
use string::String;
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::{Split, SplitTerminator, SplitN};
+pub use core::str::{RSplit, RSplitN};
pub use core::str::{from_utf8, CharEq, Chars, CharIndices, Bytes};
pub use core::str::{from_utf8_unchecked, from_c_str, ParseBoolError};
pub use unicode::str::{Words, Graphemes, GraphemeIndices};
Section: Creating a string
*/
-impl<S: Str> SliceConcatExt<str, String> for [S] {
+impl<S: AsRef<str>> SliceConcatExt<str, String> for [S] {
fn concat(&self) -> String {
- let s = self.as_slice();
-
- if s.is_empty() {
+ if self.is_empty() {
return String::new();
}
// `len` calculation may overflow but push_str will check boundaries
- let len = s.iter().map(|s| s.as_slice().len()).sum();
+ let len = self.iter().map(|s| s.as_ref().len()).sum();
let mut result = String::with_capacity(len);
- for s in s {
- result.push_str(s.as_slice())
+ for s in self {
+ result.push_str(s.as_ref())
}
result
}
fn connect(&self, sep: &str) -> String {
- let s = self.as_slice();
-
- if s.is_empty() {
+ if self.is_empty() {
return String::new();
}
// concat is faster
if sep.is_empty() {
- return s.concat();
+ return self.concat();
}
// this is wrong without the guarantee that `self` is non-empty
// `len` calculation may overflow but push_str but will check boundaries
- let len = sep.len() * (s.len() - 1)
- + s.iter().map(|s| s.as_slice().len()).sum();
+ let len = sep.len() * (self.len() - 1)
+ + self.iter().map(|s| s.as_ref().len()).sum();
let mut result = String::with_capacity(len);
let mut first = true;
- for s in s {
+ for s in self {
if first {
first = false;
} else {
result.push_str(sep);
}
- result.push_str(s.as_slice());
+ result.push_str(s.as_ref());
}
result
}
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// assert!("hello".contains_char('e'));
///
/// assert!(!"hello".contains_char('z'));
core_str::StrExt::split_terminator(&self[..], pat)
}
- /// An iterator over substrings of `self`, separated by characters matched by a pattern,
+ /// An iterator over substrings of `self`, separated by a pattern,
/// starting from the end of the string.
///
- /// Restricted to splitting at most `count` times.
+ /// # Examples
///
- /// The pattern can be a simple `&str`, or a closure that determines the split.
+ /// Simple patterns:
+ ///
+ /// ```
+ /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
+ /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
+ ///
+ /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
+ /// assert_eq!(v, ["leopard", "tiger", "lion"]);
+ /// ```
+ ///
+ /// More complex patterns with a lambda:
+ ///
+ /// ```
+ /// let v: Vec<&str> = "abc1def2ghi".rsplit(|c: char| c.is_numeric()).collect();
+ /// assert_eq!(v, ["ghi", "def", "abc"]);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
+ where P::Searcher: ReverseSearcher<'a>
+ {
+ core_str::StrExt::rsplit(&self[..], pat)
+ }
+
+ /// An iterator over substrings of `self`, separated by a pattern,
+ /// starting from the end of the string, restricted to splitting
+ /// at most `count` times.
///
/// # Examples
///
- /// Simple `&str` patterns:
+ /// Simple patterns:
///
/// ```
/// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
/// assert_eq!(v, ["lamb", "little", "Mary had a"]);
///
- /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
- /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
+ /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(1, "::").collect();
+ /// assert_eq!(v, ["leopard", "lion::tiger"]);
/// ```
///
/// More complex patterns with a lambda:
/// assert_eq!(v, ["ghi", "abc1def"]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P> {
+ pub fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
+ where P::Searcher: ReverseSearcher<'a>
+ {
core_str::StrExt::rsplitn(&self[..], count, pat)
}
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
/// assert_eq!(v, [(0,3), (6,9), (12,15)]);
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let v: Vec<&str> = "abcXXXabcYYYabc".split_str("abc").collect();
/// assert_eq!(v, ["", "XXX", "YYY", ""]);
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let s = "Löwe 老虎 Léopard";
///
/// assert_eq!(s.slice_chars(0, 4), "Löwe");
/// # Examples
///
/// ```
+ /// # #![feature(str_char)]
/// let s = "Löwe 老虎 Léopard";
/// assert!(s.is_char_boundary(0));
/// // start of `老`
/// done by `.chars()` or `.char_indices()`.
///
/// ```
+ /// # #![feature(str_char, core)]
/// use std::str::CharRange;
///
/// let s = "中华Việt Nam";
/// done by `.chars().rev()` or `.char_indices()`.
///
/// ```
+ /// # #![feature(str_char, core)]
/// use std::str::CharRange;
///
/// let s = "中华Việt Nam";
/// # Examples
///
/// ```
+ /// # #![feature(str_char)]
/// let s = "abπc";
/// assert_eq!(s.char_at(1), 'b');
/// assert_eq!(s.char_at(2), 'π');
/// # Examples
///
/// ```
+ /// # #![feature(str_char)]
/// let s = "abπc";
/// assert_eq!(s.char_at_reverse(1), 'a');
/// assert_eq!(s.char_at_reverse(2), 'b');
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let s = "Löwe 老虎 Léopard";
///
/// assert_eq!(s.find_str("老虎 L"), Some(6));
/// # Examples
///
/// ```
+ /// # #![feature(str_char)]
/// let s = "Löwe 老虎 Léopard";
/// let (c, s1) = s.slice_shift_char().unwrap();
///
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let string = "a\nb\nc";
/// let lines: Vec<&str> = string.lines().collect();
///
/// # Examples
///
/// ```
+ /// # #![feature(unicode, core)]
/// let gr1 = "a\u{310}e\u{301}o\u{308}\u{332}".graphemes(true).collect::<Vec<&str>>();
/// let b: &[_] = &["a\u{310}", "e\u{301}", "o\u{308}\u{332}"];
///
/// # Examples
///
/// ```
+ /// # #![feature(unicode, core)]
/// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
/// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
///
/// # Examples
///
/// ```
+ /// # #![feature(str_words)]
/// let some_words = " Mary had\ta little \n\t lamb";
/// let v: Vec<&str> = some_words.words().collect();
///
use core::ops::{self, Deref, Add, Index};
use core::ptr;
use core::slice;
+use core::str::Pattern;
use unicode::str as unicode_str;
use unicode::str::Utf16Item;
/// # Examples
///
/// ```
+ /// # #![feature(collections, core)]
/// let s = String::from_str("hello");
/// assert_eq!(s.as_slice(), "hello");
/// ```
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::str::Utf8Error;
///
/// let hello_vec = vec![104, 101, 108, 108, 111];
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let s = String::from_str("hello");
/// let bytes = s.into_bytes();
/// assert_eq!(bytes, [104, 101, 108, 108, 111]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut s = String::from_str("foo");
/// s.push_str("bar");
/// assert_eq!(s, "foobar");
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut s = String::from_str("foo");
/// s.reserve(100);
/// assert!(s.capacity() >= 100);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut s = String::from_str("abc");
/// s.push('1');
/// s.push('2');
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let s = String::from_str("hello");
/// let b: &[_] = &[104, 101, 108, 108, 111];
/// assert_eq!(s.as_bytes(), b);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut s = String::from_str("hello");
/// s.truncate(2);
/// assert_eq!(s, "he");
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut s = String::from_str("foo");
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.pop(), Some('o'));
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut s = String::from_str("foo");
/// assert_eq!(s.remove(0), 'f');
/// assert_eq!(s.remove(1), 'o');
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut s = String::from_str("hello");
/// unsafe {
/// let vec = s.as_mut_vec();
}
}
+/// A convenience impl that delegates to the impl for `&str`
+impl<'a, 'b> Pattern<'a> for &'b String {
+ type Searcher = <&'b str as Pattern<'a>>::Searcher;
+
+ fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher {
+ self[..].into_searcher(haystack)
+ }
+
+ #[inline]
+ fn is_contained_in(self, haystack: &'a str) -> bool {
+ self[..].is_contained_in(haystack)
+ }
+
+ #[inline]
+ fn is_prefix_of(self, haystack: &'a str) -> bool {
+ self[..].is_prefix_of(haystack)
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for String {
#[inline]
}
#[unstable(feature = "collections", reason = "waiting on Str stabilization")]
+#[allow(deprecated)]
impl Str for String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::Range<usize>> for String {
type Output = str;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::Range<usize>) -> &str {
&self[..][*index]
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::Range<usize>) -> &str {
+ &self[..][index]
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeTo<usize>> for String {
type Output = str;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeTo<usize>) -> &str {
&self[..][*index]
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeTo<usize>) -> &str {
+ &self[..][index]
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFrom<usize>> for String {
type Output = str;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeFrom<usize>) -> &str {
&self[..][*index]
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeFrom<usize>) -> &str {
+ &self[..][index]
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for String {
type Output = str;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, _index: &ops::RangeFull) -> &str {
unsafe { mem::transmute(&*self.vec) }
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, _index: ops::RangeFull) -> &str {
+ unsafe { mem::transmute(&*self.vec) }
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
/// # Examples
///
/// ```
+/// # #![feature(collections)]
/// use std::string::as_string;
///
/// fn string_consumer(s: String) {
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<str> for String {
+ fn as_ref(&self) -> &str {
+ self
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a str> for String {
+ fn from(s: &'a str) -> String {
+ s.to_string()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl Into<Vec<u8>> for String {
+ fn into(self) -> Vec<u8> {
+ self.into_bytes()
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl IntoCow<'static, str> for String {
#[inline]
}
}
+#[allow(deprecated)]
impl<'a> Str for Cow<'a, str> {
#[inline]
fn as_slice<'b>(&'b self) -> &'b str {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! A growable list type with heap-allocated contents, written `Vec<T>` but pronounced 'vector.'
+//! A growable list type with heap-allocated contents, written `Vec<T>` but
+//! pronounced 'vector.'
//!
//! Vectors have `O(1)` indexing, push (to the end) and pop (from the end).
//!
/// # Examples
///
/// ```
+/// # #![feature(collections)]
/// let mut vec = Vec::new();
/// vec.push(1);
/// vec.push(2);
///
/// # Capacity and reallocation
///
-/// The capacity of a vector is the amount of space allocated for any future elements that will be
-/// added onto the vector. This is not to be confused with the *length* of a vector, which
-/// specifies the number of actual elements within the vector. If a vector's length exceeds its
-/// capacity, its capacity will automatically be increased, but its elements will have to be
+/// The capacity of a vector is the amount of space allocated for any future
+/// elements that will be added onto the vector. This is not to be confused with
+/// the *length* of a vector, which specifies the number of actual elements
+/// within the vector. If a vector's length exceeds its capacity, its capacity
+/// will automatically be increased, but its elements will have to be
/// reallocated.
///
-/// For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10
-/// more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or
-/// cause reallocation to occur. However, if the vector's length is increased to 11, it will have
-/// to reallocate, which can be slow. For this reason, it is recommended to use
-/// `Vec::with_capacity` whenever possible to specify how big the vector is expected to get.
+/// For example, a vector with capacity 10 and length 0 would be an empty vector
+/// with space for 10 more elements. Pushing 10 or fewer elements onto the
+/// vector will not change its capacity or cause reallocation to occur. However,
+/// if the vector's length is increased to 11, it will have to reallocate, which
+/// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
+/// whenever possible to specify how big the vector is expected to get.
#[unsafe_no_drop_flag]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Vec<T> {
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut vec = Vec::with_capacity(10);
/// vec.push_all(&[1, 2, 3]);
/// assert_eq!(vec.capacity(), 10);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut vec = vec![1, 2, 3, 4];
/// vec.truncate(2);
/// assert_eq!(vec, [1, 2]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut v = vec![1, 2, 3];
/// assert_eq!(v.remove(1), 2);
/// assert_eq!(v, [1, 3]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut vec = vec![1, 2, 3];
/// let mut vec2 = vec![4, 5, 6];
/// vec.append(&mut vec2);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut v = vec!["a".to_string(), "b".to_string()];
/// for s in v.drain() {
/// // s has type String, not &String
/// # Examples
///
/// ```
+ /// # #![feature(collections, core)]
/// let v = vec![0, 1, 2];
/// let w = v.map_in_place(|i| i + 3);
/// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut vec = vec![1,2,3];
/// let vec2 = vec.split_off(1);
/// assert_eq!(vec, [1]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut vec = vec!["hello"];
/// vec.resize(3, "world");
/// assert_eq!(vec, ["hello", "world", "world"]);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// let mut vec = vec![1];
/// vec.push_all(&[2, 3, 4]);
/// assert_eq!(vec, [1, 2, 3, 4]);
// Avoid bounds checks by using unsafe pointers.
let p = self.as_mut_ptr();
- let mut r = 1;
- let mut w = 1;
+ let mut r: usize = 1;
+ let mut w: usize = 1;
while r < ln {
let p_r = p.offset(r as isize);
impl<T> Index<usize> for Vec<T> {
type Output = T;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &usize) -> &T {
// NB built-in indexing via `&[T]`
&(**self)[*index]
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: usize) -> &T {
+ // NB built-in indexing via `&[T]`
+ &(**self)[index]
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> IndexMut<usize> for Vec<T> {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &usize) -> &mut T {
// NB built-in indexing via `&mut [T]`
&mut (**self)[*index]
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: usize) -> &mut T {
+ // NB built-in indexing via `&mut [T]`
+ &mut (**self)[index]
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::Range<usize>) -> &[T] {
Index::index(&**self, index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::Range<usize>) -> &[T] {
+ Index::index(&**self, index)
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
Index::index(&**self, index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
+ Index::index(&**self, index)
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
Index::index(&**self, index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
+ Index::index(&**self, index)
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Index<ops::RangeFull> for Vec<T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, _index: &ops::RangeFull) -> &[T] {
- self.as_slice()
+ self
+ }
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, _index: ops::RangeFull) -> &[T] {
+ self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
IndexMut::index_mut(&mut **self, index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
+ IndexMut::index_mut(&mut **self, index)
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
IndexMut::index_mut(&mut **self, index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
+ IndexMut::index_mut(&mut **self, index)
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
IndexMut::index_mut(&mut **self, index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
+ IndexMut::index_mut(&mut **self, index)
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, _index: &ops::RangeFull) -> &mut [T] {
self.as_mut_slice()
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
+ self.as_mut_slice()
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Deref for Vec<T> {
type Target = [T];
- fn deref(&self) -> &[T] { self.as_slice() }
+ fn deref(&self) -> &[T] {
+ unsafe {
+ let p = *self.ptr;
+ assume(p != 0 as *mut T);
+ slice::from_raw_parts(p, self.len)
+ }
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
}
}
+#[allow(deprecated)]
impl<T> AsSlice<T> for Vec<T> {
/// Returns a slice into `self`.
///
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// fn foo(slice: &[i32]) {}
///
/// let vec = vec![1, 2];
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn as_slice(&self) -> &[T] {
- unsafe {
- let p = *self.ptr;
- assume(p != 0 as *mut T);
- slice::from_raw_parts(p, self.len)
- }
+ self
}
}
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<T> AsRef<Vec<T>> for Vec<T> {
+ fn as_ref(&self) -> &Vec<T> {
+ self
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<T> Into<Vec<T>> for Vec<T> {
+ fn into(self) -> Vec<T> {
+ self
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<T> AsRef<[T]> for Vec<T> {
+ fn as_ref(&self) -> &[T] {
+ self
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
+ #[cfg(not(test))]
+ fn from(s: &'a [T]) -> Vec<T> {
+ s.to_vec()
+ }
+ #[cfg(test)]
+ fn from(s: &'a [T]) -> Vec<T> {
+ ::slice::to_vec(s)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a str> for Vec<u8> {
+ fn from(s: &'a str) -> Vec<u8> {
+ From::from(s.as_bytes())
+ }
+}
+
////////////////////////////////////////////////////////////////////////////////
// Clone-on-write
////////////////////////////////////////////////////////////////////////////////
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let buf: VecDeque<i32> = VecDeque::with_capacity(10);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<i32> = vec![1].into_iter().collect();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::with_capacity(15);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
}
}
- /// Consumes the list into an iterator yielding elements by value.
+ /// Consumes the list into a front-to-back iterator yielding elements by value.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_iter(self) -> IntoIter<T> {
IntoIter {
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut v = VecDeque::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
///
/// # Examples
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<_> = vec![1,2,3].into_iter().collect();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
/// A by-value VecDeque iterator
+#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct IntoIter<T> {
inner: VecDeque<T>,
impl<A> Index<usize> for VecDeque<A> {
type Output = A;
+ #[cfg(stage0)]
#[inline]
fn index(&self, i: &usize) -> &A {
self.get(*i).expect("Out of bounds access")
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, i: usize) -> &A {
+ self.get(i).expect("Out of bounds access")
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> IndexMut<usize> for VecDeque<A> {
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, i: &usize) -> &mut A {
self.get_mut(*i).expect("Out of bounds access")
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, i: usize) -> &mut A {
+ self.get_mut(i).expect("Out of bounds access")
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
/// # Examples
///
/// ```
+/// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut months = VecMap::new();
}
/// A view into a single entry in a map, which may either be vacant or occupied.
-#[unstable(feature = "collections",
- reason = "precise API still under development")]
+
+#[stable(feature = "rust1", since = "1.0.0")]
pub enum Entry<'a, V:'a> {
/// A vacant Entry
+ #[stable(feature = "rust1", since = "1.0.0")]
Vacant(VacantEntry<'a, V>),
+
/// An occupied Entry
+ #[stable(feature = "rust1", since = "1.0.0")]
Occupied(OccupiedEntry<'a, V>),
}
/// A vacant Entry.
-#[unstable(feature = "collections",
- reason = "precise API still under development")]
+
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct VacantEntry<'a, V:'a> {
map: &'a mut VecMap<V>,
index: usize,
}
/// An occupied Entry.
-#[unstable(feature = "collections",
- reason = "precise API still under development")]
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct OccupiedEntry<'a, V:'a> {
map: &'a mut VecMap<V>,
index: usize,
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
/// let mut map: VecMap<&str> = VecMap::new();
/// ```
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
/// let mut map: VecMap<&str> = VecMap::with_capacity(10);
/// ```
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
/// let map: VecMap<String> = VecMap::with_capacity(10);
/// assert!(map.capacity() >= 10);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
/// let mut map: VecMap<&str> = VecMap::new();
/// map.reserve_len(10);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
/// let mut map: VecMap<&str> = VecMap::new();
/// map.reserve_len_exact(10);
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut a = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut a = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut a = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut a = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut a = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
///
/// let mut map = VecMap::new();
/// # Examples
///
/// ```
+ /// # #![feature(collections)]
/// use std::collections::VecMap;
/// use std::collections::vec_map::Entry;
///
impl<'a, V> Entry<'a, V> {
#[unstable(feature = "collections",
- reason = "matches collection reform v2 specification, waiting for dust to settle")]
+ reason = "will soon be replaced by or_insert")]
/// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant
pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, V>> {
match self {
}
}
+#[cfg(stage0)]
impl<V> Index<usize> for VecMap<V> {
type Output = V;
}
}
+#[cfg(not(stage0))]
+impl<V> Index<usize> for VecMap<V> {
+ type Output = V;
+
+ #[inline]
+ fn index<'a>(&'a self, i: usize) -> &'a V {
+ self.get(&i).expect("key not present")
+ }
+}
+
+#[cfg(not(stage0))]
+impl<'a,V> Index<&'a usize> for VecMap<V> {
+ type Output = V;
+
+ #[inline]
+ fn index(&self, i: &usize) -> &V {
+ self.get(i).expect("key not present")
+ }
+}
+
+#[cfg(stage0)]
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<V> IndexMut<usize> for VecMap<V> {
+ #[inline]
+ fn index_mut(&mut self, i: &usize) -> &mut V {
+ self.get_mut(&i).expect("key not present")
+ }
+}
+
+#[cfg(not(stage0))]
#[stable(feature = "rust1", since = "1.0.0")]
impl<V> IndexMut<usize> for VecMap<V> {
#[inline]
- fn index_mut<'a>(&'a mut self, i: &usize) -> &'a mut V {
+ fn index_mut(&mut self, i: usize) -> &mut V {
+ self.get_mut(&i).expect("key not present")
+ }
+}
+
+#[cfg(not(stage0))]
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, V> IndexMut<&'a usize> for VecMap<V> {
+ #[inline]
+ fn index_mut(&mut self, i: &usize) -> &mut V {
self.get_mut(i).expect("key not present")
}
}
}
impl<'a, 'b, 'c> FnMut<(&'c i32,)> for Counter<'a, 'b> {
- type Output = bool;
-
extern "rust-call" fn call_mut(&mut self, (&x,): (&'c i32,)) -> bool {
assert_eq!(x, self.expected[*self.i]);
*self.i += 1;
}
}
+impl<'a, 'b, 'c> FnOnce<(&'c i32,)> for Counter<'a, 'b> {
+ type Output = bool;
+
+ extern "rust-call" fn call_once(mut self, args: (&'c i32,)) -> bool {
+ self.call_mut(args)
+ }
+}
+
fn check<F>(a: &[i32], b: &[i32], expected: &[i32], f: F) where
// FIXME Replace Counter with `Box<FnMut(_) -> _>`
F: FnOnce(&BTreeSet<i32>, &BTreeSet<i32>, Counter) -> bool,
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unsafe_destructor)]
+#![feature(into_cow)]
+#![cfg_attr(test, feature(str_char))]
#[macro_use] extern crate log;
let mut v = Vec::<u8>::with_capacity(1024);
unsafe {
let vp = v.as_mut_ptr();
- ptr::set_memory(vp, 0, 1024);
+ ptr::write_bytes(vp, 0, 1024);
v.set_len(1024);
}
v
assert_eq!(split, ["", "Märy häd ä little lämb", "Little lämb"]);
}
+#[test]
+fn test_rsplit() {
+ let data = "\nMäry häd ä little lämb\nLittle lämb\n";
+
+ let split: Vec<&str> = data.rsplit(' ').collect();
+ assert_eq!(split, ["lämb\n", "lämb\nLittle", "little", "ä", "häd", "\nMäry"]);
+
+ let split: Vec<&str> = data.rsplit("lämb").collect();
+ assert_eq!(split, ["\n", "\nLittle ", "\nMäry häd ä little "]);
+
+ let split: Vec<&str> = data.rsplit(|c: char| c == 'ä').collect();
+ assert_eq!(split, ["mb\n", "mb\nLittle l", " little l", "d ", "ry h", "\nM"]);
+}
+
+#[test]
+fn test_rsplitn() {
+ let data = "\nMäry häd ä little lämb\nLittle lämb\n";
+
+ let split: Vec<&str> = data.rsplitn(1, ' ').collect();
+ assert_eq!(split, ["lämb\n", "\nMäry häd ä little lämb\nLittle"]);
+
+ let split: Vec<&str> = data.rsplitn(1, "lämb").collect();
+ assert_eq!(split, ["\n", "\nMäry häd ä little lämb\nLittle "]);
+
+ let split: Vec<&str> = data.rsplitn(1, |c: char| c == 'ä').collect();
+ assert_eq!(split, ["mb\n", "\nMäry häd ä little lämb\nLittle l"]);
+}
+
#[test]
fn test_words() {
let data = "\n \tMäry häd\tä little lämb\nLittle lämb\n";
// Any trait
///////////////////////////////////////////////////////////////////////////////
-/// The `Any` trait is implemented by all `'static` types, and can be used for
-/// dynamic typing
+/// A type to emulate dynamic typing. See the [module-level documentation][mod] for more details.
///
-/// Every type with no non-`'static` references implements `Any`, so `Any` can
-/// be used as a trait object to emulate the effects dynamic typing.
+/// Every type with no non-`'static` references implements `Any`.
+///
+/// [mod]: ../index.html
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Any: 'static {
/// Get the `TypeId` of `self`
#![unstable(feature = "core")] // not yet reviewed
+#![doc(primitive = "array")]
+
use clone::Clone;
use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
use fmt;
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn get(&self) -> *mut T { &self.value as *const T as *mut T }
+ pub fn get(&self) -> *mut T {
+ // FIXME(#23542) Replace with type ascription.
+ #![allow(trivial_casts)]
+ &self.value as *const T as *mut T
+ }
/// Unwraps the value
///
//! could do the following:
//!
//! ```
-//! use core::num::SignedInt;
+//! # #![feature(core)]
+//! use std::num::SignedInt;
//!
//! struct FuzzyNum {
//! num: i32,
/// # Examples
///
/// ```
+/// # #![feature(core)]
/// use std::cmp;
///
/// assert_eq!(Some(1), cmp::partial_min(1, 2));
/// When comparison is impossible:
///
/// ```
+/// # #![feature(core)]
/// use std::cmp;
///
/// let result = cmp::partial_min(std::f64::NAN, 1.0);
/// # Examples
///
/// ```
+/// # #![feature(core)]
/// use std::cmp;
///
/// assert_eq!(Some(2), cmp::partial_max(1, 2));
/// When comparison is impossible:
///
/// ```
+/// # #![feature(core)]
/// use std::cmp;
///
/// let result = cmp::partial_max(std::f64::NAN, 1.0);
--- /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.
+
+//! Traits for conversions between types.
+//!
+//! The traits in this module provide a general way to talk about
+//! conversions from one type to another. They follow the standard
+//! Rust conventions of `as`/`to`/`into`/`from`.
+
+#![unstable(feature = "convert",
+ reason = "recently added, experimental traits")]
+
+use marker::Sized;
+
+/// A cheap, reference-to-reference conversion.
+pub trait AsRef<T: ?Sized> {
+ /// Perform the conversion.
+ fn as_ref(&self) -> &T;
+}
+
+/// A cheap, mutable reference-to-mutable reference conversion.
+pub trait AsMut<T: ?Sized> {
+ /// Perform the conversion.
+ fn as_mut(&mut self) -> &mut T;
+}
+
+/// A conversion that consumes `self`, which may or may not be
+/// expensive.
+pub trait Into<T>: Sized {
+ /// Perform the conversion.
+ fn into(self) -> T;
+}
+
+/// Construct `Self` via a conversion.
+pub trait From<T> {
+ /// Perform the conversion.
+ fn from(T) -> Self;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// GENERIC IMPLS
+////////////////////////////////////////////////////////////////////////////////
+
+// As implies Into
+impl<'a, T: ?Sized, U: ?Sized> Into<&'a U> for &'a T where T: AsRef<U> {
+ fn into(self) -> &'a U {
+ self.as_ref()
+ }
+}
+
+// As lifts over &
+impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
+ fn as_ref(&self) -> &U {
+ <T as AsRef<U>>::as_ref(*self)
+ }
+}
+
+// As lifts over &mut
+impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
+ fn as_ref(&self) -> &U {
+ <T as AsRef<U>>::as_ref(*self)
+ }
+}
+
+// AsMut implies Into
+impl<'a, T: ?Sized, U: ?Sized> Into<&'a mut U> for &'a mut T where T: AsMut<U> {
+ fn into(self) -> &'a mut U {
+ (*self).as_mut()
+ }
+}
+
+// AsMut lifts over &mut
+impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
+ fn as_mut(&mut self) -> &mut U {
+ (*self).as_mut()
+ }
+}
+
+// From implies Into
+impl<T, U> Into<U> for T where U: From<T> {
+ fn into(self) -> U {
+ U::from(self)
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// CONCRETE IMPLS
+////////////////////////////////////////////////////////////////////////////////
+
+impl<T> AsRef<[T]> for [T] {
+ fn as_ref(&self) -> &[T] {
+ self
+ }
+}
+
+impl<T> AsMut<[T]> for [T] {
+ fn as_mut(&mut self) -> &mut [T] {
+ self
+ }
+}
+
+impl AsRef<str> for str {
+ fn as_ref(&self) -> &str {
+ self
+ }
+}
//! For example,
//!
//! ```
+//! # #![feature(os, old_io, old_path)]
//! use std::error::FromError;
//! use std::old_io::{File, IoError};
//! use std::os::{MemoryMap, MapError};
#![stable(feature = "rust1", since = "1.0.0")]
use prelude::*;
-use fmt::Display;
+use fmt::{Debug, Display};
/// Base functionality for all errors in Rust.
-#[unstable(feature = "core",
- reason = "the exact API of this trait may change")]
-pub trait Error: Display {
- /// A short description of the error; usually a static string.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub trait Error: Debug + Display + Send {
+ /// A short description of the error.
+ ///
+ /// The description should not contain newlines or sentence-ending
+ /// punctuation, to facilitate embedding in larger user-facing
+ /// strings.
+ #[stable(feature = "rust1", since = "1.0.0")]
fn description(&self) -> &str;
/// The lower-level cause of this error, if any.
+ #[stable(feature = "rust1", since = "1.0.0")]
fn cause(&self) -> Option<&Error> { None }
}
//! # Examples
//!
//! ```
+//! # #![feature(core)]
//! # #![feature(unboxed_closures)]
//!
//! use std::finally::Finally;
/// # Examples
///
/// ```
+/// # #![feature(core)]
/// use std::finally::try_finally;
///
/// struct State<'a> { buffer: &'a mut [u8], len: usize }
/// # Examples
///
/// ```rust
+ /// # #![feature(debug_builders, core)]
/// use std::fmt;
///
/// struct Foo {
/// # Examples
///
/// ```rust
+ /// # #![feature(debug_builders, core)]
/// use std::fmt;
///
/// struct Foo(i32, String);
/// # Examples
///
/// ```rust
+ /// # #![feature(debug_builders, core)]
/// use std::fmt;
///
/// struct Foo(Vec<i32>);
/// # Examples
///
/// ```rust
+ /// # #![feature(debug_builders, core)]
/// use std::fmt;
///
/// struct Foo(Vec<(String, i32)>);
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Pointer for *mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
+ // FIXME(#23542) Replace with type ascription.
+ #![allow(trivial_casts)]
Pointer::fmt(&(*self as *const T), f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Pointer for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result {
+ // FIXME(#23542) Replace with type ascription.
+ #![allow(trivial_casts)]
Pointer::fmt(&(*self as *const T), f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Pointer for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
+ // FIXME(#23542) Replace with type ascription.
+ #![allow(trivial_casts)]
Pointer::fmt(&(&**self as *const T), f)
}
}
// FIXME: #6220 Implement floating point formatting
#![allow(unsigned_negation)]
+#![allow(trivial_numeric_casts)]
use fmt;
use iter::IteratorExt;
/// # Examples
///
/// ```
+/// # #![feature(core)]
/// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
/// ```
//! # Examples
//!
//! ```rust
+//! # #![feature(hash)]
//! use std::hash::{hash, Hash, SipHasher};
//!
//! #[derive(Hash)]
//! the trait `Hash`:
//!
//! ```rust
+//! # #![feature(hash)]
//! use std::hash::{hash, Hash, Hasher, SipHasher};
//!
//! struct Person {
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Hasher {
/// Completes a round of hashing, producing the output hash generated.
- #[unstable(feature = "hash", reason = "module was recently redesigned")]
+ #[stable(feature = "rust1", since = "1.0.0")]
fn finish(&self) -> u64;
/// Writes some data into this `Hasher`
}
fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
+ // FIXME(#23542) Replace with type ascription.
+ #![allow(trivial_casts)]
let newlen = data.len() * ::$ty::BYTES as usize;
let ptr = data.as_ptr() as *const u8;
state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
use marker::Sized;
+#[cfg(stage0)] pub use self::copy_memory as copy;
+#[cfg(stage0)] pub use self::set_memory as write_bytes;
+#[cfg(stage0)] pub use self::copy_nonoverlapping_memory as copy_nonoverlapping;
+
extern "rust-intrinsic" {
// NB: These intrinsics take unsafe pointers because they mutate aliased
/// Copies `count * size_of<T>` bytes from `src` to `dst`. The source
/// and destination may *not* overlap.
///
- /// `copy_nonoverlapping_memory` is semantically equivalent to C's `memcpy`.
+ /// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
///
/// # Safety
///
/// A safe swap function:
///
/// ```
+ /// # #![feature(core)]
/// use std::mem;
/// use std::ptr;
///
/// let mut t: T = mem::uninitialized();
///
/// // Perform the swap, `&mut` pointers never alias
- /// ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
- /// ptr::copy_nonoverlapping_memory(x, &*y, 1);
- /// ptr::copy_nonoverlapping_memory(y, &t, 1);
+ /// ptr::copy_nonoverlapping(&mut t, &*x, 1);
+ /// ptr::copy_nonoverlapping(x, &*y, 1);
+ /// ptr::copy_nonoverlapping(y, &t, 1);
///
/// // y and t now point to the same thing, but we need to completely forget `tmp`
/// // because it's no longer relevant.
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
+ #[cfg(not(stage0))]
+ pub fn copy_nonoverlapping<T>(dst: *mut T, src: *const T, count: usize);
+
+ /// dox
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[cfg(stage0)]
pub fn copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize);
/// Copies `count * size_of<T>` bytes from `src` to `dst`. The source
/// and destination may overlap.
///
- /// `copy_memory` is semantically equivalent to C's `memmove`.
+ /// `copy` is semantically equivalent to C's `memmove`.
///
/// # Safety
///
/// Efficiently create a Rust vector from an unsafe buffer:
///
/// ```
+ /// # #![feature(core)]
/// use std::ptr;
///
/// unsafe fn from_buf_raw<T>(ptr: *const T, elts: uint) -> Vec<T> {
/// let mut dst = Vec::with_capacity(elts);
/// dst.set_len(elts);
- /// ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
+ /// ptr::copy(dst.as_mut_ptr(), ptr, elts);
/// dst
/// }
/// ```
///
+ #[cfg(not(stage0))]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn copy<T>(dst: *mut T, src: *const T, count: usize);
+
+ /// dox
+ #[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn copy_memory<T>(dst: *mut T, src: *const T, count: usize);
/// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
/// bytes of memory starting at `dst` to `c`.
+ #[cfg(not(stage0))]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn write_bytes<T>(dst: *mut T, val: u8, count: usize);
+
+ /// dox
+ #[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn set_memory<T>(dst: *mut T, val: u8, count: usize);
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let xs = [100, 200, 300];
/// let mut it = xs.iter().cloned().peekable();
/// assert_eq!(*it.peek().unwrap(), 100);
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let xs = [2, 3];
/// let ys = [0, 1, 0, 1, 2];
/// let it = xs.iter().flat_map(|&x| std::iter::count(0, 1).take(x));
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::iter::AdditiveIterator;
///
/// let a = [1, 4, 2, 3, 8, 9, 6];
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let a = [1, 2, 3, 4, 5];
/// let b: Vec<_> = a.iter().cloned().collect();
/// assert_eq!(a, b);
/// do not.
///
/// ```
+ /// # #![feature(core)]
/// let vec = vec![1, 2, 3, 4];
/// let (even, odd): (Vec<_>, Vec<_>) = vec.into_iter().partition(|&n| n % 2 == 0);
/// assert_eq!(even, [2, 4]);
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.any(|x| *x == 3));
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert_eq!(it.find(|&x| *x == 3).unwrap(), &3);
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert_eq!(it.position(|x| *x == 3).unwrap(), 2);
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let a = [1, 2, 2, 4, 5];
/// let mut it = a.iter();
/// assert_eq!(it.rposition(|x| *x == 2).unwrap(), 2);
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::iter::MinMaxResult::{NoElements, OneElement, MinMax};
///
/// let a: [i32; 0] = [];
/// # Examples
///
/// ```
- /// use core::num::SignedInt;
+ /// # #![feature(core)]
+ /// use std::num::SignedInt;
///
/// let a = [-3, 0, 1, 5, -10];
/// assert_eq!(*a.iter().max_by(|x| x.abs()).unwrap(), -10);
/// # Examples
///
/// ```
- /// use core::num::SignedInt;
+ /// # #![feature(core)]
+ /// use std::num::SignedInt;
///
/// let a = [-3, 0, 1, 5, -10];
/// assert_eq!(*a.iter().min_by(|x| x.abs()).unwrap(), 0);
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let a = [(1, 2), (3, 4)];
/// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
/// assert_eq!([1, 3], left);
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::iter::AdditiveIterator;
///
/// let a = [1, 2, 3, 4, 5];
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::iter::{count, MultiplicativeIterator};
///
/// fn factorial(n: usize) -> usize {
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::iter::MinMaxResult::{self, NoElements, OneElement, MinMax};
///
/// let r: MinMaxResult<i32> = NoElements;
/// An iterator that yields sequential Fibonacci numbers, and stops on overflow.
///
/// ```
+/// # #![feature(core)]
/// use std::iter::Unfold;
/// use std::num::Int; // For `.checked_add()`
///
/// # Examples
///
/// ```
+/// # #![feature(core)]
/// use std::iter::range_step_inclusive;
///
/// for i in range_step_inclusive(0, 10, 2) {
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/")]
+#![doc(test(no_crate_inject))]
#![feature(no_std)]
#![no_std]
pub mod cmp;
pub mod clone;
pub mod default;
+pub mod convert;
/* Core types and methods on primitives */
/// Iterators:
///
/// ```
+/// # #![feature(core)]
/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
/// for i in std::iter::count(0, 1) {
/// if 3*i < i { panic!("u32 overflow"); }
// empty.
}
+unsafe impl Send for .. { }
+
impl<T> !Send for *const T { }
impl<T> !Send for *mut T { }
impl !Send for Managed { }
// Empty
}
+unsafe impl Sync for .. { }
+
impl<T> !Sync for *const T { }
impl<T> !Sync for *mut T { }
impl !Sync for Managed { }
/// any methods, but instead is used to gate access to data.
///
/// FIXME. Better documentation needed here!
+#[stable(feature = "rust1", since = "1.0.0")]
pub trait MarkerTrait : PhantomFn<Self,Self> { }
// ~~~~~ <-- FIXME(#22806)?
//
/// `MarkerTrait`:
///
/// ```
+/// # #![feature(core)]
/// use std::marker::MarkerTrait;
/// trait Even : MarkerTrait { }
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
+ // FIXME(#23542) Replace with type ascription.
+ #![allow(trivial_casts)]
ptr::read(src as *const T as *const U)
}
/// The fractional part of the number, satisfying:
///
/// ```
- /// use core::num::Float;
+ /// # #![feature(core)]
+ /// use std::num::Float;
///
/// let x = 1.65f32;
/// assert!(x == x.trunc() + x.fract())
/// The fractional part of the number, satisfying:
///
/// ```
- /// use core::num::Float;
+ /// # #![feature(core)]
+ /// use std::num::Float;
///
/// let x = 1.65f64;
/// assert!(x == x.trunc() + x.fract())
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "i16")]
+#![allow(trivial_numeric_casts)]
int_module! { i16, 16 }
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "i32")]
+#![allow(trivial_numeric_casts)]
int_module! { i32, 32 }
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "i64")]
+#![allow(trivial_numeric_casts)]
int_module! { i64, 64 }
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "i8")]
+#![allow(trivial_numeric_casts)]
int_module! { i8, 8 }
// except according to those terms.
#![doc(hidden)]
+#![allow(trivial_numeric_casts)]
macro_rules! int_module { ($T:ty, $bits:expr) => (
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "isize")]
+#![allow(trivial_numeric_casts)]
#[cfg(target_pointer_width = "32")]
int_module! { isize, 32 }
#![stable(feature = "rust1", since = "1.0.0")]
#![allow(missing_docs)]
+#![allow(trivial_numeric_casts)]
use self::wrapping::{OverflowingOps, WrappingOps};
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b01001100u8;
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b01001100u8;
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b0101000u16;
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b0101000u16;
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0x0123456789ABCDEFu64;
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0x0123456789ABCDEFu64;
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// assert_eq!(2.pow(4), 16);
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b01001100u8;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b01001100u8;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b0101000u16;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b0101000u16;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0x0123456789ABCDEFu64;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0x0123456789ABCDEFu64;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// assert_eq!(2.pow(4), 16);
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b01001100u8;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b01001100u8;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b0101000u16;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0b0101000u16;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0x0123456789ABCDEFu64;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// let n = 0x0123456789ABCDEFu64;
/// # Examples
///
/// ```rust
+ /// # #![feature(core)]
/// use std::num::Int;
///
/// assert_eq!(2.pow(4), 16);
/// # Examples
///
/// ```
+/// # #![feature(core)]
/// use std::num;
///
/// let twenty: f32 = num::cast(0x14).unwrap();
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "u16")]
+#![allow(trivial_numeric_casts)]
uint_module! { u16, i16, 16 }
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "u32")]
+#![allow(trivial_numeric_casts)]
uint_module! { u32, i32, 32 }
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "u64")]
+#![allow(trivial_numeric_casts)]
uint_module! { u64, i64, 64 }
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "u8")]
+#![allow(trivial_numeric_casts)]
uint_module! { u8, i8, 8 }
// except according to those terms.
#![doc(hidden)]
+#![allow(trivial_numeric_casts)]
macro_rules! uint_module { ($T:ty, $T_SIGNED:ty, $bits:expr) => (
#![stable(feature = "rust1", since = "1.0.0")]
#![doc(primitive = "usize")]
+#![allow(trivial_numeric_casts)]
uint_module! { usize, isize, ::isize::BITS }
/// impl Index<Bar> for Foo {
/// type Output = Foo;
///
-/// fn index<'a>(&'a self, _index: &Bar) -> &'a Foo {
+/// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
/// println!("Indexing!");
/// self
/// }
type Output: ?Sized;
/// The method for the indexing (`Foo[Bar]`) operation
+ #[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
fn index<'a>(&'a self, index: &Idx) -> &'a Self::Output;
+
+ /// The method for the indexing (`Foo[Bar]`) operation
+ #[cfg(not(stage0))]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn index<'a>(&'a self, index: Idx) -> &'a Self::Output;
}
/// The `IndexMut` trait is used to specify the functionality of indexing
/// impl Index<Bar> for Foo {
/// type Output = Foo;
///
-/// fn index<'a>(&'a self, _index: &Bar) -> &'a Foo {
+/// fn index<'a>(&'a self, _index: Bar) -> &'a Foo {
/// self
/// }
/// }
///
/// impl IndexMut<Bar> for Foo {
-/// fn index_mut<'a>(&'a mut self, _index: &Bar) -> &'a mut Foo {
+/// fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo {
/// println!("Indexing!");
/// self
/// }
#[stable(feature = "rust1", since = "1.0.0")]
pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
/// The method for the indexing (`Foo[Bar]`) operation
+ #[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
fn index_mut<'a>(&'a mut self, index: &Idx) -> &'a mut Self::Output;
+
+ /// The method for the indexing (`Foo[Bar]`) operation
+ #[cfg(not(stage0))]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn index_mut<'a>(&'a mut self, index: Idx) -> &'a mut Self::Output;
}
/// An unbounded range.
#[lang="fn"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_paren_sugar]
+#[cfg(stage0)]
pub trait Fn<Args> {
/// The returned type after the call operator is used.
type Output;
extern "rust-call" fn call(&self, args: Args) -> Self::Output;
}
+/// A version of the call operator that takes an immutable receiver.
+#[lang="fn"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[rustc_paren_sugar]
+#[cfg(not(stage0))]
+pub trait Fn<Args> : FnMut<Args> {
+ /// This is called when the call operator is used.
+ extern "rust-call" fn call(&self, args: Args) -> Self::Output;
+}
+
/// A version of the call operator that takes a mutable receiver.
#[lang="fn_mut"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_paren_sugar]
+#[cfg(stage0)]
pub trait FnMut<Args> {
/// The returned type after the call operator is used.
type Output;
extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
}
+/// A version of the call operator that takes a mutable receiver.
+#[lang="fn_mut"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[rustc_paren_sugar]
+#[cfg(not(stage0))]
+pub trait FnMut<Args> : FnOnce<Args> {
+ /// This is called when the call operator is used.
+ extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
+}
+
/// A version of the call operator that takes a by-value receiver.
#[lang="fn_once"]
#[stable(feature = "rust1", since = "1.0.0")]
extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
}
+#[cfg(stage0)]
impl<F: ?Sized, A> FnMut<A> for F
where F : Fn<A>
{
}
}
+#[cfg(stage0)]
impl<F,A> FnOnce<A> for F
where F : FnMut<A>
{
use ops::{Deref, FnOnce};
use result::Result::{Ok, Err};
use result::Result;
+#[allow(deprecated)]
use slice::AsSlice;
use slice;
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let mut x = Some("Diamonds");
/// {
/// let v = x.as_mut_slice();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let x = Some("foo");
/// assert_eq!(x.ok_or(0), Ok("foo"));
///
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let x = Some("foo");
/// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
///
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// let mut x = Some(4);
/// match x.iter_mut().next() {
/// Some(&mut ref mut v) => *v = 42,
pub fn take(&mut self) -> Option<T> {
mem::replace(self, None)
}
+
+ /// Convert from `Option<T>` to `&[T]` (without copying)
+ #[inline]
+ #[unstable(feature = "as_slice", since = "unsure of the utility here")]
+ pub fn as_slice<'a>(&'a self) -> &'a [T] {
+ match *self {
+ Some(ref x) => slice::ref_slice(x),
+ None => {
+ let result: &[_] = &[];
+ result
+ }
+ }
+ }
}
impl<'a, T: Clone, D: Deref<Target=T>> Option<D> {
#[unstable(feature = "core",
reason = "waiting on the stability of the trait itself")]
+#[deprecated(since = "1.0.0",
+ reason = "use the inherent method instead")]
+#[allow(deprecated)]
impl<T> AsSlice<T> for Option<T> {
/// Convert from `Option<T>` to `&[T]` (without copying)
#[inline]
pub use char::CharExt;
pub use clone::Clone;
pub use cmp::{PartialEq, PartialOrd, Eq, Ord};
+pub use convert::{AsRef, AsMut, Into, From};
pub use iter::{Extend, IteratorExt};
pub use iter::{Iterator, DoubleEndedIterator};
pub use iter::{ExactSizeIterator};
//! Working with unsafe pointers in Rust is uncommon,
//! typically limited to a few patterns.
//!
-//! Use the [`null` function](fn.null.html) to create null pointers,
-//! the [`is_null`](trait.PtrExt.html#tymethod.is_null)
-//! methods of the [`PtrExt` trait](trait.PtrExt.html) to check for null.
-//! The `PtrExt` trait is imported by the prelude, so `is_null` etc.
-//! work everywhere. The `PtrExt` also defines the `offset` method,
-//! for pointer math.
+//! Use the [`null` function](fn.null.html) to create null pointers, and
+//! the `is_null` method of the `*const T` type to check for null.
+//! The `*const T` type also defines the `offset` method, for pointer math.
//!
//! # Common ways to create unsafe pointers
//!
//! the raw pointer. It doesn't destroy `T` or deallocate any memory.
//!
//! ```
+//! # #![feature(alloc)]
//! use std::boxed;
//!
//! unsafe {
//! ## 3. Get it from C.
//!
//! ```
+//! # #![feature(libc)]
//! extern crate libc;
//!
//! use std::mem;
// FIXME #19649: intrinsic docs don't render, so these have no docs :(
#[stable(feature = "rust1", since = "1.0.0")]
-pub use intrinsics::copy_nonoverlapping_memory as copy_nonoverlapping;
+pub use intrinsics::copy_nonoverlapping;
#[stable(feature = "rust1", since = "1.0.0")]
-pub use intrinsics::copy_memory as copy;
+pub use intrinsics::copy;
#[stable(feature = "rust1", since = "1.0.0")]
-pub use intrinsics::set_memory as write_bytes;
-
-extern "rust-intrinsic" {
- #[unstable(feature = "core")]
- #[deprecated(since = "1.0.0", reason = "renamed to `copy_nonoverlapping`")]
- pub fn copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize);
- #[unstable(feature = "core")]
- #[deprecated(since = "1.0.0", reason = "renamed to `copy`")]
- pub fn copy_memory<T>(dst: *mut T, src: *const T, count: usize);
-
- #[unstable(feature = "core",
- reason = "uncertain about naming and semantics")]
- #[deprecated(since = "1.0.0", reason = "renamed to `write_bytes`")]
- pub fn set_memory<T>(dst: *mut T, val: u8, count: usize);
-}
+pub use intrinsics::write_bytes;
/// Creates a null raw pointer.
///
/// Create a new `Unique`.
#[unstable(feature = "unique")]
pub unsafe fn new(ptr: *mut T) -> Unique<T> {
- Unique { pointer: NonZero::new(ptr as *const T), _marker: PhantomData }
+ Unique { pointer: NonZero::new(ptr), _marker: PhantomData }
}
/// Dereference the content.
/// # Examples
///
/// ```
+/// # #![feature(core)]
/// use std::raw::{self, Repr};
///
/// let slice: &[u16] = &[1, 2, 3, 4];
/// # Examples
///
/// ```
+/// # #![feature(core)]
/// use std::mem;
/// use std::raw;
///
//! by the [`Writer`](../io/trait.Writer.html) trait:
//!
//! ```
+//! # #![feature(old_io)]
//! use std::old_io::IoError;
//!
//! trait Writer {
//! something like this:
//!
//! ```{.ignore}
+//! # #![feature(old_io)]
//! use std::old_io::*;
//! use std::old_path::Path;
//!
//! a marginally useful message indicating why:
//!
//! ```{.no_run}
+//! # #![feature(old_io, old_path)]
//! use std::old_io::*;
//! use std::old_path::Path;
//!
//! You might also simply assert success:
//!
//! ```{.no_run}
+//! # #![feature(old_io, old_path)]
//! # use std::old_io::*;
//! # use std::old_path::Path;
//!
//! Or propagate the error up the call stack with `try!`:
//!
//! ```
+//! # #![feature(old_io, old_path)]
//! # use std::old_io::*;
//! # use std::old_path::Path;
//! fn write_message() -> Result<(), IoError> {
//! It replaces this:
//!
//! ```
+//! # #![feature(old_io, old_path)]
//! use std::old_io::*;
//! use std::old_path::Path;
//!
//! With this:
//!
//! ```
+//! # #![feature(old_io, old_path)]
//! use std::old_io::*;
//! use std::old_path::Path;
//!
FromIterator, ExactSizeIterator, IntoIterator};
use ops::{FnMut, FnOnce};
use option::Option::{self, None, Some};
+#[allow(deprecated)]
use slice::AsSlice;
use slice;
}
}
+ /// Convert from `Result<T, E>` to `&[T]` (without copying)
+ #[inline]
+ #[unstable(feature = "as_slice", since = "unsure of the utility here")]
+ pub fn as_slice(&self) -> &[T] {
+ match *self {
+ Ok(ref x) => slice::ref_slice(x),
+ Err(_) => {
+ // work around lack of implicit coercion from fixed-size array to slice
+ let emp: &[_] = &[];
+ emp
+ }
+ }
+ }
+
/// Convert from `Result<T, E>` to `&mut [T]` (without copying)
///
/// ```
+ /// # #![feature(core)]
/// let mut x: Result<&str, u32> = Ok("Gold");
/// {
/// let v = x.as_mut_slice();
/// ignoring I/O and parse errors:
///
/// ```
+ /// # #![feature(old_io)]
/// use std::old_io::*;
///
/// let mut buffer: &[u8] = b"1\n2\n3\n4\n";
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
+#[unstable(feature = "core",
+ reason = "waiting on the stability of the trait itself")]
+#[deprecated(since = "1.0.0",
+ reason = "use inherent method instead")]
+#[allow(deprecated)]
impl<T, E> AsSlice<T> for Result<T, E> {
/// Convert from `Result<T, E>` to `&[T]` (without copying)
#[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
fn as_slice<'a>(&'a self) -> &'a [T] {
match *self {
Ok(ref x) => slice::ref_slice(x),
//! provided beyond this module.
//!
//! ```rust
-//!
+//! # #![feature(core)]
//! fn main() {
//! use std::simd::f32x4;
//! let a = f32x4(40.0, 41.0, 42.0, 43.0);
#[inline]
fn as_mut_slice(&mut self) -> &mut [T] { self }
+ #[cfg(stage0)]
#[inline]
fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
unsafe {
}
}
+ #[cfg(not(stage0))]
+ #[inline]
+ fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
+ unsafe {
+ let self2: &mut [T] = mem::transmute_copy(&self);
+
+ (ops::IndexMut::index_mut(self, ops::RangeTo { end: mid } ),
+ ops::IndexMut::index_mut(self2, ops::RangeFrom { start: mid } ))
+ }
+ }
+
#[inline]
fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
unsafe {
impl<T> ops::Index<usize> for [T] {
type Output = T;
+ #[cfg(stage0)]
fn index(&self, &index: &usize) -> &T {
assert!(index < self.len());
unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
}
+
+ #[cfg(not(stage0))]
+ fn index(&self, index: usize) -> &T {
+ assert!(index < self.len());
+
+ unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<usize> for [T] {
+ #[cfg(stage0)]
+ #[inline]
fn index_mut(&mut self, &index: &usize) -> &mut T {
assert!(index < self.len());
unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: usize) -> &mut T {
+ assert!(index < self.len());
+
+ unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Index<ops::Range<usize>> for [T] {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::Range<usize>) -> &[T] {
assert!(index.start <= index.end);
)
}
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::Range<usize>) -> &[T] {
+ assert!(index.start <= index.end);
+ assert!(index.end <= self.len());
+ unsafe {
+ from_raw_parts (
+ self.as_ptr().offset(index.start as isize),
+ index.end - index.start
+ )
+ }
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Index<ops::RangeTo<usize>> for [T] {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
self.index(&ops::Range{ start: 0, end: index.end })
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
+ self.index(ops::Range{ start: 0, end: index.end })
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Index<ops::RangeFrom<usize>> for [T] {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
self.index(&ops::Range{ start: index.start, end: self.len() })
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
+ self.index(ops::Range{ start: index.start, end: self.len() })
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::Index<RangeFull> for [T] {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, _index: &RangeFull) -> &[T] {
self
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, _index: RangeFull) -> &[T] {
+ self
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::Range<usize>> for [T] {
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
assert!(index.start <= index.end);
)
}
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
+ assert!(index.start <= index.end);
+ assert!(index.end <= self.len());
+ unsafe {
+ from_raw_parts_mut(
+ self.as_mut_ptr().offset(index.start as isize),
+ index.end - index.start
+ )
+ }
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::RangeTo<usize>> for [T] {
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
self.index_mut(&ops::Range{ start: 0, end: index.end })
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
+ self.index_mut(ops::Range{ start: 0, end: index.end })
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::RangeFrom<usize>> for [T] {
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
let len = self.len();
self.index_mut(&ops::Range{ start: index.start, end: len })
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
+ let len = self.len();
+ self.index_mut(ops::Range{ start: index.start, end: len })
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<RangeFull> for [T] {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
self
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, _index: RangeFull) -> &mut [T] {
+ self
+ }
}
/// Data that is viewable as a slice.
#[unstable(feature = "core",
reason = "will be replaced by slice syntax")]
+#[deprecated(since = "1.0.0",
+ reason = "use std::convert::AsRef<[T]> instead")]
pub trait AsSlice<T> {
/// Work with `self` as a slice.
fn as_slice<'a>(&'a self) -> &'a [T];
}
#[unstable(feature = "core", reason = "trait is experimental")]
+#[allow(deprecated)]
impl<T> AsSlice<T> for [T] {
#[inline(always)]
fn as_slice<'a>(&'a self) -> &'a [T] { self }
}
#[unstable(feature = "core", reason = "trait is experimental")]
+#[allow(deprecated)]
impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U {
#[inline(always)]
fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
}
#[unstable(feature = "core", reason = "trait is experimental")]
+#[allow(deprecated)]
impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U {
#[inline(always)]
fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
#[unstable(feature = "core")]
impl<'a, T> ops::Index<ops::Range<usize>> for Iter<'a, T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::Range<usize>) -> &[T] {
self.as_slice().index(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::Range<usize>) -> &[T] {
+ self.as_slice().index(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::Index<ops::RangeTo<usize>> for Iter<'a, T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
self.as_slice().index(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
+ self.as_slice().index(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::Index<ops::RangeFrom<usize>> for Iter<'a, T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
self.as_slice().index(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
+ self.as_slice().index(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::Index<RangeFull> for Iter<'a, T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, _index: &RangeFull) -> &[T] {
self.as_slice()
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, _index: RangeFull) -> &[T] {
+ self.as_slice()
+ }
}
impl<'a, T> Iter<'a, T> {
#[unstable(feature = "core")]
impl<'a, T> ops::Index<ops::Range<usize>> for IterMut<'a, T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::Range<usize>) -> &[T] {
self.index(&RangeFull).index(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::Range<usize>) -> &[T] {
+ self.index(RangeFull).index(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::Index<ops::RangeTo<usize>> for IterMut<'a, T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
self.index(&RangeFull).index(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
+ self.index(RangeFull).index(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::Index<ops::RangeFrom<usize>> for IterMut<'a, T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
self.index(&RangeFull).index(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
+ self.index(RangeFull).index(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::Index<RangeFull> for IterMut<'a, T> {
type Output = [T];
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, _index: &RangeFull) -> &[T] {
make_slice!(T => &[T]: self.ptr, self.end)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, _index: RangeFull) -> &[T] {
+ make_slice!(T => &[T]: self.ptr, self.end)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::IndexMut<ops::Range<usize>> for IterMut<'a, T> {
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
self.index_mut(&RangeFull).index_mut(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
+ self.index_mut(RangeFull).index_mut(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::IndexMut<ops::RangeTo<usize>> for IterMut<'a, T> {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
self.index_mut(&RangeFull).index_mut(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
+ self.index_mut(RangeFull).index_mut(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::IndexMut<ops::RangeFrom<usize>> for IterMut<'a, T> {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
self.index_mut(&RangeFull).index_mut(index)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
+ self.index_mut(RangeFull).index_mut(index)
+ }
}
#[unstable(feature = "core")]
impl<'a, T> ops::IndexMut<RangeFull> for IterMut<'a, T> {
+
+ #[cfg(stage0)]
#[inline]
fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
make_mut_slice!(T => &mut [T]: self.ptr, self.end)
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index_mut(&mut self, _index: RangeFull) -> &mut [T] {
+ make_mut_slice!(T => &mut [T]: self.ptr, self.end)
+ }
}
/// # Examples
///
/// ```
+/// #![feature(core)]
/// use std::slice;
///
/// // manifest a slice out of thin air!
use marker::Sized;
use mem;
use num::Int;
-use ops::{Fn, FnMut};
+use ops::{Fn, FnMut, FnOnce};
use option::Option::{self, None, Some};
use raw::{Repr, Slice};
use result::Result::{self, Ok, Err};
self.0.size_hint()
}
}
- }
+ };
+ (pattern reverse $te:ty : $ti:ty) => {
+ #[stable(feature = "rust1", since = "1.0.0")]
+ impl<'a, P: Pattern<'a>> Iterator for $ti
+ where P::Searcher: ReverseSearcher<'a>
+ {
+ type Item = $te;
+
+ #[inline]
+ fn next(&mut self) -> Option<$te> {
+ self.0.next()
+ }
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.0.size_hint()
+ }
+ }
+ };
}
/// A trait to abstract the idea of creating a new instance of a type from a
reason = "use std::ffi::c_str_to_bytes + str::from_utf8")]
pub unsafe fn from_c_str(s: *const i8) -> &'static str {
let s = s as *const u8;
- let mut len = 0;
+ let mut len: usize = 0;
while *s.offset(len as isize) != 0 {
len += 1;
}
#[derive(Copy, Clone)]
struct BytesDeref;
+#[cfg(stage0)]
impl<'a> Fn<(&'a u8,)> for BytesDeref {
type Output = u8;
}
}
+#[cfg(not(stage0))]
+impl<'a> Fn<(&'a u8,)> for BytesDeref {
+ #[inline]
+ extern "rust-call" fn call(&self, (ptr,): (&'a u8,)) -> u8 {
+ *ptr
+ }
+}
+
+#[cfg(not(stage0))]
+impl<'a> FnMut<(&'a u8,)> for BytesDeref {
+ #[inline]
+ extern "rust-call" fn call_mut(&mut self, (ptr,): (&'a u8,)) -> u8 {
+ Fn::call(&*self, (ptr,))
+ }
+}
+
+#[cfg(not(stage0))]
+impl<'a> FnOnce<(&'a u8,)> for BytesDeref {
+ type Output = u8;
+
+ #[inline]
+ extern "rust-call" fn call_once(self, (ptr,): (&'a u8,)) -> u8 {
+ Fn::call(&self, (ptr,))
+ }
+}
+
/// An iterator over the substrings of a string, separated by `sep`.
struct CharSplits<'a, P: Pattern<'a>> {
/// The slice remaining to be iterated
iter: CharSplits<'a, P>,
/// The number of splits remaining
count: usize,
- invert: bool,
+}
+
+/// An iterator over the substrings of a string, separated by a
+/// pattern, in reverse order.
+struct RCharSplits<'a, P: Pattern<'a>> {
+ /// The slice remaining to be iterated
+ start: usize,
+ end: usize,
+ matcher: P::Searcher,
+ /// Whether an empty string at the end of iteration is allowed
+ allow_final_empty: bool,
+ finished: bool,
+}
+
+/// An iterator over the substrings of a string, separated by a
+/// pattern, splitting at most `count` times, in reverse order.
+struct RCharSplitsN<'a, P: Pattern<'a>> {
+ iter: RCharSplits<'a, P>,
+ /// The number of splits remaining
+ count: usize,
}
/// An iterator over the lines of a string, separated by `\n`.
}
#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, P: Pattern<'a>> Iterator for CharSplitsN<'a, P>
-where P::Searcher: DoubleEndedSearcher<'a> {
+impl<'a, P: Pattern<'a>> Iterator for CharSplitsN<'a, P> {
type Item = &'a str;
#[inline]
fn next(&mut self) -> Option<&'a str> {
if self.count != 0 {
self.count -= 1;
- if self.invert { self.iter.next_back() } else { self.iter.next() }
+ self.iter.next()
} else {
self.iter.get_end()
}
}
}
+impl<'a, P: Pattern<'a>> RCharSplits<'a, P> {
+ #[inline]
+ fn get_remainder(&mut self) -> Option<&'a str> {
+ if !self.finished && (self.allow_final_empty || self.end - self.start > 0) {
+ self.finished = true;
+ unsafe {
+ let string = self.matcher.haystack().slice_unchecked(self.start, self.end);
+ Some(string)
+ }
+ } else {
+ None
+ }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, P: Pattern<'a>> Iterator for RCharSplits<'a, P>
+ where P::Searcher: ReverseSearcher<'a>
+{
+ type Item = &'a str;
+
+ #[inline]
+ fn next(&mut self) -> Option<&'a str> {
+ if self.finished { return None }
+
+ let haystack = self.matcher.haystack();
+ match self.matcher.next_match_back() {
+ Some((a, b)) => unsafe {
+ let elt = haystack.slice_unchecked(b, self.end);
+ self.end = a;
+ Some(elt)
+ },
+ None => self.get_remainder(),
+ }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, P: Pattern<'a>> Iterator for RCharSplitsN<'a, P>
+ where P::Searcher: ReverseSearcher<'a>
+{
+ type Item = &'a str;
+
+ #[inline]
+ fn next(&mut self) -> Option<&'a str> {
+ if self.count != 0 {
+ self.count -= 1;
+ self.iter.next()
+ } else {
+ self.iter.get_remainder()
+ }
+ }
+}
+
/// The internal state of an iterator that searches for matches of a substring
/// within a larger string using two-way search
#[derive(Clone)]
/// // byte 100 is outside the string
/// // &s[3 .. 100];
/// ```
+ #[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::Range<usize>> for str {
type Output = str;
}
}
+ /// Returns a slice of the given string from the byte range
+ /// [`begin`..`end`).
+ ///
+ /// This operation is `O(1)`.
+ ///
+ /// Panics when `begin` and `end` do not point to valid characters
+ /// or point beyond the last character of the string.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let s = "Löwe 老虎 Léopard";
+ /// assert_eq!(&s[0 .. 1], "L");
+ ///
+ /// assert_eq!(&s[1 .. 9], "öwe 老");
+ ///
+ /// // these will panic:
+ /// // byte 2 lies within `ö`:
+ /// // &s[2 ..3];
+ ///
+ /// // byte 8 lies within `老`
+ /// // &s[1 .. 8];
+ ///
+ /// // byte 100 is outside the string
+ /// // &s[3 .. 100];
+ /// ```
+ #[cfg(not(stage0))]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ impl ops::Index<ops::Range<usize>> for str {
+ type Output = str;
+ #[inline]
+ fn index(&self, index: ops::Range<usize>) -> &str {
+ // is_char_boundary checks that the index is in [0, .len()]
+ if index.start <= index.end &&
+ self.is_char_boundary(index.start) &&
+ self.is_char_boundary(index.end) {
+ unsafe { self.slice_unchecked(index.start, index.end) }
+ } else {
+ super::slice_error_fail(self, index.start, index.end)
+ }
+ }
+ }
+
/// Returns a slice of the string from the beginning to byte
/// `end`.
///
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeTo<usize>> for str {
type Output = str;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeTo<usize>) -> &str {
// is_char_boundary checks that the index is in [0, .len()]
super::slice_error_fail(self, 0, index.end)
}
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeTo<usize>) -> &str {
+ // is_char_boundary checks that the index is in [0, .len()]
+ if self.is_char_boundary(index.end) {
+ unsafe { self.slice_unchecked(0, index.end) }
+ } else {
+ super::slice_error_fail(self, 0, index.end)
+ }
+ }
}
/// Returns a slice of the string from `begin` to its end.
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFrom<usize>> for str {
type Output = str;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, index: &ops::RangeFrom<usize>) -> &str {
// is_char_boundary checks that the index is in [0, .len()]
super::slice_error_fail(self, index.start, self.len())
}
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, index: ops::RangeFrom<usize>) -> &str {
+ // is_char_boundary checks that the index is in [0, .len()]
+ if self.is_char_boundary(index.start) {
+ unsafe { self.slice_unchecked(index.start, self.len()) }
+ } else {
+ super::slice_error_fail(self, index.start, self.len())
+ }
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for str {
type Output = str;
+
+ #[cfg(stage0)]
#[inline]
fn index(&self, _index: &ops::RangeFull) -> &str {
self
}
+
+ #[cfg(not(stage0))]
+ #[inline]
+ fn index(&self, _index: ops::RangeFull) -> &str {
+ self
+ }
}
}
reason = "Instead of taking this bound generically, this trait will be \
replaced with one of slicing syntax (&foo[..]), deref coercions, or \
a more generic conversion trait")]
+#[deprecated(since = "1.0.0",
+ reason = "use std::convert::AsRef<str> instead")]
pub trait Str {
/// Work with `self` as a slice.
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, S: ?Sized> Str for &'a S where S: Str {
#[inline]
fn as_slice(&self) -> &str { Str::as_slice(*self) }
/// Return type of `StrExt::split`
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Split<'a, P: Pattern<'a>>(CharSplits<'a, P>);
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, P: Pattern<'a>> Iterator for Split<'a, P> {
- type Item = &'a str;
-
- #[inline]
- fn next(&mut self) -> Option<&'a str> {
- self.0.next()
- }
-}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, P: Pattern<'a>> DoubleEndedIterator for Split<'a, P>
-where P::Searcher: DoubleEndedSearcher<'a> {
- #[inline]
- fn next_back(&mut self) -> Option<&'a str> {
- self.0.next_back()
- }
-}
+delegate_iter!{pattern &'a str : Split<'a, P>}
/// Return type of `StrExt::split_terminator`
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SplitN<'a, P: Pattern<'a>>(CharSplitsN<'a, P>);
delegate_iter!{pattern forward &'a str : SplitN<'a, P>}
+/// Return type of `StrExt::rsplit`
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct RSplit<'a, P: Pattern<'a>>(RCharSplits<'a, P>);
+delegate_iter!{pattern reverse &'a str : RSplit<'a, P>}
+
/// Return type of `StrExt::rsplitn`
#[stable(feature = "rust1", since = "1.0.0")]
-pub struct RSplitN<'a, P: Pattern<'a>>(CharSplitsN<'a, P>);
-delegate_iter!{pattern forward &'a str : RSplitN<'a, P>}
+pub struct RSplitN<'a, P: Pattern<'a>>(RCharSplitsN<'a, P>);
+delegate_iter!{pattern reverse &'a str : RSplitN<'a, P>}
/// Methods for string slices
#[allow(missing_docs)]
fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>;
fn splitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> SplitN<'a, P>;
fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
- fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>;
+ fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
+ where P::Searcher: ReverseSearcher<'a>;
+ fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
+ where P::Searcher: ReverseSearcher<'a>;
fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
#[allow(deprecated) /* for SplitStr */]
fn split_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitStr<'a, P>;
SplitN(CharSplitsN {
iter: self.split(pat).0,
count: count,
- invert: false,
})
}
}
#[inline]
- fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P> {
- RSplitN(CharSplitsN {
- iter: self.split(pat).0,
+ fn rsplit<'a, P: Pattern<'a>>(&'a self, pat: P) -> RSplit<'a, P>
+ where P::Searcher: ReverseSearcher<'a>
+ {
+ RSplit(RCharSplits {
+ start: 0,
+ end: self.len(),
+ matcher: pat.into_searcher(self),
+ allow_final_empty: true,
+ finished: false,
+ })
+ }
+
+ #[inline]
+ fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>
+ where P::Searcher: ReverseSearcher<'a>
+ {
+ RSplitN(RCharSplitsN {
+ iter: self.rsplit(pat).0,
count: count,
- invert: true,
})
}
s, CharEqPattern(s));
}
+/// A convenience impl that delegates to the impl for `&str`
+impl<'a, 'b> Pattern<'a> for &'b &'b str {
+ type Searcher = <&'b str as Pattern<'a>>::Searcher;
+ associated_items!(<&'b str as Pattern<'a>>::Searcher,
+ s, (*s));
+}
+
/// Searches for chars that match the given predicate
impl<'a, F> Pattern<'a> for F where F: FnMut(char) -> bool {
type Searcher = <CharEqPattern<Self> as Pattern<'a>>::Searcher;
associated_items!(<CharEqPattern<Self> as Pattern<'a>>::Searcher,
s, CharEqPattern(s));
}
-
-// Deref-forward impl
-
-use ops::Deref;
-
-/// Delegates to the next deref coercion of `Self` that implements `Pattern`
-impl<'a, 'b, P: 'b + ?Sized, T: Deref<Target = P> + ?Sized> Pattern<'a> for &'b T
- where &'b P: Pattern<'a>
-{
- type Searcher = <&'b P as Pattern<'a>>::Searcher;
- associated_items!(<&'b P as Pattern<'a>>::Searcher,
- s, (&**s));
-}
#![feature(io)]
#![feature(collections)]
#![feature(debug_builders)]
+#![feature(unique)]
+#![feature(step_by)]
#![allow(deprecated)] // rand
extern crate core;
trait Foo { fn dummy(&self) { } }
impl Foo for int {}
- let a = box 100 as Box<Foo>;
+ let a = box 100isize as Box<Foo>;
unsafe {
let x: ::core::raw::TraitObject = transmute(a);
assert!(*(x.data as *const int) == 100);
let v0 = vec![32000u16, 32001u16, 32002u16];
let mut v1 = vec![0u16, 0u16, 0u16];
- copy_memory(v1.as_mut_ptr().offset(1),
- v0.as_ptr().offset(1), 1);
+ copy(v1.as_mut_ptr().offset(1),
+ v0.as_ptr().offset(1), 1);
assert!((v1[0] == 0u16 &&
v1[1] == 32001u16 &&
v1[2] == 0u16));
- copy_memory(v1.as_mut_ptr(),
- v0.as_ptr().offset(2), 1);
+ copy(v1.as_mut_ptr(),
+ v0.as_ptr().offset(2), 1);
assert!((v1[0] == 32002u16 &&
v1[1] == 32001u16 &&
v1[2] == 0u16));
- copy_memory(v1.as_mut_ptr().offset(2),
- v0.as_ptr(), 1);
+ copy(v1.as_mut_ptr().offset(2),
+ v0.as_ptr(), 1);
assert!((v1[0] == 32002u16 &&
v1[1] == 32001u16 &&
v1[2] == 32000u16));
assert_eq!(q.as_ref().unwrap(), &2);
// Lifetime inference
- let u = 2;
+ let u = 2isize;
{
- let p: *const int = &u as *const _;
+ let p = &u as *const int;
assert_eq!(p.as_ref().unwrap(), &2);
}
}
assert!(q.as_mut().unwrap() == &mut 2);
// Lifetime inference
- let mut u = 2;
+ let mut u = 2isize;
{
- let p: *mut int = &mut u as *mut _;
+ let p = &mut u as *mut int;
assert!(p.as_mut().unwrap() == &mut 2);
}
}
fn test_set_memory() {
let mut xs = [0u8; 20];
let ptr = xs.as_mut_ptr();
- unsafe { set_memory(ptr, 5u8, xs.len()); }
+ unsafe { write_bytes(ptr, 5u8, xs.len()); }
assert!(xs == [5u8; 20]);
}
#[test]
fn test_unsized_unique() {
- let xs: &mut [_] = &mut [1, 2, 3];
- let ptr = unsafe { Unique::new(xs as *mut [_]) };
+ let xs: &mut [i32] = &mut [1, 2, 3];
+ let ptr = unsafe { Unique::new(xs as *mut [i32]) };
let ys = unsafe { &mut **ptr };
- let zs: &mut [_] = &mut [1, 2, 3];
+ let zs: &mut [i32] = &mut [1, 2, 3];
assert!(ys == zs);
}
let data = "aabcdaa";
assert!(data.contains("bcd"));
assert!(data.contains(&"bcd"));
- assert!(data.contains(&&"bcd"));
assert!(data.contains(&"bcd".to_string()));
- assert!(data.contains(&&"bcd".to_string()));
}
#[test]
#![feature(libc)]
#![feature(staged_api)]
#![feature(unique)]
+#![cfg_attr(test, feature(rustc_private, rand, collections))]
#[cfg(test)] #[macro_use] extern crate log;
//! which is cyclic.
//!
//! ```rust
+//! # #![feature(rustc_private, core, into_cow)]
//! use std::borrow::IntoCow;
//! use std::io::Write;
//! use graphviz as dot;
//!
-//! type Nd = int;
-//! type Ed = (int,int);
+//! type Nd = isize;
+//! type Ed = (isize,isize);
//! struct Edges(Vec<Ed>);
//!
//! pub fn render_to<W: Write>(output: &mut W) {
//! direct reference to the `(source,target)` pair stored in the graph's
//! internal vector (rather than passing around a copy of the pair
//! itself). Note that this implies that `fn edges(&'a self)` must
-//! construct a fresh `Vec<&'a (uint,uint)>` from the `Vec<(uint,uint)>`
+//! construct a fresh `Vec<&'a (usize,usize)>` from the `Vec<(usize,usize)>`
//! edges stored in `self`.
//!
//! Since both the set of nodes and the set of edges are always
//! entity `&sube`).
//!
//! ```rust
+//! # #![feature(rustc_private, core, into_cow)]
//! use std::borrow::IntoCow;
//! use std::io::Write;
//! use graphviz as dot;
//!
-//! type Nd = uint;
-//! type Ed<'a> = &'a (uint, uint);
-//! struct Graph { nodes: Vec<&'static str>, edges: Vec<(uint,uint)> }
+//! type Nd = usize;
+//! type Ed<'a> = &'a (usize, usize);
+//! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
//!
//! pub fn render_to<W: Write>(output: &mut W) {
//! let nodes = vec!("{x,y}","{x}","{y}","{}");
//! Hasse-diagram for the subsets of the set `{x, y}`.
//!
//! ```rust
+//! # #![feature(rustc_private, core, into_cow)]
//! use std::borrow::IntoCow;
//! use std::io::Write;
//! use graphviz as dot;
//!
-//! type Nd<'a> = (uint, &'a str);
+//! type Nd<'a> = (usize, &'a str);
//! type Ed<'a> = (Nd<'a>, Nd<'a>);
-//! struct Graph { nodes: Vec<&'static str>, edges: Vec<(uint,uint)> }
+//! struct Graph { nodes: Vec<&'static str>, edges: Vec<(usize,usize)> }
//!
//! pub fn render_to<W: Write>(output: &mut W) {
//! let nodes = vec!("{x,y}","{x}","{y}","{}");
//! }
//! fn node_label<'b>(&'b self, n: &Nd<'b>) -> dot::LabelText<'b> {
//! let &(i, _) = n;
-//! dot::LabelText::LabelStr(self.nodes[i].as_slice().into_cow())
+//! dot::LabelText::LabelStr(self.nodes[i].into_cow())
//! }
//! fn edge_label<'b>(&'b self, _: &Ed<'b>) -> dot::LabelText<'b> {
//! dot::LabelText::LabelStr("⊆".into_cow())
//!
//! impl<'a> dot::GraphWalk<'a, Nd<'a>, Ed<'a>> for Graph {
//! fn nodes(&'a self) -> dot::Nodes<'a,Nd<'a>> {
-//! self.nodes.iter().map(|s|s.as_slice()).enumerate().collect()
+//! self.nodes.iter().map(|s| &s[..]).enumerate().collect()
//! }
//! fn edges(&'a self) -> dot::Edges<'a,Ed<'a>> {
//! self.edges.iter()
-//! .map(|&(i,j)|((i, self.nodes[i].as_slice()),
-//! (j, self.nodes[j].as_slice())))
+//! .map(|&(i,j)|((i, &self.nodes[i][..]),
+//! (j, &self.nodes[j][..])))
//! .collect()
//! }
//! fn source(&self, e: &Ed<'a>) -> Nd<'a> { let &(s,_) = e; s }
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(int_uint)]
#![feature(collections)]
+#![feature(into_cow)]
use self::LabelText::*;
is_letter_or_underscore(c) || in_range('0', c, '9')
}
fn in_range(low: char, c: char, high: char) -> bool {
- low as uint <= c as uint && c as uint <= high as uint
+ low as usize <= c as usize && c as usize <= high as usize
}
}
use std::iter::repeat;
/// each node is an index in a vector in the graph.
- type Node = uint;
+ type Node = usize;
struct Edge {
- from: uint, to: uint, label: &'static str
+ from: usize, to: usize, label: &'static str
}
- fn edge(from: uint, to: uint, label: &'static str) -> Edge {
+ fn edge(from: usize, to: usize, label: &'static str) -> Edge {
Edge { from: from, to: to, label: label }
}
enum NodeLabels<L> {
AllNodesLabelled(Vec<L>),
- UnlabelledNodes(uint),
+ UnlabelledNodes(usize),
SomeNodesLabelled(Vec<Option<L>>),
}
pub const S_IXUSR : c_int = 64;
pub const S_IWUSR : c_int = 128;
pub const S_IRUSR : c_int = 256;
+ pub const S_IRWXG : mode_t = 56;
+ pub const S_IXGRP : mode_t = 8;
+ pub const S_IWGRP : mode_t = 16;
+ pub const S_IRGRP : mode_t = 32;
+ pub const S_IRWXO : mode_t = 7;
+ pub const S_IXOTH : mode_t = 1;
+ pub const S_IWOTH : mode_t = 2;
+ pub const S_IROTH : mode_t = 4;
pub const F_OK : c_int = 0;
pub const R_OK : c_int = 4;
pub const W_OK : c_int = 2;
pub const TCP_NODELAY: c_int = 0x0001;
pub const SOL_SOCKET: c_int = 0xffff;
- pub const SO_KEEPALIVE: c_int = 8;
- pub const SO_BROADCAST: c_int = 32;
- pub const SO_REUSEADDR: c_int = 4;
+
+ pub const SO_DEBUG: c_int = 0x0001;
+ pub const SO_ACCEPTCONN: c_int = 0x0002;
+ pub const SO_REUSEADDR: c_int = 0x0004;
+ pub const SO_KEEPALIVE: c_int = 0x0008;
+ pub const SO_DONTROUTE: c_int = 0x0010;
+ pub const SO_BROADCAST: c_int = 0x0020;
+ pub const SO_USELOOPBACK: c_int = 0x0040;
+ pub const SO_LINGER: c_int = 0x0080;
+ pub const SO_OOBINLINE: c_int = 0x0100;
+ pub const SO_SNDBUF: c_int = 0x1001;
+ pub const SO_RCVBUF: c_int = 0x1002;
+ pub const SO_SNDLOWAT: c_int = 0x1003;
+ pub const SO_RCVLOWAT: c_int = 0x1004;
+ pub const SO_SNDTIMEO: c_int = 0x1005;
+ pub const SO_RCVTIMEO: c_int = 0x1006;
pub const SO_ERROR: c_int = 0x1007;
+ pub const SO_TYPE: c_int = 0x1008;
pub const IFF_LOOPBACK: c_int = 4;
pub const S_IXUSR : mode_t = 64;
pub const S_IWUSR : mode_t = 128;
pub const S_IRUSR : mode_t = 256;
+ pub const S_IRWXG : mode_t = 56;
+ pub const S_IXGRP : mode_t = 8;
+ pub const S_IWGRP : mode_t = 16;
+ pub const S_IRGRP : mode_t = 32;
+ pub const S_IRWXO : mode_t = 7;
+ pub const S_IXOTH : mode_t = 1;
+ pub const S_IWOTH : mode_t = 2;
+ pub const S_IROTH : mode_t = 4;
pub const F_OK : c_int = 0;
pub const R_OK : c_int = 4;
pub const W_OK : c_int = 2;
pub const S_IXUSR : mode_t = 64;
pub const S_IWUSR : mode_t = 128;
pub const S_IRUSR : mode_t = 256;
+ pub const S_IRWXG : mode_t = 56;
+ pub const S_IXGRP : mode_t = 8;
+ pub const S_IWGRP : mode_t = 16;
+ pub const S_IRGRP : mode_t = 32;
+ pub const S_IRWXO : mode_t = 7;
+ pub const S_IXOTH : mode_t = 1;
+ pub const S_IWOTH : mode_t = 2;
+ pub const S_IROTH : mode_t = 4;
pub const F_OK : c_int = 0;
pub const R_OK : c_int = 4;
pub const W_OK : c_int = 2;
pub const TCP_NODELAY: c_int = 1;
pub const SOL_SOCKET: c_int = 1;
- pub const SO_KEEPALIVE: c_int = 9;
- pub const SO_BROADCAST: c_int = 6;
+
+ pub const SO_DEBUG: c_int = 1;
pub const SO_REUSEADDR: c_int = 2;
+ pub const SO_TYPE: c_int = 3;
pub const SO_ERROR: c_int = 4;
+ pub const SO_DONTROUTE: c_int = 5;
+ pub const SO_BROADCAST: c_int = 6;
+ pub const SO_SNDBUF: c_int = 7;
+ pub const SO_RCVBUF: c_int = 8;
+ pub const SO_KEEPALIVE: c_int = 9;
+ pub const SO_OOBINLINE: c_int = 10;
+ pub const SO_LINGER: c_int = 13;
+ pub const SO_REUSEPORT: c_int = 15;
+ pub const SO_RCVLOWAT: c_int = 18;
+ pub const SO_SNDLOWAT: c_int = 19;
+ pub const SO_RCVTIMEO: c_int = 20;
+ pub const SO_SNDTIMEO: c_int = 21;
+ pub const SO_ACCEPTCONN: c_int = 30;
pub const SHUT_RD: c_int = 0;
pub const SHUT_WR: c_int = 1;
pub const TCP_NODELAY: c_int = 1;
pub const SOL_SOCKET: c_int = 65535;
- pub const SO_KEEPALIVE: c_int = 8;
- pub const SO_BROADCAST: c_int = 32;
- pub const SO_REUSEADDR: c_int = 4;
- pub const SO_ERROR: c_int = 4103;
+
+ pub const SO_DEBUG: c_int = 0x0001;
+ pub const SO_REUSEADDR: c_int = 0x0004;
+ pub const SO_KEEPALIVE: c_int = 0x0008;
+ pub const SO_DONTROUTE: c_int = 0x0010;
+ pub const SO_BROADCAST: c_int = 0x0020;
+ pub const SO_LINGER: c_int = 0x0080;
+ pub const SO_OOBINLINE: c_int = 0x100;
+ pub const SO_REUSEPORT: c_int = 0x0200;
+ pub const SO_SNDBUF: c_int = 0x1001;
+ pub const SO_RCVBUF: c_int = 0x1002;
+ pub const SO_SNDLOWAT: c_int = 0x1003;
+ pub const SO_RCVLOWAT: c_int = 0x1004;
+ pub const SO_SNDTIMEO: c_int = 0x1005;
+ pub const SO_RCVTIMEO: c_int = 0x1006;
+ pub const SO_ERROR: c_int = 0x1007;
+ pub const SO_TYPE: c_int = 0x1008;
+ pub const SO_ACCEPTCONN: c_int = 0x1009;
pub const SHUT_RD: c_int = 0;
pub const SHUT_WR: c_int = 1;
pub const S_IXUSR : mode_t = 64;
pub const S_IWUSR : mode_t = 128;
pub const S_IRUSR : mode_t = 256;
+ pub const S_IRWXG : mode_t = 56;
+ pub const S_IXGRP : mode_t = 8;
+ pub const S_IWGRP : mode_t = 16;
+ pub const S_IRGRP : mode_t = 32;
+ pub const S_IRWXO : mode_t = 7;
+ pub const S_IXOTH : mode_t = 1;
+ pub const S_IWOTH : mode_t = 2;
+ pub const S_IROTH : mode_t = 4;
pub const F_OK : c_int = 0;
pub const R_OK : c_int = 4;
pub const W_OK : c_int = 2;
pub const TCP_NODELAY: c_int = 1;
pub const TCP_KEEPIDLE: c_int = 256;
pub const SOL_SOCKET: c_int = 0xffff;
+ pub const SO_DEBUG: c_int = 0x01;
+ pub const SO_ACCEPTCONN: c_int = 0x0002;
+ pub const SO_REUSEADDR: c_int = 0x0004;
pub const SO_KEEPALIVE: c_int = 0x0008;
+ pub const SO_DONTROUTE: c_int = 0x0010;
pub const SO_BROADCAST: c_int = 0x0020;
- pub const SO_REUSEADDR: c_int = 0x0004;
+ pub const SO_USELOOPBACK: c_int = 0x0040;
+ pub const SO_LINGER: c_int = 0x0080;
+ pub const SO_OOBINLINE: c_int = 0x0100;
+ pub const SO_REUSEPORT: c_int = 0x0200;
+ pub const SO_SNDBUF: c_int = 0x1001;
+ pub const SO_RCVBUF: c_int = 0x1002;
+ pub const SO_SNDLOWAT: c_int = 0x1003;
+ pub const SO_RCVLOWAT: c_int = 0x1004;
+ pub const SO_SNDTIMEO: c_int = 0x1005;
+ pub const SO_RCVTIMEO: c_int = 0x1006;
pub const SO_ERROR: c_int = 0x1007;
+ pub const SO_TYPE: c_int = 0x1008;
pub const IFF_LOOPBACK: c_int = 0x8;
pub const S_IXUSR : mode_t = 64;
pub const S_IWUSR : mode_t = 128;
pub const S_IRUSR : mode_t = 256;
+ pub const S_IRWXG : mode_t = 56;
+ pub const S_IXGRP : mode_t = 8;
+ pub const S_IWGRP : mode_t = 16;
+ pub const S_IRGRP : mode_t = 32;
+ pub const S_IRWXO : mode_t = 7;
+ pub const S_IXOTH : mode_t = 1;
+ pub const S_IWOTH : mode_t = 2;
+ pub const S_IROTH : mode_t = 4;
pub const F_OK : c_int = 0;
pub const R_OK : c_int = 4;
pub const W_OK : c_int = 2;
pub const TCP_NODELAY: c_int = 0x01;
pub const SOL_SOCKET: c_int = 0xffff;
+ pub const SO_DEBUG: c_int = 0x01;
+ pub const SO_ACCEPTCONN: c_int = 0x0002;
+ pub const SO_REUSEADDR: c_int = 0x0004;
pub const SO_KEEPALIVE: c_int = 0x0008;
+ pub const SO_DONTROUTE: c_int = 0x0010;
pub const SO_BROADCAST: c_int = 0x0020;
- pub const SO_REUSEADDR: c_int = 0x0004;
+ pub const SO_USELOOPBACK: c_int = 0x0040;
+ pub const SO_LINGER: c_int = 0x0080;
+ pub const SO_OOBINLINE: c_int = 0x0100;
+ pub const SO_REUSEPORT: c_int = 0x0200;
+ pub const SO_SNDBUF: c_int = 0x1001;
+ pub const SO_RCVBUF: c_int = 0x1002;
+ pub const SO_SNDLOWAT: c_int = 0x1003;
+ pub const SO_RCVLOWAT: c_int = 0x1004;
+ pub const SO_SNDTIMEO: c_int = 0x1005;
+ pub const SO_RCVTIMEO: c_int = 0x1006;
pub const SO_ERROR: c_int = 0x1007;
+ pub const SO_TYPE: c_int = 0x1008;
pub const IFF_LOOPBACK: c_int = 0x8;
pub const S_IXUSR : mode_t = 64;
pub const S_IWUSR : mode_t = 128;
pub const S_IRUSR : mode_t = 256;
+ pub const S_IRWXG : mode_t = 56;
+ pub const S_IXGRP : mode_t = 8;
+ pub const S_IWGRP : mode_t = 16;
+ pub const S_IRGRP : mode_t = 32;
+ pub const S_IRWXO : mode_t = 7;
+ pub const S_IXOTH : mode_t = 1;
+ pub const S_IWOTH : mode_t = 2;
+ pub const S_IROTH : mode_t = 4;
pub const F_OK : c_int = 0;
pub const R_OK : c_int = 4;
pub const W_OK : c_int = 2;
pub const TCP_NODELAY: c_int = 0x01;
pub const TCP_KEEPALIVE: c_int = 0x10;
pub const SOL_SOCKET: c_int = 0xffff;
+
+ pub const SO_DEBUG: c_int = 0x01;
+ pub const SO_ACCEPTCONN: c_int = 0x0002;
+ pub const SO_REUSEADDR: c_int = 0x0004;
pub const SO_KEEPALIVE: c_int = 0x0008;
+ pub const SO_DONTROUTE: c_int = 0x0010;
pub const SO_BROADCAST: c_int = 0x0020;
- pub const SO_REUSEADDR: c_int = 0x0004;
+ pub const SO_USELOOPBACK: c_int = 0x0040;
+ pub const SO_LINGER: c_int = 0x0080;
+ pub const SO_OOBINLINE: c_int = 0x0100;
+ pub const SO_REUSEPORT: c_int = 0x0200;
+ pub const SO_SNDBUF: c_int = 0x1001;
+ pub const SO_RCVBUF: c_int = 0x1002;
+ pub const SO_SNDLOWAT: c_int = 0x1003;
+ pub const SO_RCVLOWAT: c_int = 0x1004;
+ pub const SO_SNDTIMEO: c_int = 0x1005;
+ pub const SO_RCVTIMEO: c_int = 0x1006;
pub const SO_ERROR: c_int = 0x1007;
+ pub const SO_TYPE: c_int = 0x1008;
pub const IFF_LOOPBACK: c_int = 0x8;
pub const MAP_STACK : c_int = 0;
pub const IPPROTO_RAW : c_int = 255;
+
+ pub const SO_NREAD: c_int = 0x1020;
+ pub const SO_NKE: c_int = 0x1021;
+ pub const SO_NOSIGPIPE: c_int = 0x1022;
+ pub const SO_NOADDRERR: c_int = 0x1023;
+ pub const SO_NWRITE: c_int = 0x1024;
+ pub const SO_DONTTRUNC: c_int = 0x2000;
+ pub const SO_WANTMORE: c_int = 0x4000;
+ pub const SO_WANTOOBFLAG: c_int = 0x8000;
}
pub mod sysconf {
use types::os::arch::c95::c_int;
///
/// # Examples
///
- /// ```no_run
+ /// ```no_run,ignore
/// extern crate libc;
///
/// fn main() {
// Completely remove the local logger from TLS in case anyone attempts to
// frob the slot while we're doing the logging. This will destroy any logger
// set during logging.
- let mut logger = LOCAL_LOGGER.with(|s| {
+ let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| {
s.borrow_mut().take()
}).unwrap_or_else(|| {
- box DefaultLogger { handle: io::stderr() } as Box<Logger + Send>
+ box DefaultLogger { handle: io::stderr() }
});
logger.log(&LogRecord {
level: LogLevel(level),
DIRECTIVES = boxed::into_raw(box directives);
// Schedule the cleanup for the globals for when the runtime exits.
- rt::at_exit(move || {
+ let _ = rt::at_exit(move || {
let _g = LOCK.lock();
assert!(!DIRECTIVES.is_null());
let _directives = Box::from_raw(DIRECTIVES);
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::distributions::{Exp, IndependentSample};
///
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::distributions::{IndependentSample, Gamma};
///
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::distributions::{ChiSquared, IndependentSample};
///
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::distributions::{FisherF, IndependentSample};
///
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::distributions::{StudentT, IndependentSample};
///
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::distributions::{Weighted, WeightedChoice, IndependentSample};
///
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::distributions::{Normal, IndependentSample};
///
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::distributions::{LogNormal, IndependentSample};
///
//! Generating numbers between two others.
+#![allow(trivial_numeric_casts)]
+
// this is surprisingly complicated to be both generic & correct
use core::prelude::{PartialOrd};
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand::distributions::{IndependentSample, Range};
///
/// fn main() {
#[inline]
fn next_u64(&mut self) -> u64 {
+ #![allow(trivial_numeric_casts)]
if self.cnt == 0 {
// make some more numbers
self.isaac64();
#![deprecated(reason = "use the crates.io `rand` library instead",
since = "1.0.0-alpha")]
-#![cfg_attr(test, feature(test, rand))]
+#![cfg_attr(test, feature(test, rand, rustc_private))]
#![allow(deprecated)]
/// # Examples
///
/// ```
+ /// # #![feature(rand, core)]
/// use std::rand::{thread_rng, Rng};
///
/// let mut v = [0; 13579];
/// # Examples
///
/// ```
+ /// # #![feature(rand)]
/// use std::rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// # Examples
///
/// ```
+ /// # #![feature(rand)]
/// use std::rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// # Examples
///
/// ```
+ /// # #![feature(rand)]
/// use std::rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// # Examples
///
/// ```
+ /// # #![feature(rand)]
/// use std::rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// # Examples
///
/// ```
+ /// # #![feature(rand)]
/// use std::rand::{thread_rng, Rng};
///
/// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
/// # Examples
///
/// ```
+ /// # #![feature(rand)]
/// use std::rand::{thread_rng, Rng};
///
/// let choices = [1, 2, 4, 8, 16, 32];
/// # Examples
///
/// ```
+ /// # #![feature(rand, core)]
/// use std::rand::{thread_rng, Rng};
///
/// let mut rng = thread_rng();
/// # Examples
///
/// ```
+ /// # #![feature(rand)]
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// # Examples
///
/// ```
+ /// # #![feature(rand)]
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand::{random, Open01};
///
/// let Open01(val) = random::<Open01<f32>>();
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand::{random, Closed01};
///
/// let Closed01(val) = random::<Closed01<f32>>();
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand::{Rng, SeedableRng, StdRng};
/// use std::rand::reseeding::{Reseeder, ReseedingRng};
///
let (shift, mask) = SHIFT_MASK_TABLE[i];
Ok(Res {
val: ((val >> shift) & mask) as uint,
- next: start + (((32 - shift) >> 3) as uint)
+ next: start + ((32 - shift) >> 3),
})
}
}
0 => doc_as_u8(r_doc) as u64,
1 => doc_as_u16(r_doc) as u64,
2 => doc_as_u32(r_doc) as u64,
- 3 => doc_as_u64(r_doc) as u64,
+ 3 => doc_as_u64(r_doc),
_ => unreachable!(),
}
} else {
#![feature(path_ext)]
#![feature(str_words)]
#![feature(str_char)]
+#![feature(convert)]
+#![feature(into_cow)]
#![cfg_attr(test, feature(test))]
+#![allow(trivial_casts)]
+#![allow(trivial_numeric_casts)]
+
extern crate arena;
extern crate flate;
extern crate fmt_macros;
"detects transmutes of fat pointers"
}
+declare_lint! {
+ pub TRIVIAL_CASTS,
+ Warn,
+ "detects trivial casts which could be removed"
+}
+
+declare_lint! {
+ pub TRIVIAL_NUMERIC_CASTS,
+ Warn,
+ "detects trivial casts of numeric types which could be removed"
+}
/// Does nothing as a lint pass, but registers some `Lint`s
/// which are used by other parts of the compiler.
#[derive(Copy)]
STABLE_FEATURES,
UNKNOWN_CRATE_TYPES,
VARIANT_SIZE_DIFFERENCES,
- FAT_PTR_TRANSMUTES
+ FAT_PTR_TRANSMUTES,
+ TRIVIAL_CASTS,
+ TRIVIAL_NUMERIC_CASTS
)
}
}
fn maybe_stage_features(&mut self, sess: &Session) {
let lvl = match sess.opts.unstable_features {
UnstableFeatures::Default => return,
- UnstableFeatures::Disallow => Warn,
+ UnstableFeatures::Disallow => Forbid,
UnstableFeatures::Cheat => Allow
};
match self.by_name.get("unstable_features") {
}
pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> {
- (*self.metas.borrow())[cnum].clone()
+ self.metas.borrow().get(&cnum).unwrap().clone()
}
pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh {
impl MetadataBlob {
pub fn as_slice<'a>(&'a self) -> &'a [u8] {
let slice = match *self {
- MetadataVec(ref vec) => vec.as_slice(),
+ MetadataVec(ref vec) => &vec[..],
MetadataArchive(ref ar) => ar.as_slice(),
};
if slice.len() < 4 {
match ecx.tcx.inherent_impls.borrow().get(&exp.def_id) {
Some(implementations) => {
for base_impl_did in &**implementations {
- for &method_did in &*(*impl_items)[*base_impl_did] {
+ for &method_did in impl_items.get(base_impl_did).unwrap() {
let impl_item = ty::impl_or_trait_item(
ecx.tcx,
method_did.def_id());
// We need to encode information about the default methods we
// have inherited, so we drive this based on the impl structure.
let impl_items = tcx.impl_items.borrow();
- let items = &(*impl_items)[def_id];
+ let items = impl_items.get(&def_id).unwrap();
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for ImplVisitor<'a, 'b, 'c, 'tcx> {
fn visit_item(&mut self, item: &ast::Item) {
if let ast::ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node {
- let def_id = self.ecx.tcx.def_map.borrow()[trait_ref.ref_id].def_id();
+ let def_id = self.ecx.tcx.def_map.borrow().get(&trait_ref.ref_id).unwrap().def_id();
// Load eagerly if this is an implementation of the Drop trait
// or if the trait is not defined in this crate.
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<PathBuf> {
- let mut p = PathBuf::new(self.sysroot);
+ let mut p = PathBuf::from(self.sysroot);
p.push(&find_libdir(self.sysroot));
p.push(&rustlibdir());
p.push(&self.triple);
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
- let mut p = PathBuf::new(&find_libdir(sysroot));
+ let mut p = PathBuf::from(&find_libdir(sysroot));
assert!(p.is_relative());
p.push(&rustlibdir());
p.push(target_triple);
Some(env_path) => {
let env_path_components =
env_path.split(PATH_ENTRY_SEPARATOR);
- env_path_components.map(|s| PathBuf::new(s)).collect()
+ env_path_components.map(|s| PathBuf::from(s)).collect()
}
None => Vec::new()
};
let mut rlibs = HashMap::new();
let mut dylibs = HashMap::new();
{
- let locs = locs.iter().map(|l| PathBuf::new(&l[..])).filter(|loc| {
+ let locs = locs.iter().map(|l| PathBuf::from(l)).filter(|loc| {
if !loc.exists() {
sess.err(&format!("extern location for {} does not exist: {}",
self.crate_name, loc.display()));
var_id: var_id,
closure_expr_id: id
};
- let upvar_capture = tcx.upvar_capture_map.borrow()[upvar_id].clone();
+ let upvar_capture = tcx.upvar_capture_map.borrow().get(&upvar_id).unwrap().clone();
var_id.encode(rbml_w);
upvar_capture.encode(rbml_w);
})
}
ast::PatEnum(_, ref args) => {
- let def = cx.tcx.def_map.borrow()[pat_id].full_def();
+ let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
match def {
DefConst(..) =>
cx.tcx.sess.span_bug(pat_span, "const pattern should've \
ast::PatStruct(_, ref pattern_fields, _) => {
// Is this a struct or an enum variant?
- let def = cx.tcx.def_map.borrow()[pat_id].full_def();
+ let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
let class_id = match def {
DefConst(..) =>
cx.tcx.sess.span_bug(pat_span, "const pattern should've \
ast::PatTup(exprs.iter().map(|expr| const_expr_to_pat(tcx, &**expr, span)).collect()),
ast::ExprCall(ref callee, ref args) => {
- let def = tcx.def_map.borrow()[callee.id];
+ let def = *tcx.def_map.borrow().get(&callee.id).unwrap();
if let Vacant(entry) = tcx.def_map.borrow_mut().entry(expr.id) {
entry.insert(def);
}
fn handle_field_pattern_match(&mut self, lhs: &ast::Pat,
pats: &[codemap::Spanned<ast::FieldPat>]) {
- let id = match self.tcx.def_map.borrow()[lhs.id].full_def() {
+ let id = match self.tcx.def_map.borrow().get(&lhs.id).unwrap().full_def() {
def::DefVariant(_, id, _) => id,
_ => {
match ty::ty_to_def_id(ty::node_id_to_type(self.tcx,
None => (),
Some(impl_list) => {
for impl_did in &**impl_list {
- for item_did in &(*impl_items)[*impl_did] {
+ for item_did in &*impl_items.get(impl_did).unwrap() {
if self.live_symbols.contains(&item_did.def_id()
.node) {
return true;
match expr.node {
ast::ExprMethodCall(_, _, _) => {
let method_call = MethodCall::expr(expr.id);
- let base_type = (*self.tcx.method_map.borrow())[method_call].ty;
+ let base_type = self.tcx.method_map.borrow().get(&method_call).unwrap().ty;
debug!("effect: method call case, base type is {}",
ppaux::ty_to_string(self.tcx, base_type));
if type_is_unsafe_function(base_type) {
if !self.walk_overloaded_operator(expr,
&**lhs,
vec![&**rhs],
- PassArgs::ByRef) {
+ PassArgs::ByValue) {
self.select_from_expr(&**lhs);
self.consume_expr(&**rhs);
}
// Each match binding is effectively an assignment to the
// binding being produced.
- let def = def_map.borrow()[pat.id].full_def();
+ let def = def_map.borrow().get(&pat.id).unwrap().full_def();
match mc.cat_def(pat.id, pat.span, pat_ty, def) {
Ok(binding_cmt) => {
delegate.mutate(pat.id, pat.span, binding_cmt, Init);
(&ty::ty_rptr(a_r, ref a_mt), &ty::ty_rptr(b_r, ref b_mt)) => {
let r = try!(this.regions_with_variance(ty::Contravariant, *a_r, *b_r));
-
- // FIXME(14985) If we have mutable references to trait objects, we
- // used to use covariant subtyping. I have preserved this behaviour,
- // even though it is probably incorrect. So don't go down the usual
- // path which would require invariance.
- let mt = match (&a_mt.ty.sty, &b_mt.ty.sty) {
- (&ty::ty_trait(..), &ty::ty_trait(..)) if a_mt.mutbl == b_mt.mutbl => {
- let ty = try!(this.tys(a_mt.ty, b_mt.ty));
- ty::mt { ty: ty, mutbl: a_mt.mutbl }
- }
- _ => try!(this.mts(a_mt, b_mt))
- };
+ let mt = try!(this.mts(a_mt, b_mt));
Ok(ty::mk_rptr(tcx, tcx.mk_region(r), mt))
}
ConstrainVarSubReg(_, region) => {
state.result.push(RegionAndOrigin {
region: region,
- origin: this.constraints.borrow()[edge.data].clone()
+ origin: this.constraints.borrow().get(&edge.data).unwrap().clone()
});
}
}
match expr.node {
// live nodes required for uses or definitions of variables:
ast::ExprPath(..) => {
- let def = ir.tcx.def_map.borrow()[expr.id].full_def();
+ let def = ir.tcx.def_map.borrow().get(&expr.id).unwrap().full_def();
debug!("expr {}: path that leads to {:?}", expr.id, def);
if let DefLocal(..) = def {
ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
-> LiveNode {
- match self.ir.tcx.def_map.borrow()[expr.id].full_def() {
+ match self.ir.tcx.def_map.borrow().get(&expr.id).unwrap().full_def() {
DefLocal(nid) => {
let ln = self.live_node(expr.id, expr.span);
if acc != 0 {
fn check_lvalue(&mut self, expr: &Expr) {
match expr.node {
ast::ExprPath(..) => {
- if let DefLocal(nid) = self.ir.tcx.def_map.borrow()[expr.id].full_def() {
+ if let DefLocal(nid) = self.ir.tcx.def_map.borrow().get(&expr.id)
+ .unwrap()
+ .full_def() {
// Assignment to an immutable variable or argument: only legal
// if there is no later assignment. If this local is actually
// mutable, then check for a reassignment to flag the mutability
}
ast::ExprPath(..) => {
- let def = self.tcx().def_map.borrow()[expr.id].full_def();
+ let def = self.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
self.cat_def(expr.id, expr.span, expr_ty, def)
}
contains_bindings
}
+/// Checks if the pattern contains any `ref` or `ref mut` bindings.
+pub fn pat_contains_ref_binding(dm: &DefMap, pat: &ast::Pat) -> bool {
+ let mut result = false;
+ pat_bindings(dm, pat, |mode, _, _, _| {
+ match mode {
+ ast::BindingMode::BindByRef(_) => { result = true; }
+ ast::BindingMode::BindByValue(_) => { }
+ }
+ });
+ result
+}
+
+/// Checks if the patterns for this arm contain any `ref` or `ref mut`
+/// bindings.
+pub fn arm_contains_ref_binding(dm: &DefMap, arm: &ast::Arm) -> bool {
+ arm.pats.iter().any(|pat| pat_contains_ref_binding(dm, pat))
+}
+
/// Checks if the pattern contains any patterns that bind something to
/// an ident or wildcard, e.g. `foo`, or `Foo(_)`, `foo @ Bar(..)`,
pub fn pat_contains_bindings_or_wild(dm: &DefMap, pat: &ast::Pat) -> bool {
}
ast::ExprMethodCall(..) => {
let method_call = ty::MethodCall::expr(expr.id);
- match (*self.tcx.method_map.borrow())[method_call].origin {
+ match (*self.tcx.method_map.borrow()).get(&method_call).unwrap().origin {
ty::MethodStatic(def_id) => {
if is_local(def_id) {
if self.def_id_represents_local_inlined_item(def_id) {
use syntax::ast_util::is_local;
use syntax::attr::{Stability, AttrMetaMethods};
use syntax::visit::{FnKind, Visitor};
-use syntax::feature_gate::emit_feature_warn;
+use syntax::feature_gate::emit_feature_err;
use util::nodemap::{NodeMap, DefIdMap, FnvHashSet, FnvHashMap};
use util::ppaux::Repr;
None => format!("use of unstable library feature '{}'", &feature)
};
- emit_feature_warn(&self.tcx.sess.parse_sess.span_diagnostic,
+ emit_feature_err(&self.tcx.sess.parse_sess.span_diagnostic,
&feature, span, &msg);
}
}
// individually as it's possible to have a stable trait with unstable
// items.
ast::ItemImpl(_, _, _, Some(ref t), _, ref impl_items) => {
- let trait_did = tcx.def_map.borrow()[t.ref_id].def_id();
+ let trait_did = tcx.def_map.borrow().get(&t.ref_id).unwrap().def_id();
let trait_items = ty::trait_items(tcx, trait_did);
for impl_item in impl_items {
FulfillmentError,
FulfillmentErrorCode,
MismatchedProjectionTypes,
+ Obligation,
ObligationCauseCode,
OutputTypeParameterMismatch,
PredicateObligation,
use fmt_macros::{Parser, Piece, Position};
use middle::infer::InferCtxt;
use middle::ty::{self, AsPredicate, ReferencesError, ToPolyTraitRef, TraitRef};
+use middle::ty_fold::TypeFoldable;
use std::collections::HashMap;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::attr::{AttributeMethods, AttrMetaMethods};
report
}
+/// Reports that an overflow has occurred and halts compilation. We
+/// halt compilation unconditionally because it is important that
+/// overflows never be masked -- they basically represent computations
+/// whose result could not be truly determined and thus we can't say
+/// if the program type checks or not -- and they are unusual
+/// occurrences in any case.
+pub fn report_overflow_error<'a, 'tcx, T>(infcx: &InferCtxt<'a, 'tcx>,
+ obligation: &Obligation<'tcx, T>)
+ -> !
+ where T: UserString<'tcx> + TypeFoldable<'tcx>
+{
+ let predicate =
+ infcx.resolve_type_vars_if_possible(&obligation.predicate);
+ span_err!(infcx.tcx.sess, obligation.cause.span, E0275,
+ "overflow evaluating the requirement `{}`",
+ predicate.user_string(infcx.tcx));
+
+ suggest_new_overflow_limit(infcx.tcx, obligation.cause.span);
+
+ note_obligation_cause(infcx, obligation);
+
+ infcx.tcx.sess.abort_if_errors();
+ unreachable!();
+}
+
pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
obligation: &PredicateObligation<'tcx>,
error: &SelectionError<'tcx>)
{
match *error {
- SelectionError::Overflow => {
- // We could track the stack here more precisely if we wanted, I imagine.
- let predicate =
- infcx.resolve_type_vars_if_possible(&obligation.predicate);
- span_err!(infcx.tcx.sess, obligation.cause.span, E0275,
- "overflow evaluating the requirement `{}`",
- predicate.user_string(infcx.tcx));
-
- suggest_new_overflow_limit(infcx.tcx, obligation.cause.span);
-
- note_obligation_cause(infcx, obligation);
- }
-
SelectionError::Unimplemented => {
match &obligation.cause.code {
&ObligationCauseCode::CompareImplMethodObligation => {
}
}
-fn note_obligation_cause<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
- obligation: &PredicateObligation<'tcx>)
+fn note_obligation_cause<'a, 'tcx, T>(infcx: &InferCtxt<'a, 'tcx>,
+ obligation: &Obligation<'tcx, T>)
+ where T: UserString<'tcx>
{
note_obligation_cause_code(infcx,
&obligation.predicate,
&obligation.cause.code);
}
-fn note_obligation_cause_code<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
- predicate: &ty::Predicate<'tcx>,
- cause_span: Span,
- cause_code: &ObligationCauseCode<'tcx>)
+fn note_obligation_cause_code<'a, 'tcx, T>(infcx: &InferCtxt<'a, 'tcx>,
+ predicate: &T,
+ cause_span: Span,
+ cause_code: &ObligationCauseCode<'tcx>)
+ where T: UserString<'tcx>
{
let tcx = infcx.tcx;
match *cause_code {
use std::rc::Rc;
use syntax::ast;
use syntax::codemap::{Span, DUMMY_SP};
-use util::ppaux::{Repr, UserString};
+use util::ppaux::Repr;
pub use self::error_reporting::report_fulfillment_errors;
+pub use self::error_reporting::report_overflow_error;
pub use self::error_reporting::suggest_new_overflow_limit;
pub use self::coherence::orphan_check;
pub use self::coherence::overlapping_impls;
#[derive(Clone,Debug)]
pub enum SelectionError<'tcx> {
Unimplemented,
- Overflow,
OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
ty::PolyTraitRef<'tcx>,
ty::type_err<'tcx>),
let result = match fulfill_cx.select_all_or_error(infcx, typer) {
Ok(()) => Ok(Some(())), // Success, we know it implements Copy.
Err(errors) => {
- // Check if overflow occurred anywhere and propagate that.
- if errors.iter().any(
- |err| match err.code { CodeSelectionError(Overflow) => true, _ => false })
- {
- return Err(Overflow);
- }
-
- // Otherwise, if there were any hard errors, propagate an
- // arbitrary one of those. If no hard errors at all,
- // report ambiguity.
+ // If there were any hard errors, propagate an arbitrary
+ // one of those. If no hard errors at all, report
+ // ambiguity.
let sel_error =
errors.iter()
.filter_map(|err| {
// soldering on, so just treat this like not implemented
false
}
- Err(Overflow) => {
- span_err!(infcx.tcx.sess, span, E0285,
- "overflow evaluating whether `{}` is `{}`",
- ty.user_string(infcx.tcx),
- bound.user_string(infcx.tcx));
- suggest_new_overflow_limit(infcx.tcx, span);
- false
- }
Err(_) => {
- // other errors: not implemented.
+ // errors: not implemented.
false
}
}
{
FulfillmentError { obligation: obligation, code: code }
}
-
- pub fn is_overflow(&self) -> bool {
- match self.code {
- CodeAmbiguity => false,
- CodeSelectionError(Overflow) => true,
- CodeSelectionError(_) => false,
- CodeProjectionError(_) => false,
- }
- }
}
impl<'tcx> TraitObligation<'tcx> {
//! Code for projecting associated types out of trait references.
use super::elaborate_predicates;
+use super::report_overflow_error;
use super::Obligation;
use super::ObligationCause;
-use super::Overflow;
use super::PredicateObligation;
use super::SelectionContext;
use super::SelectionError;
let recursion_limit = selcx.tcx().sess.recursion_limit.get();
if obligation.recursion_depth >= recursion_limit {
debug!("project: overflow!");
- return Err(ProjectionTyError::TraitSelectionError(Overflow));
+ report_overflow_error(selcx.infcx(), &obligation);
}
let obligation_trait_ref =
obligation.repr(tcx),
fn_sig.repr(tcx));
+ // the `Output` associated type is declared on `FnOnce`
+ let fn_once_def_id = tcx.lang_items.fn_once_trait().unwrap();
+
// Note: we unwrap the binder here but re-create it below (1)
let ty::Binder((trait_ref, ret_type)) =
util::closure_trait_ref_and_return_type(tcx,
- obligation.predicate.trait_ref.def_id,
+ fn_once_def_id,
obligation.predicate.trait_ref.self_ty(),
fn_sig,
flag);
let impl_items_map = selcx.tcx().impl_items.borrow();
let impl_or_trait_items_map = selcx.tcx().impl_or_trait_items.borrow();
- let impl_items = &impl_items_map[impl_vtable.impl_def_id];
+ let impl_items = impl_items_map.get(&impl_vtable.impl_def_id).unwrap();
let mut impl_ty = None;
for impl_item in impl_items {
- let assoc_type = match impl_or_trait_items_map[impl_item.def_id()] {
+ let assoc_type = match *impl_or_trait_items_map.get(&impl_item.def_id()).unwrap() {
ty::TypeTraitItem(ref assoc_type) => assoc_type.clone(),
ty::MethodTraitItem(..) => { continue; }
};
use super::project;
use super::project::{normalize_with_depth, Normalized};
use super::{PredicateObligation, TraitObligation, ObligationCause};
+use super::{report_overflow_error};
use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
-use super::{SelectionError, Unimplemented, Overflow, OutputTypeParameterMismatch};
+use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch};
use super::{Selection};
use super::{SelectionResult};
use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure,
// not update) the cache.
let recursion_limit = self.infcx.tcx.sess.recursion_limit.get();
if stack.obligation.recursion_depth >= recursion_limit {
- debug!("{} --> overflow (limit={})",
- stack.obligation.repr(self.tcx()),
- recursion_limit);
- return Err(Overflow)
+ report_overflow_error(self.infcx(), &stack.obligation);
}
// Check the cache. Note that we skolemize the trait-ref
match self.closure_typer.closure_kind(closure_def_id) {
Some(closure_kind) => {
debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
- if closure_kind == kind {
+ if closure_kind.extends(kind) {
candidates.vec.push(ClosureCandidate(closure_def_id, substs.clone()));
}
}
candidates: &mut SelectionCandidateSet<'tcx>)
-> Result<(),SelectionError<'tcx>>
{
- // We provide a `Fn` impl for fn pointers. There is no need to provide
- // the other traits (e.g. `FnMut`) since those are provided by blanket
- // impls.
- if Some(obligation.predicate.def_id()) != self.tcx().lang_items.fn_trait() {
+ // We provide impl of all fn traits for fn pointers.
+ if self.tcx().lang_items.fn_trait_kind(obligation.predicate.def_id()).is_none() {
return Ok(());
}
match obligations {
Ok(mut obls) => {
- obls.push_all(normalized.obligations.as_slice());
+ obls.push_all(&normalized.obligations);
obls
},
Err(ErrorReported) => Vec::new()
impl<'tcx> EvaluationResult<'tcx> {
fn may_apply(&self) -> bool {
match *self {
- EvaluatedToOk
- | EvaluatedToAmbig
- | EvaluatedToErr(Overflow)
- | EvaluatedToErr(OutputTypeParameterMismatch(..)) => true,
- EvaluatedToErr(Unimplemented) => false,
+ EvaluatedToOk |
+ EvaluatedToAmbig |
+ EvaluatedToErr(OutputTypeParameterMismatch(..)) =>
+ true,
+
+ EvaluatedToErr(Unimplemented) =>
+ false,
}
}
}
impl<'tcx> Repr<'tcx> for super::SelectionError<'tcx> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
match *self {
- super::Overflow =>
- format!("Overflow"),
-
super::Unimplemented =>
format!("Unimplemented"),
use middle::region;
use middle::resolve_lifetime;
use middle::infer;
+use middle::pat_util;
use middle::stability;
use middle::subst::{self, ParamSpace, Subst, Substs, VecPerParamSpace};
use middle::traits;
impl<'tcx> Hash for TyS<'tcx> {
fn hash<H: Hasher>(&self, s: &mut H) {
- (self as *const _).hash(s)
+ (self as *const TyS).hash(s)
}
}
pub substs: Substs<'tcx>,
}
-#[derive(Clone, Copy, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
+#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
pub enum ClosureKind {
+ // Warning: Ordering is significant here! The ordering is chosen
+ // because the trait Fn is a subtrait of FnMut and so in turn, and
+ // hence we order it so that Fn < FnMut < FnOnce.
FnClosureKind,
FnMutClosureKind,
FnOnceClosureKind,
Err(err) => cx.sess.fatal(&err[..]),
}
}
+
+ /// True if this a type that impls this closure kind
+ /// must also implement `other`.
+ pub fn extends(self, other: ty::ClosureKind) -> bool {
+ match (self, other) {
+ (FnClosureKind, FnClosureKind) => true,
+ (FnClosureKind, FnMutClosureKind) => true,
+ (FnClosureKind, FnOnceClosureKind) => true,
+ (FnMutClosureKind, FnMutClosureKind) => true,
+ (FnMutClosureKind, FnOnceClosureKind) => true,
+ (FnOnceClosureKind, FnOnceClosureKind) => true,
+ _ => false,
+ }
+ }
}
pub trait ClosureTyper<'tcx> {
}
pub fn closure_kind(&self, def_id: ast::DefId) -> ty::ClosureKind {
- self.closure_kinds.borrow()[def_id]
+ *self.closure_kinds.borrow().get(&def_id).unwrap()
}
pub fn closure_type(&self,
substs: &subst::Substs<'tcx>)
-> ty::ClosureTy<'tcx>
{
- self.closure_tys.borrow()[def_id].subst(self, substs)
+ self.closure_tys.borrow().get(&def_id).unwrap().subst(self, substs)
}
pub fn type_parameter_def(&self,
node_id: ast::NodeId)
-> TypeParameterDef<'tcx>
{
- self.ty_param_defs.borrow()[node_id].clone()
+ self.ty_param_defs.borrow().get(&node_id).unwrap().clone()
+ }
+
+ pub fn pat_contains_ref_binding(&self, pat: &ast::Pat) -> bool {
+ pat_util::pat_contains_ref_binding(&self.def_map, pat)
+ }
+
+ pub fn arm_contains_ref_binding(&self, arm: &ast::Arm) -> bool {
+ pat_util::arm_contains_ref_binding(&self.def_map, arm)
}
}
};
debug!("Interned type: {:?} Pointer: {:?}",
- ty, ty as *const _);
+ ty, ty as *const TyS);
interner.insert(InternedTy { ty: ty }, ty);
RvalueDpsExpr
}
- ast::ExprCast(..) => {
- match tcx.node_types.borrow().get(&expr.id) {
- Some(&ty) => {
- if type_is_trait(ty) {
- RvalueDpsExpr
- } else {
- RvalueDatumExpr
- }
- }
- None => {
- // Technically, it should not happen that the expr is not
- // present within the table. However, it DOES happen
- // during type check, because the final types from the
- // expressions are not yet recorded in the tcx. At that
- // time, though, we are only interested in knowing lvalue
- // vs rvalue. It would be better to base this decision on
- // the AST type in cast node---but (at the time of this
- // writing) it's not easy to distinguish casts to traits
- // from other casts based on the AST. This should be
- // easier in the future, when casts to traits
- // would like @Foo, Box<Foo>, or &Foo.
- RvalueDatumExpr
- }
- }
- }
-
ast::ExprBreak(..) |
ast::ExprAgain(..) |
ast::ExprRet(..) |
ast::ExprUnary(..) |
ast::ExprBox(None, _) |
ast::ExprAddrOf(..) |
- ast::ExprBinary(..) => {
+ ast::ExprBinary(..) |
+ ast::ExprCast(..) => {
RvalueDatumExpr
}
pub fn trait_has_default_impl(tcx: &ctxt, trait_def_id: DefId) -> bool {
populate_implementations_for_trait_if_necessary(tcx, trait_def_id);
- match tcx.lang_items.to_builtin_kind(trait_def_id) {
- Some(BoundSend) | Some(BoundSync) => true,
- _ => tcx.traits_with_default_impls.borrow().contains_key(&trait_def_id),
- }
+ tcx.traits_with_default_impls.borrow().contains_key(&trait_def_id)
}
/// Records a trait-to-implementation mapping.
}
pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
- Some(self.upvar_capture_map.borrow()[upvar_id].clone())
+ Some(self.upvar_capture_map.borrow().get(&upvar_id).unwrap().clone())
}
}
let cg = build_codegen_options(matches);
- let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::new(&m));
+ let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
let target = matches.opt_str("target").unwrap_or(
host_triple().to_string());
let opt_level = {
if path.is_empty() {
early_error("empty search path given via `-L`");
}
- self.paths.push((kind, PathBuf::new(path)));
+ self.paths.push((kind, PathBuf::from(path)));
}
pub fn iter(&self, kind: PathKind) -> Iter {
};
let new_filename = self.work_dir.path().join(&filename[..]);
try!(fs::rename(&file, &new_filename));
- self.members.push(PathBuf::new(&filename));
+ self.members.push(PathBuf::from(filename));
}
Ok(())
}
pub fn realpath(original: &Path) -> io::Result<PathBuf> {
let old = old_path::Path::new(original.to_str().unwrap());
match old_realpath(&old) {
- Ok(p) => Ok(PathBuf::new(p.as_str().unwrap())),
+ Ok(p) => Ok(PathBuf::from(p.as_str().unwrap())),
Err(e) => Err(io::Error::new(io::ErrorKind::Other,
"realpath error",
Some(e.to_string())))
#![feature(collections)]
#![feature(core)]
#![feature(old_fs)]
-#![feature(hash)]
#![feature(int_uint)]
#![feature(io)]
#![feature(old_io)]
#![feature(rand)]
#![feature(path_ext)]
#![feature(std_misc)]
-#![feature(path_relative_from)]
#![feature(step_by)]
+#![feature(convert)]
+#![cfg_attr(test, feature(test, rand))]
extern crate syntax;
extern crate serialize;
lib.pop();
let mut output = (config.realpath)(&cwd.join(&config.out_filename)).unwrap();
output.pop();
- let relative = relativize(&lib, &output);
+ let relative = path_relative_from(&lib, &output)
+ .expect(&format!("couldn't create relative path from {:?} to {:?}", output, lib));
// FIXME (#9639): This needs to handle non-utf8 paths
format!("{}/{}", prefix,
relative.to_str().expect("non-utf8 component in path"))
}
-fn relativize(path: &Path, rel: &Path) -> PathBuf {
- let mut res = PathBuf::new("");
- let mut cur = rel;
- while !path.starts_with(cur) {
- res.push("..");
- match cur.parent() {
- Some(p) => cur = p,
- None => panic!("can't create relative paths across filesystems"),
+// This routine is adapted from the *old* Path's `path_relative_from`
+// function, which works differently from the new `relative_from` function.
+// In particular, this handles the case on unix where both paths are
+// absolute but with only the root as the common directory.
+fn path_relative_from(path: &Path, base: &Path) -> Option<PathBuf> {
+ use std::path::Component;
+
+ if path.is_absolute() != base.is_absolute() {
+ if path.is_absolute() {
+ Some(PathBuf::from(path))
+ } else {
+ None
}
+ } else {
+ let mut ita = path.components();
+ let mut itb = base.components();
+ let mut comps: Vec<Component> = vec![];
+ loop {
+ match (ita.next(), itb.next()) {
+ (None, None) => break,
+ (Some(a), None) => {
+ comps.push(a);
+ comps.extend(ita.by_ref());
+ break;
+ }
+ (None, _) => comps.push(Component::ParentDir),
+ (Some(a), Some(b)) if comps.is_empty() && a == b => (),
+ (Some(a), Some(b)) if b == Component::CurDir => comps.push(a),
+ (Some(_), Some(b)) if b == Component::ParentDir => return None,
+ (Some(a), Some(_)) => {
+ comps.push(Component::ParentDir);
+ for _ in itb {
+ comps.push(Component::ParentDir);
+ }
+ comps.push(a);
+ comps.extend(ita.by_ref());
+ break;
+ }
+ }
+ }
+ Some(comps.iter().map(|c| c.as_os_str()).collect())
}
- match path.relative_from(cur) {
- Some(s) => { res.push(s); res }
- None => panic!("couldn't create relative path from {:?} to {:?}",
- rel, path),
- }
-
}
+
fn get_install_prefix_rpath(config: &mut RPathConfig) -> String {
let path = (config.get_install_prefix_lib_path)();
let path = env::current_dir().unwrap().join(&path);
used_crates: Vec::new(),
has_rpath: true,
is_like_osx: true,
- out_filename: PathBuf::new("bin/rustc"),
+ out_filename: PathBuf::from("bin/rustc"),
get_install_prefix_lib_path: &mut || panic!(),
realpath: &mut |p| Ok(p.to_path_buf()),
};
} else {
let config = &mut RPathConfig {
used_crates: Vec::new(),
- out_filename: PathBuf::new("bin/rustc"),
+ out_filename: PathBuf::from("bin/rustc"),
get_install_prefix_lib_path: &mut || panic!(),
has_rpath: true,
is_like_osx: false,
let path = {
let mut target = target.to_string();
target.push_str(".json");
- PathBuf::new(&target)
+ PathBuf::from(target)
};
let target_path = env::var_os("RUST_TARGET_PATH")
- .unwrap_or(OsString::from_str(""));
+ .unwrap_or(OsString::new());
// FIXME 16351: add a sane default search path?
#![feature(no_std)]
#![no_std]
#![unstable(feature = "rustc_private")]
+#![cfg_attr(test, feature(hash))]
//! A typesafe bitmask flag generator.
/// # Examples
///
/// ```{.rust}
+/// # #![feature(rustc_private)]
/// #[macro_use] extern crate rustc_bitflags;
///
/// bitflags! {
/// The generated `struct`s can also be extended with type and trait implementations:
///
/// ```{.rust}
+/// # #![feature(rustc_private)]
/// #[macro_use] extern crate rustc_bitflags;
///
/// use std::fmt;
match path.loan_path.kind {
LpVar(..) | LpUpvar(..) | LpDowncast(..) => {
let kill_scope = path.loan_path.kill_scope(tcx);
- let path = self.path_map.borrow()[path.loan_path];
+ let path = *self.path_map.borrow().get(&path.loan_path).unwrap();
self.kill_moves(path, kill_scope.node_id(), dfcx_moves);
}
LpExtend(..) => {}
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(unsafe_destructor)]
+#![feature(into_cow)]
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
// dependent dlls. Note that this uses cfg!(windows) as opposed to
// targ_cfg because syntax extensions are always loaded for the host
// compiler, not for the target.
- let mut _old_path = OsString::from_str("");
+ let mut _old_path = OsString::new();
if cfg!(windows) {
_old_path = env::var_os("PATH").unwrap_or(_old_path);
let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
pub fn phase_6_link_output(sess: &Session,
trans: &trans::CrateTranslation,
outputs: &OutputFilenames) {
- let old_path = env::var_os("PATH").unwrap_or(OsString::from_str(""));
+ let old_path = env::var_os("PATH").unwrap_or(OsString::new());
let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
new_path.extend(env::split_paths(&old_path));
env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
// We want to toss everything after the final '.'
let dirpath = match *odir {
Some(ref d) => d.clone(),
- None => PathBuf::new("")
+ None => PathBuf::new()
};
// If a crate name is present, we use it as the link name
#![feature(io)]
#![feature(set_stdio)]
#![feature(unicode)]
+#![feature(convert)]
extern crate arena;
extern crate flate;
// Extract output directory and file from matches.
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
- let odir = matches.opt_str("out-dir").map(|o| PathBuf::new(&o));
- let ofile = matches.opt_str("o").map(|o| PathBuf::new(&o));
+ let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
+ let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
(odir, ofile)
}
io::stdin().read_to_string(&mut src).unwrap();
Some((Input::Str(src), None))
} else {
- Some((Input::File(PathBuf::new(ifile)), Some(PathBuf::new(ifile))))
+ Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile))))
}
} else {
None
use syntax::diagnostics::registry::Registry;
let all_errors = Vec::new() +
- rustc::diagnostics::DIAGNOSTICS.as_slice() +
- rustc_typeck::diagnostics::DIAGNOSTICS.as_slice() +
- rustc_resolve::diagnostics::DIAGNOSTICS.as_slice();
+ &rustc::diagnostics::DIAGNOSTICS[..] +
+ &rustc_typeck::diagnostics::DIAGNOSTICS[..] +
+ &rustc_resolve::diagnostics::DIAGNOSTICS[..];
Registry::new(&*all_errors)
}
}
}
-declare_lint! {
- UNUSED_TYPECASTS,
- Allow,
- "detects unnecessary type casts that can be removed"
-}
-
-#[derive(Copy)]
-pub struct UnusedCasts;
-
-impl LintPass for UnusedCasts {
- fn get_lints(&self) -> LintArray {
- lint_array!(UNUSED_TYPECASTS)
- }
-
- fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
- if let ast::ExprCast(ref expr, ref ty) = e.node {
- let t_t = ty::expr_ty(cx.tcx, e);
- if ty::expr_ty(cx.tcx, &**expr) == t_t {
- cx.span_lint(UNUSED_TYPECASTS, ty.span, "unnecessary type cast");
- }
- }
- }
-}
-
declare_lint! {
UNSIGNED_NEGATION,
Warn,
impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
fn check_def(&mut self, sp: Span, id: ast::NodeId) {
- match self.cx.tcx.def_map.borrow()[id].full_def() {
+ match self.cx.tcx.def_map.borrow().get(&id).unwrap().full_def() {
def::DefPrimTy(ast::TyInt(ast::TyIs(_))) => {
self.cx.span_lint(IMPROPER_CTYPES, sp,
"found rust type `isize` in foreign module, while \
fn check_fn(&mut self, cx: &Context, fn_kind: visit::FnKind, _: &ast::FnDecl,
blk: &ast::Block, sp: Span, id: ast::NodeId) {
+ // FIXME(#23542) Replace with type ascription.
+ #![allow(trivial_casts)]
+
type F = for<'tcx> fn(&ty::ctxt<'tcx>,
ast::NodeId, ast::NodeId, ast::Ident, ast::NodeId) -> bool;
}
},
ast::ItemStatic(..) => {
- if attr::contains_name(it.attrs.as_slice(), "no_mangle") &&
+ if attr::contains_name(&it.attrs, "no_mangle") &&
!cx.exported_items.contains(&it.id) {
let msg = format!("static {} is marked #[no_mangle], but not exported",
it.ident);
}
},
ast::ItemConst(..) => {
- if attr::contains_name(it.attrs.as_slice(), "no_mangle") {
+ if attr::contains_name(&it.attrs, "no_mangle") {
// Const items do not refer to a particular location in memory, and therefore
// don't have anything to attach a symbol to
let msg = "const items should never be #[no_mangle], consider instead using \
#![feature(rustc_private)]
#![feature(unsafe_destructor)]
#![feature(staged_api)]
-#![feature(std_misc)]
#![feature(str_char)]
#![cfg_attr(test, feature(test))]
pub use rustc::util as util;
use session::Session;
-use lint::{LintPassObject, LintId};
+use lint::LintId;
mod builtin;
macro_rules! add_builtin {
($sess:ident, $($name:ident),*,) => (
{$(
- store.register_pass($sess, false, box builtin::$name as LintPassObject);
+ store.register_pass($sess, false, box builtin::$name);
)*}
)
}
macro_rules! add_builtin_with_new {
($sess:ident, $($name:ident),*,) => (
{$(
- store.register_pass($sess, false, box builtin::$name::new() as LintPassObject);
+ store.register_pass($sess, false, box builtin::$name::new());
)*}
)
}
add_builtin!(sess,
HardwiredLints,
WhileTrue,
- UnusedCasts,
ImproperCTypes,
BoxPointers,
UnusedAttributes,
UNUSED_UNSAFE, PATH_STATEMENTS);
// We have one lint pass defined specially
- store.register_pass(sess, false, box lint::GatherNodeLevels as LintPassObject);
+ store.register_pass(sess, false, box lint::GatherNodeLevels);
// Insert temporary renamings for a one-time deprecation
store.register_renamed("raw_pointer_deriving", "raw_pointer_derive");
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
+#![allow(trivial_casts)]
+#![allow(trivial_numeric_casts)]
#![crate_name = "rustc_llvm"]
#![unstable(feature = "rustc_private")]
ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => {
let public_ty = match ty.node {
ast::TyPath(..) => {
- match self.tcx.def_map.borrow()[ty.id].full_def() {
+ match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
def::DefPrimTy(..) => true,
def => {
let did = def.def_id();
ast::ItemTy(ref ty, _) if public_first => {
if let ast::TyPath(..) = ty.node {
- match self.tcx.def_map.borrow()[ty.id].full_def() {
+ match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() {
def::DefPrimTy(..) | def::DefTyParam(..) => {},
def => {
let did = def.def_id();
// crate module gets processed as well.
if self.prev_exported {
assert!(self.export_map.contains_key(&id), "wut {}", id);
- for export in &self.export_map[id] {
+ for export in self.export_map.get(&id).unwrap() {
if is_local(export.def_id) {
self.reexports.insert(export.def_id.node);
}
// if we've reached the root, then everything was allowable and this
// access is public.
if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
- closest_private_id = self.parents[closest_private_id];
+ closest_private_id = *self.parents.get(&closest_private_id).unwrap();
// If we reached the top, then we were public all the way down and
// we can allow this access.
/// whether the node is accessible by the current module that iteration is
/// inside.
fn private_accessible(&self, id: ast::NodeId) -> bool {
- let parent = self.parents[id];
+ let parent = *self.parents.get(&id).unwrap();
debug!("privacy - accessible parent {}", self.nodestr(parent));
// After finding `did`'s closest private member, we roll ourselves back
_ => {}
}
- cur = self.parents[cur];
+ cur = *self.parents.get(&cur).unwrap();
}
}
ast::TyPath(..) => {}
_ => return Some((err_span, err_msg, None)),
};
- let def = self.tcx.def_map.borrow()[ty.id].full_def();
+ let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def();
let did = def.def_id();
assert!(is_local(did));
match self.tcx.map.get(did.node) {
// Checks that a path is in scope.
fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Ident) {
debug!("privacy - path {}", self.nodestr(path_id));
- let path_res = self.tcx.def_map.borrow()[path_id];
+ let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap();
let ck = |tyname: &str| {
let ck_public = |def: ast::DefId| {
debug!("privacy - ck_public {:?}", def);
}
}
ty::ty_enum(_, _) => {
- match self.tcx.def_map.borrow()[expr.id].full_def() {
+ match self.tcx.def_map.borrow().get(&expr.id).unwrap().full_def() {
def::DefVariant(_, variant_id, _) => {
for field in fields {
self.check_field(expr.span, variant_id,
if t.options.is_like_osx {
let morestack = lib_path.join("libmorestack.a");
- let mut v = OsString::from_str("-Wl,-force_load,");
+ let mut v = OsString::from("-Wl,-force_load,");
v.push(&morestack);
cmd.arg(&v);
} else {
cmd.args(&["-dynamiclib", "-Wl,-dylib"]);
if sess.opts.cg.rpath {
- let mut v = OsString::from_str("-Wl,-install_name,@rpath/");
+ let mut v = OsString::from("-Wl,-install_name,@rpath/");
v.push(out_filename.file_name().unwrap());
cmd.arg(&v);
}
let mut get_install_prefix_lib_path = || {
let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
- let mut path = PathBuf::new(install_prefix);
+ let mut path = PathBuf::from(install_prefix);
path.push(&tlib);
path
&sess.target.target.options.staticlib_suffix,
&search_path[..],
&sess.diagnostic().handler);
- let mut v = OsString::from_str("-Wl,-force_load,");
+ let mut v = OsString::from("-Wl,-force_load,");
v.push(&lib);
cmd.arg(&v);
}
// involves just passing the right -l flag.
let data = if dylib {
- &trans.crate_formats[config::CrateTypeDylib]
+ trans.crate_formats.get(&config::CrateTypeDylib).unwrap()
} else {
- &trans.crate_formats[config::CrateTypeExecutable]
+ trans.crate_formats.get(&config::CrateTypeExecutable).unwrap()
};
// Invoke get_used_crates to ensure that we get a topological sorting of
#![feature(unicode)]
#![feature(path_ext)]
#![feature(fs)]
-#![feature(hash)]
+#![feature(convert)]
#![feature(path_relative_from)]
+#![allow(trivial_casts)]
+#![allow(trivial_numeric_casts)]
+
extern crate arena;
extern crate flate;
extern crate getopts;
self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref",
ref_id));
}
- let def = self.analysis.ty_cx.def_map.borrow()[ref_id].full_def();
+ let def = self.analysis.ty_cx.def_map.borrow().get(&ref_id).unwrap().full_def();
match def {
def::DefPrimTy(_) => None,
_ => Some(def.def_id()),
self.sess.span_bug(span, &format!("def_map has no key for {} in lookup_def_kind",
ref_id));
}
- let def = def_map[ref_id].full_def();
+ let def = def_map.get(&ref_id).unwrap().full_def();
match def {
def::DefMod(_) |
def::DefForeignMod(_) => Some(recorder::ModRef),
self.collecting = false;
let span_utils = self.span.clone();
for &(id, ref p, _, _) in &self.collected_paths {
- let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
- (*self.analysis.ty_cx.node_types.borrow())[id]);
+ let typ =
+ ppaux::ty_to_string(
+ &self.analysis.ty_cx,
+ *self.analysis.ty_cx.node_types.borrow().get(&id).unwrap());
// get the span only for the name of the variable (I hope the path is only ever a
// variable name, but who knows?)
self.fmt.formal_str(p.span,
ast::NamedField(ident, _) => {
let name = get_ident(ident);
let qualname = format!("{}::{}", qualname, name);
- let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
- (*self.analysis.ty_cx.node_types.borrow())[field.node.id]);
+ let typ =
+ ppaux::ty_to_string(
+ &self.analysis.ty_cx,
+ *self.analysis.ty_cx.node_types.borrow().get(&field.node.id).unwrap());
match self.span.sub_span_before_token(field.span, token::Colon) {
Some(sub_span) => self.fmt.field_str(field.span,
Some(sub_span),
self.sess.span_bug(span,
&format!("def_map has no key for {} in visit_expr", id));
}
- let def = def_map[id].full_def();
+ let def = def_map.get(&id).unwrap().full_def();
let sub_span = self.span.span_for_last_ident(span);
match def {
def::DefUpvar(..) |
.ty_cx
.impl_items
.borrow();
- Some((*impl_items)[def_id]
+ Some(impl_items.get(&def_id)
+ .unwrap()
.iter()
.find(|mr| {
ty::impl_or_trait_item(
ex: &ast::Expr,
args: &Vec<P<ast::Expr>>) {
let method_map = self.analysis.ty_cx.method_map.borrow();
- let method_callee = &(*method_map)[ty::MethodCall::expr(ex.id)];
+ let method_callee = method_map.get(&ty::MethodCall::expr(ex.id)).unwrap();
let (def_id, decl_id) = match method_callee.origin {
ty::MethodStatic(def_id) |
ty::MethodStaticClosure(def_id) => {
self.collected_paths.push((p.id, path.clone(), false, recorder::StructRef));
visit::walk_path(self, path);
- let def = self.analysis.ty_cx.def_map.borrow()[p.id].full_def();
+ let def = self.analysis.ty_cx.def_map.borrow().get(&p.id).unwrap().full_def();
let struct_def = match def {
def::DefConst(..) => None,
def::DefVariant(_, variant_id, _) => Some(variant_id),
let glob_map = &self.analysis.glob_map;
let glob_map = glob_map.as_ref().unwrap();
if glob_map.contains_key(&item.id) {
- for n in &glob_map[item.id] {
+ for n in glob_map.get(&item.id).unwrap() {
if name_string.len() > 0 {
name_string.push_str(", ");
}
&format!("def_map has no key for {} in visit_arm",
id));
}
- let def = def_map[id].full_def();
+ let def = def_map.get(&id).unwrap().full_def();
match def {
def::DefLocal(id) => {
let value = if *immut {
for &(id, ref p, ref immut, _) in &self.collected_paths {
let value = if *immut { value.to_string() } else { "<mutable>".to_string() };
let types = self.analysis.ty_cx.node_types.borrow();
- let typ = ppaux::ty_to_string(&self.analysis.ty_cx, (*types)[id]);
+ let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *types.get(&id).unwrap());
// Get the span only for the name of the variable (I hope the path
// is only ever a variable name, but who knows?).
let sub_span = self.span.span_for_last_ident(p.span);
// find a path to dump our data to
let mut root_path = match env::var_os("DXR_RUST_TEMP_FOLDER") {
- Some(val) => PathBuf::new(&val),
+ Some(val) => PathBuf::from(val),
None => match odir {
Some(val) => val.join("dxr"),
- None => PathBuf::new("dxr-temp"),
+ None => PathBuf::from("dxr-temp"),
},
};
None => {
let data = &m[0].data;
for &(ref ident, ref value_ptr) in &m[0].bound_ptrs {
- let binfo = data.bindings_map[*ident];
+ let binfo = *data.bindings_map.get(ident).unwrap();
call_lifetime_start(bcx, binfo.llmatch);
if binfo.trmode == TrByRef && type_is_fat_ptr(bcx.tcx(), binfo.ty) {
expr::copy_fat_ptr(bcx, *value_ptr, binfo.llmatch);
// no failure occurred preparing operands, no need to cleanup
fcx.pop_custom_cleanup_scope(temp_scope);
- let mut constraints = constraints.iter()
- .map(|s| s.to_string())
- .chain(ext_constraints.into_iter())
- .collect::<Vec<String>>()
- .connect(",");
-
- let mut clobbers = ia.clobbers.iter()
- .map(|s| format!("~{{{}}}", &s))
- .collect::<Vec<String>>()
- .connect(",");
- let more_clobbers = get_clobbers();
- if !more_clobbers.is_empty() {
- if !clobbers.is_empty() {
- clobbers.push(',');
- }
- clobbers.push_str(&more_clobbers[..]);
- }
-
- // Add the clobbers to our constraints list
- if clobbers.len() != 0 && constraints.len() != 0 {
- constraints.push(',');
- constraints.push_str(&clobbers[..]);
- } else {
- constraints.push_str(&clobbers[..]);
- }
+ let clobbers = ia.clobbers.iter()
+ .map(|s| format!("~{{{}}}", &s));
+
+ // Default per-arch clobbers
+ // Basically what clang does
+ let arch_clobbers = match &bcx.sess().target.target.arch[..] {
+ "x86" | "x86_64" => vec!("~{dirflag}", "~{fpsr}", "~{flags}"),
+ _ => Vec::new()
+ };
- debug!("Asm Constraints: {}", &constraints[..]);
+ let all_constraints= constraints.iter()
+ .map(|s| s.to_string())
+ .chain(ext_constraints.into_iter())
+ .chain(clobbers)
+ .chain(arch_clobbers.iter()
+ .map(|s| s.to_string()))
+ .collect::<Vec<String>>()
+ .connect(",");
- let num_outputs = outputs.len();
+ debug!("Asm Constraints: {}", &all_constraints[..]);
// Depending on how many outputs we have, the return type is different
- let output_type = if num_outputs == 0 {
- Type::void(bcx.ccx())
- } else if num_outputs == 1 {
- output_types[0]
- } else {
- Type::struct_(bcx.ccx(), &output_types[..], false)
+ let num_outputs = outputs.len();
+ let output_type = match num_outputs {
+ 0 => Type::void(bcx.ccx()),
+ 1 => output_types[0],
+ _ => Type::struct_(bcx.ccx(), &output_types[..], false)
};
let dialect = match ia.dialect {
};
let asm = CString::new(ia.asm.as_bytes()).unwrap();
- let constraints = CString::new(constraints).unwrap();
+ let constraint_cstr = CString::new(all_constraints).unwrap();
let r = InlineAsmCall(bcx,
asm.as_ptr(),
- constraints.as_ptr(),
+ constraint_cstr.as_ptr(),
&inputs,
output_type,
ia.volatile,
}
-// Default per-arch clobbers
-// Basically what clang does
-
-#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
-fn get_clobbers() -> String {
- "".to_string()
-}
-
-#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
-fn get_clobbers() -> String {
- "~{dirflag},~{fpsr},~{flags}".to_string()
-}
}
pub fn kind_for_closure(ccx: &CrateContext, closure_id: ast::DefId) -> ty::ClosureKind {
- ccx.tcx().closure_kinds.borrow()[closure_id]
+ *ccx.tcx().closure_kinds.borrow().get(&closure_id).unwrap()
}
pub fn decl_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
let mut used = true;
match &attr.name()[..] {
"no_stack_check" => unset_split_stack(llfn),
- "no_split_stack" => {
- unset_split_stack(llfn);
- ccx.sess().span_warn(attr.span,
- "no_split_stack is a deprecated synonym for no_stack_check");
- }
"cold" => unsafe {
llvm::LLVMAddFunctionAttribute(llfn,
llvm::FunctionIndex as c_uint,
bcx
}
-fn copy_closure_args_to_allocas<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
- arg_scope: cleanup::CustomScopeIndex,
- args: &[ast::Arg],
- arg_datums: Vec<RvalueDatum<'tcx>>,
- monomorphized_arg_types: &[Ty<'tcx>])
- -> Block<'blk, 'tcx> {
- let _icx = push_ctxt("copy_closure_args_to_allocas");
- let arg_scope_id = cleanup::CustomScope(arg_scope);
-
- assert_eq!(arg_datums.len(), 1);
-
- let arg_datum = arg_datums.into_iter().next().unwrap();
-
- // Untuple the rest of the arguments.
- let tuple_datum =
- unpack_datum!(bcx,
- arg_datum.to_lvalue_datum_in_scope(bcx,
- "argtuple",
- arg_scope_id));
- let untupled_arg_types = match monomorphized_arg_types[0].sty {
- ty::ty_tup(ref types) => &types[..],
- _ => {
- bcx.tcx().sess.span_bug(args[0].pat.span,
- "first arg to `rust-call` ABI function \
- wasn't a tuple?!")
- }
- };
- for j in 0..args.len() {
- let tuple_element_type = untupled_arg_types[j];
- let tuple_element_datum =
- tuple_datum.get_element(bcx,
- tuple_element_type,
- |llval| GEPi(bcx, llval, &[0, j]));
- let tuple_element_datum = tuple_element_datum.to_expr_datum();
- let tuple_element_datum =
- unpack_datum!(bcx,
- tuple_element_datum.to_rvalue_datum(bcx,
- "arg"));
- bcx = _match::store_arg(bcx,
- &*args[j].pat,
- tuple_element_datum,
- arg_scope_id);
-
- debuginfo::create_argument_metadata(bcx, &args[j]);
- }
-
- bcx
-}
-
// Ties up the llstaticallocas -> llloadenv -> lltop edges,
// and builds the return block.
pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
debug!("trans_closure: function lltype: {}",
bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
- let arg_datums = if abi != RustCall {
- create_datums_for_fn_args(&fcx,
- &monomorphized_arg_types[..])
- } else {
- create_datums_for_fn_args_under_call_abi(
- bcx,
- arg_scope,
- &monomorphized_arg_types[..])
- };
-
- bcx = match closure_env {
- closure::ClosureEnv::NotClosure => {
- copy_args_to_allocas(bcx,
- arg_scope,
- &decl.inputs,
- arg_datums)
+ let arg_datums = match closure_env {
+ closure::ClosureEnv::NotClosure if abi == RustCall => {
+ create_datums_for_fn_args_under_call_abi(bcx, arg_scope, &monomorphized_arg_types[..])
}
- closure::ClosureEnv::Closure(_) => {
- copy_closure_args_to_allocas(
- bcx,
- arg_scope,
- &decl.inputs,
- arg_datums,
- &monomorphized_arg_types[..])
+ _ => {
+ let arg_tys = untuple_arguments_if_necessary(ccx, &monomorphized_arg_types, abi);
+ create_datums_for_fn_args(&fcx, &arg_tys)
}
};
+ bcx = copy_args_to_allocas(bcx, arg_scope, &decl.inputs, arg_datums);
+
bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
// Up until here, IR instructions for this function have explicitly not been annotated with
static");
}
- let v = ccx.static_values().borrow()[item.id].clone();
+ let v = ccx.static_values().borrow().get(&item.id).unwrap().clone();
unsafe {
if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
ccx.sess().span_fatal(expr.span, "static assertion failed");
/// but for the bare function type given.
pub fn trans_fn_pointer_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
+ closure_kind: ty::ClosureKind,
bare_fn_ty: Ty<'tcx>)
-> ValueRef
{
let _icx = push_ctxt("trans_fn_pointer_shim");
let tcx = ccx.tcx();
+ // Normalize the type for better caching.
let bare_fn_ty = common::erase_regions(tcx, &bare_fn_ty);
- match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty) {
+
+ // If this is an impl of `Fn` or `FnMut` trait, the receiver is `&self`.
+ let is_by_ref = match closure_kind {
+ ty::FnClosureKind | ty::FnMutClosureKind => true,
+ ty::FnOnceClosureKind => false,
+ };
+ let bare_fn_ty_maybe_ref = if is_by_ref {
+ ty::mk_imm_rptr(tcx, tcx.mk_region(ty::ReStatic), bare_fn_ty)
+ } else {
+ bare_fn_ty
+ };
+
+ // Check if we already trans'd this shim.
+ match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty_maybe_ref) {
Some(&llval) => { return llval; }
None => { }
}
debug!("trans_fn_pointer_shim(bare_fn_ty={})",
bare_fn_ty.repr(tcx));
- // This is an impl of `Fn` trait, so receiver is `&self`.
- let bare_fn_ty_ref = ty::mk_imm_rptr(tcx, tcx.mk_region(ty::ReStatic), bare_fn_ty);
-
// Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
// which is the fn pointer, and `args`, which is the arguments tuple.
let (opt_def_id, sig) =
unsafety: ast::Unsafety::Normal,
abi: synabi::RustCall,
sig: ty::Binder(ty::FnSig {
- inputs: vec![bare_fn_ty_ref,
+ inputs: vec![bare_fn_ty_maybe_ref,
tuple_input_ty],
output: sig.output,
variadic: false
let mut bcx = init_function(&fcx, false, sig.output);
// the first argument (`self`) will be ptr to the the fn pointer
- let llfnpointer =
- Load(bcx, get_param(fcx.llfn, fcx.arg_pos(0) as u32));
+ let llfnpointer = if is_by_ref {
+ Load(bcx, get_param(fcx.llfn, fcx.arg_pos(0) as u32))
+ } else {
+ get_param(fcx.llfn, fcx.arg_pos(0) as u32)
+ };
// the remaining arguments will be the untupled values
let llargs: Vec<_> =
finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
- ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty, llfn);
+ ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty_maybe_ref, llfn);
llfn
}
let ref_ty = match node {
ExprId(id) => ty::node_id_to_type(tcx, id),
MethodCallKey(method_call) => {
- (*tcx.method_map.borrow())[method_call].ty
+ tcx.method_map.borrow().get(&method_call).unwrap().ty
}
};
let ref_ty = monomorphize::apply_param_substs(tcx,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use back::link::mangle_internal_name_by_path_and_seq;
-use llvm::ValueRef;
+use arena::TypedArena;
+use back::link::{self, mangle_internal_name_by_path_and_seq};
+use llvm::{ValueRef, get_param};
use middle::mem_categorization::Typer;
use trans::adt;
use trans::base::*;
use trans::build::*;
-use trans::cleanup::{CleanupMethods, ScopeId};
+use trans::callee::{self, ArgVals, Callee, TraitItem, MethodData};
+use trans::cleanup::{CleanupMethods, CustomScope, ScopeId};
use trans::common::*;
-use trans::datum::{Datum, rvalue_scratch_datum};
-use trans::datum::{Rvalue, ByValue};
-use trans::debuginfo;
+use trans::datum::{self, Datum, rvalue_scratch_datum, Rvalue, ByValue};
+use trans::debuginfo::{self, DebugLoc};
use trans::expr;
use trans::monomorphize::{self, MonoId};
use trans::type_of::*;
use middle::ty::{self, ClosureTyper};
use middle::subst::{Substs};
use session::config::FullDebugInfo;
+use util::ppaux::Repr;
+use syntax::abi::RustCall;
use syntax::ast;
use syntax::ast_util;
// Create the closure.
for (i, freevar) in freevars.iter().enumerate() {
let datum = expr::trans_local_var(bcx, freevar.def);
- let upvar_slot_dest = adt::trans_field_ptr(bcx,
- &*repr,
- dest_addr,
- 0,
- i);
+ let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr, dest_addr, 0, i);
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: id };
match tcx.upvar_capture(upvar_id).unwrap() {
Some(bcx)
}
+
+pub fn trans_closure_method<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
+ closure_def_id: ast::DefId,
+ substs: Substs<'tcx>,
+ node: ExprOrMethodCall,
+ param_substs: &'tcx Substs<'tcx>,
+ trait_closure_kind: ty::ClosureKind)
+ -> ValueRef
+{
+ // The substitutions should have no type parameters remaining
+ // after passing through fulfill_obligation
+ let llfn = callee::trans_fn_ref_with_substs(ccx,
+ closure_def_id,
+ node,
+ param_substs,
+ substs.clone()).val;
+
+ // If the closure is a Fn closure, but a FnOnce is needed (etc),
+ // then adapt the self type
+ let closure_kind = ccx.tcx().closure_kind(closure_def_id);
+ trans_closure_adapter_shim(ccx,
+ closure_def_id,
+ substs,
+ closure_kind,
+ trait_closure_kind,
+ llfn)
+}
+
+fn trans_closure_adapter_shim<'a, 'tcx>(
+ ccx: &'a CrateContext<'a, 'tcx>,
+ closure_def_id: ast::DefId,
+ substs: Substs<'tcx>,
+ llfn_closure_kind: ty::ClosureKind,
+ trait_closure_kind: ty::ClosureKind,
+ llfn: ValueRef)
+ -> ValueRef
+{
+ let _icx = push_ctxt("trans_closure_adapter_shim");
+ let tcx = ccx.tcx();
+
+ debug!("trans_closure_adapter_shim(llfn_closure_kind={:?}, \
+ trait_closure_kind={:?}, \
+ llfn={})",
+ llfn_closure_kind,
+ trait_closure_kind,
+ ccx.tn().val_to_string(llfn));
+
+ match (llfn_closure_kind, trait_closure_kind) {
+ (ty::FnClosureKind, ty::FnClosureKind) |
+ (ty::FnMutClosureKind, ty::FnMutClosureKind) |
+ (ty::FnOnceClosureKind, ty::FnOnceClosureKind) => {
+ // No adapter needed.
+ llfn
+ }
+ (ty::FnClosureKind, ty::FnMutClosureKind) => {
+ // The closure fn `llfn` is a `fn(&self, ...)`. We want a
+ // `fn(&mut self, ...)`. In fact, at trans time, these are
+ // basically the same thing, so we can just return llfn.
+ llfn
+ }
+ (ty::FnClosureKind, ty::FnOnceClosureKind) |
+ (ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
+ // The closure fn `llfn` is a `fn(&self, ...)` or `fn(&mut
+ // self, ...)`. We want a `fn(self, ...)`. We can produce
+ // this by doing something like:
+ //
+ // fn call_once(self, ...) { call_mut(&self, ...) }
+ // fn call_once(mut self, ...) { call_mut(&mut self, ...) }
+ //
+ // These are both the same at trans time.
+ trans_fn_once_adapter_shim(ccx, closure_def_id, substs, llfn)
+ }
+ _ => {
+ tcx.sess.bug(&format!("trans_closure_adapter_shim: cannot convert {:?} to {:?}",
+ llfn_closure_kind,
+ trait_closure_kind));
+ }
+ }
+}
+
+fn trans_fn_once_adapter_shim<'a, 'tcx>(
+ ccx: &'a CrateContext<'a, 'tcx>,
+ closure_def_id: ast::DefId,
+ substs: Substs<'tcx>,
+ llreffn: ValueRef)
+ -> ValueRef
+{
+ debug!("trans_fn_once_adapter_shim(closure_def_id={}, substs={}, llreffn={})",
+ closure_def_id.repr(ccx.tcx()),
+ substs.repr(ccx.tcx()),
+ ccx.tn().val_to_string(llreffn));
+
+ let tcx = ccx.tcx();
+ let typer = NormalizingClosureTyper::new(tcx);
+
+ // Find a version of the closure type. Substitute static for the
+ // region since it doesn't really matter.
+ let substs = tcx.mk_substs(substs);
+ let closure_ty = ty::mk_closure(tcx, closure_def_id, substs);
+ let ref_closure_ty = ty::mk_imm_rptr(tcx, tcx.mk_region(ty::ReStatic), closure_ty);
+
+ // Make a version with the type of by-ref closure.
+ let ty::ClosureTy { unsafety, abi, mut sig } = typer.closure_type(closure_def_id, substs);
+ sig.0.inputs.insert(0, ref_closure_ty); // sig has no self type as of yet
+ let llref_bare_fn_ty = tcx.mk_bare_fn(ty::BareFnTy { unsafety: unsafety,
+ abi: abi,
+ sig: sig.clone() });
+ let llref_fn_ty = ty::mk_bare_fn(tcx, None, llref_bare_fn_ty);
+ debug!("trans_fn_once_adapter_shim: llref_fn_ty={}",
+ llref_fn_ty.repr(tcx));
+
+ // Make a version of the closure type with the same arguments, but
+ // with argument #0 being by value.
+ assert_eq!(abi, RustCall);
+ sig.0.inputs[0] = closure_ty;
+ let llonce_bare_fn_ty = tcx.mk_bare_fn(ty::BareFnTy { unsafety: unsafety,
+ abi: abi,
+ sig: sig });
+ let llonce_fn_ty = ty::mk_bare_fn(tcx, None, llonce_bare_fn_ty);
+
+ // Create the by-value helper.
+ let function_name = link::mangle_internal_name_by_type_and_seq(ccx, llonce_fn_ty, "once_shim");
+ let lloncefn = decl_internal_rust_fn(ccx, llonce_fn_ty, &function_name);
+
+ let sig = ty::erase_late_bound_regions(tcx, &llonce_bare_fn_ty.sig);
+ let (block_arena, fcx): (TypedArena<_>, FunctionContext);
+ block_arena = TypedArena::new();
+ fcx = new_fn_ctxt(ccx,
+ lloncefn,
+ ast::DUMMY_NODE_ID,
+ false,
+ sig.output,
+ substs,
+ None,
+ &block_arena);
+ let mut bcx = init_function(&fcx, false, sig.output);
+
+ // the first argument (`self`) will be the (by value) closure env.
+ let self_scope = fcx.push_custom_cleanup_scope();
+ let self_scope_id = CustomScope(self_scope);
+ let rvalue_mode = datum::appropriate_rvalue_mode(ccx, closure_ty);
+ let llself = get_param(lloncefn, fcx.arg_pos(0) as u32);
+ let env_datum = Datum::new(llself, closure_ty, Rvalue::new(rvalue_mode));
+ let env_datum = unpack_datum!(bcx,
+ env_datum.to_lvalue_datum_in_scope(bcx, "self",
+ self_scope_id));
+
+ debug!("trans_fn_once_adapter_shim: env_datum={}",
+ bcx.val_to_string(env_datum.val));
+
+ // the remaining arguments will be packed up in a tuple.
+ let input_tys = match sig.inputs[1].sty {
+ ty::ty_tup(ref tys) => &**tys,
+ _ => bcx.sess().bug(&format!("trans_fn_once_adapter_shim: not rust-call! \
+ closure_def_id={}",
+ closure_def_id.repr(tcx)))
+ };
+ let llargs: Vec<_> =
+ input_tys.iter()
+ .enumerate()
+ .map(|(i, _)| get_param(lloncefn, fcx.arg_pos(i+1) as u32))
+ .collect();
+
+ let dest =
+ fcx.llretslotptr.get().map(
+ |_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
+
+ let callee_data = TraitItem(MethodData { llfn: llreffn,
+ llself: env_datum.val });
+
+ bcx = callee::trans_call_inner(bcx,
+ DebugLoc::None,
+ llref_fn_ty,
+ |bcx, _| Callee { bcx: bcx, data: callee_data },
+ ArgVals(&llargs),
+ dest).bcx;
+
+ fcx.pop_custom_cleanup_scope(self_scope);
+
+ finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
+
+ lloncefn
+}
}
fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture> {
- Some(self.tcx().upvar_capture_map.borrow()[upvar_id].clone())
+ Some(self.tcx().upvar_capture_map.borrow().get(&upvar_id).unwrap().clone())
}
fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
// shallow result we are looking for -- that is, what specific impl.
let typer = NormalizingClosureTyper::new(tcx);
let mut selcx = traits::SelectionContext::new(&infcx, &typer);
- let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
- trait_ref.to_poly_trait_predicate());
+ let obligation =
+ traits::Obligation::new(traits::ObligationCause::misc(span, ast::DUMMY_NODE_ID),
+ trait_ref.to_poly_trait_predicate());
let selection = match selcx.select(&obligation) {
Ok(Some(selection)) => selection,
Ok(None) => {
let obligation = traits::Obligation::new(traits::ObligationCause::dummy(), predicate);
fulfill_cx.register_predicate_obligation(&infcx, obligation);
}
- drain_fulfillment_cx(DUMMY_SP, &infcx, &mut fulfill_cx, &()).is_ok()
+ drain_fulfillment_cx(&infcx, &mut fulfill_cx, &()).is_ok()
}
pub struct NormalizingClosureTyper<'a,'tcx:'a> {
-> T
where T : TypeFoldable<'tcx> + Repr<'tcx>
{
- match drain_fulfillment_cx(span, infcx, fulfill_cx, result) {
+ match drain_fulfillment_cx(infcx, fulfill_cx, result) {
Ok(v) => v,
Err(errors) => {
infcx.tcx.sess.span_bug(
/// inference variables that appear in `result` to be unified, and
/// hence we need to process those obligations to get the complete
/// picture of the type.
-pub fn drain_fulfillment_cx<'a,'tcx,T>(span: Span,
- infcx: &infer::InferCtxt<'a,'tcx>,
+pub fn drain_fulfillment_cx<'a,'tcx,T>(infcx: &infer::InferCtxt<'a,'tcx>,
fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
result: &T)
-> StdResult<T,Vec<traits::FulfillmentError<'tcx>>>
match fulfill_cx.select_all_or_error(infcx, &typer) {
Ok(()) => { }
Err(errors) => {
- // We always want to surface any overflow errors, no matter what.
- if errors.iter().all(|e| e.is_overflow()) {
- infcx.tcx.sess.span_fatal(
- span,
- "reached the recursion limit during monomorphization");
- } else {
- return Err(errors);
- }
+ return Err(errors);
}
}
ty::node_id_item_substs(tcx, id).substs
}
MethodCallKey(method_call) => {
- (*tcx.method_map.borrow())[method_call].substs.clone()
+ tcx.method_map.borrow().get(&method_call).unwrap().substs.clone()
}
};
// Special-case constants to cache a common global for all uses.
match expr.node {
ast::ExprPath(..) => {
- let def = ccx.tcx().def_map.borrow()[expr.id].full_def();
+ let def = ccx.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
match def {
def::DefConst(def_id) => {
if !ccx.tcx().adjustments.borrow().contains_key(&expr.id) {
}
}
ast::ExprPath(..) => {
- let def = cx.tcx().def_map.borrow()[e.id].full_def();
+ let def = cx.tcx().def_map.borrow().get(&e.id).unwrap().full_def();
match def {
def::DefFn(..) | def::DefMethod(..) => {
expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
let g = base::get_item_val(ccx, id);
// At this point, get_item_val has already translated the
// constant's initializer to determine its LLVM type.
- let v = ccx.static_values().borrow()[id].clone();
+ let v = ccx.static_values().borrow().get(&id).unwrap().clone();
// boolean SSA values are i1, but they have to be stored in i8 slots,
// otherwise some LLVM optimization passes don't work as expected
let v = if llvm::LLVMTypeOf(v) == Type::i1(ccx).to_ref() {
})
}
- /// Ensures that `self` will get cleaned up, if it is not an lvalue already.
- pub fn clean<'blk>(self,
- bcx: Block<'blk, 'tcx>,
- name: &'static str,
- expr_id: ast::NodeId)
- -> Block<'blk, 'tcx> {
- self.to_lvalue_datum(bcx, name, expr_id).bcx
- }
-
pub fn to_lvalue_datum<'blk>(self,
bcx: Block<'blk, 'tcx>,
name: &str,
};
let name = CString::new(name.as_bytes()).unwrap();
- match (variable_access, [].as_slice()) {
+ match (variable_access, &[][..]) {
(DirectVariable { alloca }, address_operations) |
(IndirectVariable {alloca, address_operations}, _) => {
let metadata = unsafe {
return datum.store_to_dest(bcx, dest, expr.id);
}
- let qualif = bcx.tcx().const_qualif_map.borrow()[expr.id];
+ let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
if !qualif.intersects(check_const::NOT_CONST | check_const::NEEDS_DROP) {
if !qualif.intersects(check_const::PREFER_IN_PLACE) {
if let SaveIn(lldest) = dest {
let mut bcx = bcx;
let fcx = bcx.fcx;
- let qualif = bcx.tcx().const_qualif_map.borrow()[expr.id];
+ let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
let adjusted_global = !qualif.intersects(check_const::NON_STATIC_BORROWS);
let global = if !qualif.intersects(check_const::NOT_CONST | check_const::NEEDS_DROP) {
let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
base_datum,
vec![(ix_datum, idx.id)],
Some(SaveIn(scratch.val)),
- true));
+ false));
let datum = scratch.to_expr_datum();
if type_is_sized(bcx.tcx(), elt_ty) {
Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr)
trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
vec![(idx_datum, idx.id)], Some(dest), true).bcx
}
- ast::ExprCast(ref val, _) => {
- // DPS output mode means this is a trait cast:
- if ty::type_is_trait(node_id_type(bcx, expr.id)) {
- let trait_ref =
- bcx.tcx().object_cast_map.borrow()
- .get(&expr.id)
- .cloned()
- .unwrap();
- let trait_ref = bcx.monomorphize(&trait_ref);
- let datum = unpack_datum!(bcx, trans(bcx, &**val));
- meth::trans_trait_cast(bcx, datum, expr.id,
- trait_ref, dest)
- } else {
- bcx.tcx().sess.span_bug(expr.span,
- "expr_cast of non-trait");
- }
+ ast::ExprCast(..) => {
+ // Trait casts used to come this way, now they should be coercions.
+ bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
}
ast::ExprAssignOp(op, ref dst, ref src) => {
trans_assign_op(bcx, expr, op, &**dst, &**src)
ty.repr(tcx)));
}
Some(node_id) => {
- let def = tcx.def_map.borrow()[node_id].full_def();
+ let def = tcx.def_map.borrow().get(&node_id).unwrap().full_def();
match def {
def::DefVariant(enum_id, variant_id, _) => {
let variant_info = ty::enum_variant_with_id(tcx, enum_id, variant_id);
dest: Option<Dest>,
autoref: bool)
-> Result<'blk, 'tcx> {
- let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
+ let method_ty = bcx.tcx().method_map.borrow().get(&method_call).unwrap().ty;
callee::trans_call_inner(bcx,
expr.debug_loc(),
monomorphize_type(bcx, method_ty),
dest: Option<Dest>)
-> Block<'blk, 'tcx> {
let method_call = MethodCall::expr(expr.id);
- let method_type = (*bcx.tcx()
- .method_map
- .borrow())[method_call]
- .ty;
+ let method_type = bcx.tcx()
+ .method_map
+ .borrow()
+ .get(&method_call)
+ .unwrap()
+ .ty;
let mut all_args = vec!(callee);
all_args.extend(args.iter().map(|e| &**e));
unpack_result!(bcx,
let mut bcx = bcx;
let ccx = bcx.ccx();
- let t_in = expr_ty(bcx, expr);
+ let t_in = expr_ty_adjusted(bcx, expr);
let t_out = node_id_type(bcx, id);
let k_in = cast_type_kind(bcx.tcx(), t_in);
let k_out = cast_type_kind(bcx.tcx(), t_out);
// by-value as appropriate given its type:
let mut datum = unpack_datum!(bcx, trans(bcx, expr));
- if cast_is_noop(datum.ty, t_out) {
+ let datum_ty = monomorphize_type(bcx, datum.ty);
+ if cast_is_noop(datum_ty, t_out) {
datum.ty = t_out;
return DatumBlock::new(bcx, datum);
}
InBoundsGEP(bcx, ptr, &[offset])
}
- (_, "copy_nonoverlapping_memory") => {
+ (_, "copy_nonoverlapping") => {
copy_intrinsic(bcx,
false,
false,
llargs[2],
call_debug_location)
}
- (_, "copy_memory") => {
+ (_, "copy") => {
copy_intrinsic(bcx,
true,
false,
llargs[2],
call_debug_location)
}
- (_, "set_memory") => {
+ (_, "write_bytes") => {
memset_intrinsic(bcx,
false,
*substs.types.get(FnSpace, 0),
use middle::subst::VecPerParamSpace;
use middle::subst;
use middle::traits;
+use middle::ty::ClosureTyper;
use trans::base::*;
use trans::build::*;
use trans::callee::*;
use trans::callee;
use trans::cleanup;
+use trans::closure;
use trans::common::*;
use trans::consts;
use trans::datum::*;
use trans::debuginfo::DebugLoc;
-use trans::expr::{SaveIn, Ignore};
+use trans::expr::SaveIn;
use trans::expr;
use trans::glue;
use trans::machine;
traits::VtableClosure(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.ccx(),
- closure_def_id,
- MethodCallKey(method_call),
- bcx.fcx.param_substs,
- substs).val;
-
+ let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
+ let llfn = closure::trans_closure_method(bcx.ccx(),
+ closure_def_id,
+ substs,
+ MethodCallKey(method_call),
+ bcx.fcx.param_substs,
+ trait_closure_kind);
Callee {
bcx: bcx,
data: Fn(llfn),
}
}
traits::VtableFnPointer(fn_ty) => {
- let llfn = trans_fn_pointer_shim(bcx.ccx(), fn_ty);
+ let trait_closure_kind = bcx.tcx().lang_items.fn_trait_kind(trait_id).unwrap();
+ let llfn = trans_fn_pointer_shim(bcx.ccx(), trait_closure_kind, fn_ty);
Callee { bcx: bcx, data: Fn(llfn) }
}
traits::VtableObject(ref data) => {
assert!(!fcx.needs_ret_allocas);
- let sig =
- ty::erase_late_bound_regions(bcx.tcx(), &fty.sig);
-
let dest =
fcx.llretslotptr.get().map(
|_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
emit_vtable_methods(ccx, id, substs, param_substs).into_iter()
}
traits::VtableClosure(closure_def_id, substs) => {
- let llfn = trans_fn_ref_with_substs(
- ccx,
- closure_def_id,
- ExprId(0),
- param_substs,
- substs).val;
-
+ let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
+ let llfn = closure::trans_closure_method(ccx,
+ closure_def_id,
+ substs,
+ ExprId(0),
+ param_substs,
+ trait_closure_kind);
vec![llfn].into_iter()
}
traits::VtableFnPointer(bare_fn_ty) => {
- vec![trans_fn_pointer_shim(ccx, bare_fn_ty)].into_iter()
+ let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_ref.def_id()).unwrap();
+ vec![trans_fn_pointer_shim(ccx, trait_closure_kind, bare_fn_ty)].into_iter()
}
traits::VtableObject(ref data) => {
// this would imply that the Self type being erased is
.collect()
}
-/// Generates the code to convert from a pointer (`Box<T>`, `&T`, etc) into an object
-/// (`Box<Trait>`, `&Trait`, etc). This means creating a pair where the first word is the vtable
-/// and the second word is the pointer.
-pub fn trans_trait_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
- datum: Datum<'tcx, Expr>,
- id: ast::NodeId,
- trait_ref: ty::PolyTraitRef<'tcx>,
- dest: expr::Dest)
- -> Block<'blk, 'tcx> {
- let mut bcx = bcx;
- let _icx = push_ctxt("meth::trans_trait_cast");
-
- let lldest = match dest {
- Ignore => {
- return datum.clean(bcx, "trait_trait_cast", id);
- }
- SaveIn(dest) => dest
- };
-
- debug!("trans_trait_cast: trait_ref={}",
- trait_ref.repr(bcx.tcx()));
-
- let llty = type_of(bcx.ccx(), datum.ty);
-
- // Store the pointer into the first half of pair.
- let llboxdest = GEPi(bcx, lldest, &[0, abi::FAT_PTR_ADDR]);
- let llboxdest = PointerCast(bcx, llboxdest, llty.ptr_to());
- bcx = datum.store_to(bcx, llboxdest);
-
- // Store the vtable into the second half of pair.
- let vtable = get_vtable(bcx.ccx(), trait_ref, bcx.fcx.param_substs);
- let llvtabledest = GEPi(bcx, lldest, &[0, abi::FAT_PTR_EXTRA]);
- let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to());
- Store(bcx, vtable, llvtabledest);
-
- bcx
-}
-
/// Replace the self type (&Self or Box<Self>) with an opaque pointer.
pub fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>)
-> &'tcx ty::BareFnTy<'tcx> {
use middle::privacy::{AllPublic, LastMod};
use middle::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs};
use middle::traits;
-use middle::ty::{self, RegionEscape, ToPolyTraitRef, Ty};
+use middle::ty::{self, RegionEscape, Ty};
use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope};
use util::common::{ErrorReported, FN_OUTPUT_NAME};
poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
-> ty::PolyTraitRef<'tcx>
{
- let mut projections = Vec::new();
-
- // The trait reference introduces a binding level here, so
- // we need to shift the `rscope`. It'd be nice if we could
- // do away with this rscope stuff and work this knowledge
- // into resolve_lifetimes, as we do with non-omitted
- // lifetimes. Oh well, not there yet.
- let shifted_rscope = ShiftedRscope::new(rscope);
-
- let trait_ref = instantiate_trait_ref(this, &shifted_rscope,
- &ast_trait_ref.trait_ref,
- None, self_ty, Some(&mut projections));
-
- for projection in projections {
- poly_projections.push(ty::Binder(projection));
- }
-
- ty::Binder(trait_ref)
+ let trait_ref = &ast_trait_ref.trait_ref;
+ let trait_def_id = trait_def_id(this, trait_ref);
+ ast_path_to_poly_trait_ref(this,
+ rscope,
+ trait_ref.path.span,
+ PathParamMode::Explicit,
+ trait_def_id,
+ self_ty,
+ trait_ref.path.segments.last().unwrap(),
+ poly_projections)
}
/// Instantiates the path for the given trait reference, assuming that it's
///
/// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
/// are disallowed. Otherwise, they are pushed onto the vector given.
-pub fn instantiate_trait_ref<'tcx>(
+pub fn instantiate_mono_trait_ref<'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
trait_ref: &ast::TraitRef,
- impl_id: Option<ast::NodeId>,
- self_ty: Option<Ty<'tcx>>,
- projections: Option<&mut Vec<ty::ProjectionPredicate<'tcx>>>)
+ self_ty: Option<Ty<'tcx>>)
-> Rc<ty::TraitRef<'tcx>>
{
+ let trait_def_id = trait_def_id(this, trait_ref);
+ ast_path_to_mono_trait_ref(this,
+ rscope,
+ trait_ref.path.span,
+ PathParamMode::Explicit,
+ trait_def_id,
+ self_ty,
+ trait_ref.path.segments.last().unwrap())
+}
+
+fn trait_def_id<'tcx>(this: &AstConv<'tcx>, trait_ref: &ast::TraitRef) -> ast::DefId {
let path = &trait_ref.path;
match ::lookup_full_def(this.tcx(), path.span, trait_ref.ref_id) {
- def::DefTrait(trait_def_id) => {
- let trait_ref = ast_path_to_trait_ref(this,
- rscope,
- path.span,
- PathParamMode::Explicit,
- trait_def_id,
- self_ty,
- path.segments.last().unwrap(),
- projections);
- if let Some(id) = impl_id {
- this.tcx().impl_trait_refs.borrow_mut().insert(id, trait_ref.clone());
- }
- trait_ref
- }
+ def::DefTrait(trait_def_id) => trait_def_id,
_ => {
span_fatal!(this.tcx().sess, path.span, E0245, "`{}` is not a trait",
path.user_string(this.tcx()));
mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
-> ty::PolyTraitRef<'tcx>
{
- // we are introducing a binder here, so shift the
- // anonymous regions depth to account for that
- let shifted_rscope = ShiftedRscope::new(rscope);
-
- let mut tmp = Vec::new();
- let trait_ref = ty::Binder(ast_path_to_trait_ref(this,
- &shifted_rscope,
- span,
- param_mode,
- trait_def_id,
- None,
- trait_segment,
- Some(&mut tmp)));
- projections.extend(tmp.into_iter().map(ty::Binder));
- trait_ref
+ ast_path_to_poly_trait_ref(this,
+ rscope,
+ span,
+ param_mode,
+ trait_def_id,
+ None,
+ trait_segment,
+ projections)
}
-fn ast_path_to_trait_ref<'a,'tcx>(
+fn ast_path_to_poly_trait_ref<'a,'tcx>(
this: &AstConv<'tcx>,
rscope: &RegionScope,
span: Span,
trait_def_id: ast::DefId,
self_ty: Option<Ty<'tcx>>,
trait_segment: &ast::PathSegment,
- mut projections: Option<&mut Vec<ty::ProjectionPredicate<'tcx>>>)
- -> Rc<ty::TraitRef<'tcx>>
+ poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
+ -> ty::PolyTraitRef<'tcx>
+{
+ // The trait reference introduces a binding level here, so
+ // we need to shift the `rscope`. It'd be nice if we could
+ // do away with this rscope stuff and work this knowledge
+ // into resolve_lifetimes, as we do with non-omitted
+ // lifetimes. Oh well, not there yet.
+ let shifted_rscope = &ShiftedRscope::new(rscope);
+
+ let (substs, assoc_bindings) =
+ create_substs_for_ast_trait_ref(this,
+ shifted_rscope,
+ span,
+ param_mode,
+ trait_def_id,
+ self_ty,
+ trait_segment);
+ let poly_trait_ref = ty::Binder(Rc::new(ty::TraitRef::new(trait_def_id, substs)));
+
+ {
+ let converted_bindings =
+ assoc_bindings
+ .iter()
+ .filter_map(|binding| {
+ // specify type to assert that error was already reported in Err case:
+ let predicate: Result<_, ErrorReported> =
+ ast_type_binding_to_poly_projection_predicate(this,
+ poly_trait_ref.clone(),
+ self_ty,
+ binding);
+ predicate.ok() // ok to ignore Err() because ErrorReported (see above)
+ });
+ poly_projections.extend(converted_bindings);
+ }
+
+ poly_trait_ref
+}
+
+fn ast_path_to_mono_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
+ rscope: &RegionScope,
+ span: Span,
+ param_mode: PathParamMode,
+ trait_def_id: ast::DefId,
+ self_ty: Option<Ty<'tcx>>,
+ trait_segment: &ast::PathSegment)
+ -> Rc<ty::TraitRef<'tcx>>
{
- debug!("ast_path_to_trait_ref {:?}", trait_segment);
+ let (substs, assoc_bindings) =
+ create_substs_for_ast_trait_ref(this,
+ rscope,
+ span,
+ param_mode,
+ trait_def_id,
+ self_ty,
+ trait_segment);
+ prohibit_projections(this.tcx(), &assoc_bindings);
+ Rc::new(ty::TraitRef::new(trait_def_id, substs))
+}
+
+fn create_substs_for_ast_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
+ rscope: &RegionScope,
+ span: Span,
+ param_mode: PathParamMode,
+ trait_def_id: ast::DefId,
+ self_ty: Option<Ty<'tcx>>,
+ trait_segment: &ast::PathSegment)
+ -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
+{
+ debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
+ trait_segment);
+
let trait_def = match this.get_trait_def(span, trait_def_id) {
Ok(trait_def) => trait_def,
Err(ErrorReported) => {
self_ty,
types,
regions);
- let substs = this.tcx().mk_substs(substs);
- let trait_ref = Rc::new(ty::TraitRef::new(trait_def_id, substs));
-
- match projections {
- None => {
- prohibit_projections(this.tcx(), &assoc_bindings);
- }
- Some(ref mut v) => {
- for binding in &assoc_bindings {
- match ast_type_binding_to_projection_predicate(this, trait_ref.clone(),
- self_ty, binding) {
- Ok(pp) => { v.push(pp); }
- Err(ErrorReported) => { }
- }
- }
- }
- }
-
- trait_ref
+ (this.tcx().mk_substs(substs), assoc_bindings)
}
-fn ast_type_binding_to_projection_predicate<'tcx>(
+fn ast_type_binding_to_poly_projection_predicate<'tcx>(
this: &AstConv<'tcx>,
- mut trait_ref: Rc<ty::TraitRef<'tcx>>,
+ mut trait_ref: ty::PolyTraitRef<'tcx>,
self_ty: Option<Ty<'tcx>>,
binding: &ConvertedBinding<'tcx>)
- -> Result<ty::ProjectionPredicate<'tcx>, ErrorReported>
+ -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
{
let tcx = this.tcx();
// We want to produce `<B as SuperTrait<int>>::T == foo`.
// Simple case: X is defined in the current trait.
- if this.trait_defines_associated_type_named(trait_ref.def_id, binding.item_name) {
- return Ok(ty::ProjectionPredicate {
- projection_ty: ty::ProjectionTy {
- trait_ref: trait_ref,
+ if this.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
+ return Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------+
+ projection_ty: ty::ProjectionTy { // |
+ trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
item_name: binding.item_name,
},
ty: binding.ty,
- });
+ }));
}
// Otherwise, we have to walk through the supertraits to find
let dummy_self_ty = ty::mk_infer(tcx, ty::FreshTy(0));
if self_ty.is_none() { // if converting for an object type
- let mut dummy_substs = trait_ref.substs.clone();
- assert!(dummy_substs.self_ty().is_none());
- dummy_substs.types.push(SelfSpace, dummy_self_ty);
- trait_ref = Rc::new(ty::TraitRef::new(trait_ref.def_id,
- tcx.mk_substs(dummy_substs)));
+ let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
+ assert!(dummy_substs.self_ty().is_none()); // |
+ dummy_substs.types.push(SelfSpace, dummy_self_ty); // |
+ trait_ref = ty::Binder(Rc::new(ty::TraitRef::new(trait_ref.def_id(), // <------------+
+ tcx.mk_substs(dummy_substs))));
}
- try!(this.ensure_super_predicates(binding.span, trait_ref.def_id));
+ try!(this.ensure_super_predicates(binding.span, trait_ref.def_id()));
let mut candidates: Vec<ty::PolyTraitRef> =
- traits::supertraits(tcx, trait_ref.to_poly_trait_ref())
+ traits::supertraits(tcx, trait_ref.clone())
.filter(|r| this.trait_defines_associated_type_named(r.def_id(), binding.item_name))
.collect();
}
};
- if ty::binds_late_bound_regions(tcx, &candidate) {
- span_err!(tcx.sess, binding.span, E0219,
- "associated type `{}` defined in higher-ranked supertrait `{}`",
- token::get_name(binding.item_name),
- candidate.user_string(tcx));
- return Err(ErrorReported);
- }
-
- Ok(ty::ProjectionPredicate {
- projection_ty: ty::ProjectionTy {
- trait_ref: candidate.0,
+ Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
+ projection_ty: ty::ProjectionTy { // |
+ trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
item_name: binding.item_name,
},
ty: binding.ty,
- })
+ }))
}
fn ast_path_to_ty<'tcx>(
return (tcx.types.err, ty_path_def);
};
- let ty_param_name = tcx.ty_param_defs.borrow()[ty_param_node_id].name;
+ let ty_param_name = tcx.ty_param_defs.borrow().get(&ty_param_node_id).unwrap().name;
let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) {
Ok(v) => v,
debug!("qpath_to_ty: self_type={}", self_ty.repr(tcx));
- let trait_ref = ast_path_to_trait_ref(this,
- rscope,
- span,
- param_mode,
- trait_def_id,
- Some(self_ty),
- trait_segment,
- None);
+ let trait_ref =
+ ast_path_to_mono_trait_ref(this,
+ rscope,
+ span,
+ param_mode,
+ trait_def_id,
+ Some(self_ty),
+ trait_segment);
debug!("qpath_to_ty: trait_ref={}", trait_ref.repr(tcx));
demand::eqtype(fcx, pat.span, expected, lhs_ty);
}
ast::PatEnum(..) | ast::PatIdent(..) if pat_is_const(&tcx.def_map, pat) => {
- let const_did = tcx.def_map.borrow()[pat.id].def_id();
+ let const_did = tcx.def_map.borrow().get(&pat.id).unwrap().def_id();
let const_scheme = ty::lookup_item_type(tcx, const_did);
assert!(const_scheme.generics.is_empty());
let const_ty = pcx.fcx.instantiate_type_scheme(pat.span,
// if there are multiple arms, make sure they all agree on
// what the type of the binding `x` ought to be
- let canon_id = pcx.map[path.node];
+ let canon_id = *pcx.map.get(&path.node).unwrap();
if canon_id != pat.id {
let ct = fcx.local_ty(pat.span, canon_id);
demand::eqtype(fcx, pat.span, ct, typ);
// (nmatsakis) an hour or two debugging to remember, so I thought
// I'd write them down this time.
//
- // 1. Most importantly, there is no loss of expressiveness
- // here. What we are saying is that the type of `x`
- // becomes *exactly* what is expected. This might seem
- // like it will cause errors in a case like this:
+ // 1. There is no loss of expressiveness here, though it does
+ // cause some inconvenience. What we are saying is that the type
+ // of `x` becomes *exactly* what is expected. This can cause unnecessary
+ // errors in some cases, such as this one:
+ // it will cause errors in a case like this:
//
// ```
// fn foo<'x>(x: &'x int) {
match_src: ast::MatchSource) {
let tcx = fcx.ccx.tcx;
- let discrim_ty = fcx.infcx().next_ty_var();
- check_expr_has_type(fcx, discrim, discrim_ty);
+ // Not entirely obvious: if matches may create ref bindings, we
+ // want to use the *precise* type of the discriminant, *not* some
+ // supertype, as the "discriminant type" (issue #23116).
+ let contains_ref_bindings = arms.iter().any(|a| tcx.arm_contains_ref_binding(a));
+ let discrim_ty;
+ if contains_ref_bindings {
+ check_expr(fcx, discrim);
+ discrim_ty = fcx.expr_ty(discrim);
+ } else {
+ // ...but otherwise we want to use any supertype of the
+ // discriminant. This is sort of a workaround, see note (*) in
+ // `check_pat` for some details.
+ discrim_ty = fcx.infcx().next_ty_var();
+ check_expr_has_type(fcx, discrim, discrim_ty);
+ };
// Typecheck the patterns first, so that we get types for all the
// bindings.
let fcx = pcx.fcx;
let tcx = pcx.fcx.ccx.tcx;
- let def = tcx.def_map.borrow()[pat.id].full_def();
+ let def = tcx.def_map.borrow().get(&pat.id).unwrap().full_def();
let (enum_def_id, variant_def_id) = match def {
def::DefTrait(_) => {
let name = pprust::path_to_string(path);
let fcx = pcx.fcx;
let tcx = pcx.fcx.ccx.tcx;
- let def = tcx.def_map.borrow()[pat.id].full_def();
+ let def = tcx.def_map.borrow().get(&pat.id).unwrap().full_def();
let enum_def = def.variant_def_ids()
.map_or_else(|| def.def_id(), |(enum_def, _)| enum_def);
use middle::region;
use middle::subst;
use middle::ty::{self, ToPolyTraitRef, Ty};
+use std::cmp;
use syntax::abi;
use syntax::ast;
use syntax::ast_util;
ty::ty_trait(ref object_type) => {
let proj_bounds = object_type.projection_bounds_with_self_ty(fcx.tcx(),
fcx.tcx().types.err);
- let expectations =
- proj_bounds.iter()
- .filter_map(|pb| deduce_expectations_from_projection(fcx, pb))
- .next();
-
- match expectations {
- Some((sig, kind)) => (Some(sig), Some(kind)),
- None => (None, None)
- }
+ let sig = proj_bounds.iter()
+ .filter_map(|pb| deduce_sig_from_projection(fcx, pb))
+ .next();
+ let kind = fcx.tcx().lang_items.fn_trait_kind(object_type.principal_def_id());
+ (sig, kind)
}
ty::ty_infer(ty::TyVar(vid)) => {
deduce_expectations_from_obligations(fcx, vid)
let fulfillment_cx = fcx.inh.fulfillment_cx.borrow();
// Here `expected_ty` is known to be a type inference variable.
- let expected_sig_and_kind =
+ let expected_sig =
fulfillment_cx
.pending_obligations()
.iter()
ty::Predicate::Projection(ref proj_predicate) => {
let trait_ref = proj_predicate.to_poly_trait_ref();
self_type_matches_expected_vid(fcx, trait_ref, expected_vid)
- .and_then(|_| deduce_expectations_from_projection(fcx, proj_predicate))
+ .and_then(|_| deduce_sig_from_projection(fcx, proj_predicate))
}
_ => {
None
})
.next();
- match expected_sig_and_kind {
- Some((sig, kind)) => { return (Some(sig), Some(kind)); }
- None => { }
- }
-
// Even if we can't infer the full signature, we may be able to
// infer the kind. This can occur if there is a trait-reference
- // like `F : Fn<A>`.
+ // like `F : Fn<A>`. Note that due to subtyping we could encounter
+ // many viable options, so pick the most restrictive.
let expected_kind =
fulfillment_cx
.pending_obligations()
.and_then(|trait_ref| self_type_matches_expected_vid(fcx, trait_ref, expected_vid))
.and_then(|trait_ref| fcx.tcx().lang_items.fn_trait_kind(trait_ref.def_id()))
})
- .next();
+ .fold(None, pick_most_restrictive_closure_kind);
+
+ (expected_sig, expected_kind)
+}
- (None, expected_kind)
+fn pick_most_restrictive_closure_kind(best: Option<ty::ClosureKind>,
+ cur: ty::ClosureKind)
+ -> Option<ty::ClosureKind>
+{
+ match best {
+ None => Some(cur),
+ Some(best) => Some(cmp::min(best, cur))
+ }
}
/// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
/// everything we need to know about a closure.
-fn deduce_expectations_from_projection<'a,'tcx>(
+fn deduce_sig_from_projection<'a,'tcx>(
fcx: &FnCtxt<'a,'tcx>,
projection: &ty::PolyProjectionPredicate<'tcx>)
- -> Option<(ty::FnSig<'tcx>, ty::ClosureKind)>
+ -> Option<ty::FnSig<'tcx>>
{
let tcx = fcx.tcx();
- debug!("deduce_expectations_from_projection({})",
+ debug!("deduce_sig_from_projection({})",
projection.repr(tcx));
let trait_ref = projection.to_poly_trait_ref();
- let kind = match tcx.lang_items.fn_trait_kind(trait_ref.def_id()) {
- Some(k) => k,
- None => { return None; }
- };
-
- debug!("found object type {:?}", kind);
+ if tcx.lang_items.fn_trait_kind(trait_ref.def_id()).is_none() {
+ return None;
+ }
let arg_param_ty = *trait_ref.substs().types.get(subst::TypeSpace, 0);
let arg_param_ty = fcx.infcx().resolve_type_vars_if_possible(&arg_param_ty);
- debug!("arg_param_ty {}", arg_param_ty.repr(tcx));
+ debug!("deduce_sig_from_projection: arg_param_ty {}", arg_param_ty.repr(tcx));
let input_tys = match arg_param_ty.sty {
ty::ty_tup(ref tys) => { (*tys).clone() }
_ => { return None; }
};
- debug!("input_tys {}", input_tys.repr(tcx));
+ debug!("deduce_sig_from_projection: input_tys {}", input_tys.repr(tcx));
let ret_param_ty = projection.0.ty;
let ret_param_ty = fcx.infcx().resolve_type_vars_if_possible(&ret_param_ty);
- debug!("ret_param_ty {}", ret_param_ty.repr(tcx));
+ debug!("deduce_sig_from_projection: ret_param_ty {}", ret_param_ty.repr(tcx));
let fn_sig = ty::FnSig {
inputs: input_tys,
output: ty::FnConverging(ret_param_ty),
variadic: false
};
- debug!("fn_sig {}", fn_sig.repr(tcx));
+ debug!("deduce_sig_from_projection: fn_sig {}", fn_sig.repr(tcx));
- return Some((fn_sig, kind));
+ Some(fn_sig)
}
fn self_type_matches_expected_vid<'a,'tcx>(
Ok(None) // No coercion required.
}
+ fn outlives(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ()> {
+ let sub = Sub(self.fcx.infcx().combine_fields(false, self.trace.clone()));
+ try!(sub.regions(b, a));
+ Ok(())
+ }
+
fn unpack_actual_value<T, F>(&self, a: Ty<'tcx>, f: F) -> T where
F: FnOnce(Ty<'tcx>) -> T,
{
match (&a.sty, &b.sty) {
(&ty::ty_rptr(_, ty::mt{ty: t_a, mutbl: mutbl_a}), &ty::ty_rptr(_, mt_b)) => {
- self.unpack_actual_value(t_a, |a| {
- match self.unsize_ty(t_a, a, mt_b.ty) {
- Some((ty, kind)) => {
- if !can_coerce_mutbls(mutbl_a, mt_b.mutbl) {
- return Err(ty::terr_mutability);
- }
-
- let coercion = Coercion(self.trace.clone());
- let r_borrow = self.fcx.infcx().next_region_var(coercion);
- let ty = ty::mk_rptr(self.tcx(),
- self.tcx().mk_region(r_borrow),
- ty::mt{ty: ty, mutbl: mt_b.mutbl});
- try!(self.fcx.infcx().try(|_| self.subtype(ty, b)));
- debug!("Success, coerced with AutoDerefRef(1, \
- AutoPtr(AutoUnsize({:?})))", kind);
- Ok(Some(AdjustDerefRef(AutoDerefRef {
- autoderefs: 1,
- autoref: Some(ty::AutoPtr(r_borrow, mt_b.mutbl,
- Some(box AutoUnsize(kind))))
- })))
+ match self.unsize_ty(t_a, mt_b.ty) {
+ Some((ty, kind)) => {
+ if !can_coerce_mutbls(mutbl_a, mt_b.mutbl) {
+ return Err(ty::terr_mutability);
}
- _ => Err(ty::terr_mismatch)
+
+ let coercion = Coercion(self.trace.clone());
+ let r_borrow = self.fcx.infcx().next_region_var(coercion);
+ let ty = ty::mk_rptr(self.tcx(),
+ self.tcx().mk_region(r_borrow),
+ ty::mt{ty: ty, mutbl: mt_b.mutbl});
+ try!(self.fcx.infcx().try(|_| self.subtype(ty, b)));
+ debug!("Success, coerced with AutoDerefRef(1, \
+ AutoPtr(AutoUnsize({:?})))", kind);
+ Ok(Some(AdjustDerefRef(AutoDerefRef {
+ autoderefs: 1,
+ autoref: Some(ty::AutoPtr(r_borrow, mt_b.mutbl,
+ Some(box AutoUnsize(kind))))
+ })))
}
- })
+ _ => Err(ty::terr_mismatch)
+ }
}
(&ty::ty_rptr(_, ty::mt{ty: t_a, mutbl: mutbl_a}), &ty::ty_ptr(mt_b)) => {
- self.unpack_actual_value(t_a, |a| {
- match self.unsize_ty(t_a, a, mt_b.ty) {
- Some((ty, kind)) => {
- if !can_coerce_mutbls(mutbl_a, mt_b.mutbl) {
- return Err(ty::terr_mutability);
- }
-
- let ty = ty::mk_ptr(self.tcx(),
- ty::mt{ty: ty, mutbl: mt_b.mutbl});
- try!(self.fcx.infcx().try(|_| self.subtype(ty, b)));
- debug!("Success, coerced with AutoDerefRef(1, \
- AutoPtr(AutoUnsize({:?})))", kind);
- Ok(Some(AdjustDerefRef(AutoDerefRef {
- autoderefs: 1,
- autoref: Some(ty::AutoUnsafe(mt_b.mutbl,
- Some(box AutoUnsize(kind))))
- })))
+ match self.unsize_ty(t_a, mt_b.ty) {
+ Some((ty, kind)) => {
+ if !can_coerce_mutbls(mutbl_a, mt_b.mutbl) {
+ return Err(ty::terr_mutability);
}
- _ => Err(ty::terr_mismatch)
+
+ let ty = ty::mk_ptr(self.tcx(),
+ ty::mt{ty: ty, mutbl: mt_b.mutbl});
+ try!(self.fcx.infcx().try(|_| self.subtype(ty, b)));
+ debug!("Success, coerced with AutoDerefRef(1, \
+ AutoPtr(AutoUnsize({:?})))", kind);
+ Ok(Some(AdjustDerefRef(AutoDerefRef {
+ autoderefs: 1,
+ autoref: Some(ty::AutoUnsafe(mt_b.mutbl,
+ Some(box AutoUnsize(kind))))
+ })))
}
- })
+ _ => Err(ty::terr_mismatch)
+ }
}
(&ty::ty_uniq(t_a), &ty::ty_uniq(t_b)) => {
- self.unpack_actual_value(t_a, |a| {
- match self.unsize_ty(t_a, a, t_b) {
- Some((ty, kind)) => {
- let ty = ty::mk_uniq(self.tcx(), ty);
- try!(self.fcx.infcx().try(|_| self.subtype(ty, b)));
- debug!("Success, coerced with AutoDerefRef(1, \
- AutoUnsizeUniq({:?}))", kind);
- Ok(Some(AdjustDerefRef(AutoDerefRef {
- autoderefs: 1,
- autoref: Some(ty::AutoUnsizeUniq(kind))
- })))
- }
- _ => Err(ty::terr_mismatch)
+ match self.unsize_ty(t_a, t_b) {
+ Some((ty, kind)) => {
+ let ty = ty::mk_uniq(self.tcx(), ty);
+ try!(self.fcx.infcx().try(|_| self.subtype(ty, b)));
+ debug!("Success, coerced with AutoDerefRef(1, \
+ AutoUnsizeUniq({:?}))", kind);
+ Ok(Some(AdjustDerefRef(AutoDerefRef {
+ autoderefs: 1,
+ autoref: Some(ty::AutoUnsizeUniq(kind))
+ })))
}
- })
+ _ => Err(ty::terr_mismatch)
+ }
}
_ => Err(ty::terr_mismatch)
}
// E.g., `[T, ..n]` -> `([T], UnsizeLength(n))`
fn unsize_ty(&self,
ty_a: Ty<'tcx>,
- a: Ty<'tcx>,
ty_b: Ty<'tcx>)
- -> Option<(Ty<'tcx>, ty::UnsizeKind<'tcx>)> {
- debug!("unsize_ty(a={:?}, ty_b={})", a, ty_b.repr(self.tcx()));
-
+ -> Option<(Ty<'tcx>, ty::UnsizeKind<'tcx>)>
+ {
let tcx = self.tcx();
- self.unpack_actual_value(ty_b, |b|
- match (&a.sty, &b.sty) {
- (&ty::ty_vec(t_a, Some(len)), &ty::ty_vec(_, None)) => {
- let ty = ty::mk_vec(tcx, t_a, None);
- Some((ty, ty::UnsizeLength(len)))
- }
- (&ty::ty_trait(ref data_a), &ty::ty_trait(ref data_b)) => {
- // For now, we only support upcasts from
- // `Foo+Send` to `Foo` (really, any time there are
- // fewer builtin bounds then before). These are
- // convenient because they don't require any sort
- // of change to the vtable at runtime.
- if data_a.bounds.builtin_bounds != data_b.bounds.builtin_bounds &&
- data_a.bounds.builtin_bounds.is_superset(&data_b.bounds.builtin_bounds)
- {
- let bounds_a1 = ty::ExistentialBounds {
- region_bound: data_a.bounds.region_bound,
- builtin_bounds: data_b.bounds.builtin_bounds,
- projection_bounds: data_a.bounds.projection_bounds.clone(),
- };
- let ty_a1 = ty::mk_trait(tcx, data_a.principal.clone(), bounds_a1);
- match self.fcx.infcx().try(|_| self.subtype(ty_a1, ty_b)) {
- Ok(_) => Some((ty_b, ty::UnsizeUpcast(ty_b))),
- Err(_) => None,
- }
- } else {
- None
+ self.unpack_actual_value(ty_a, |a| {
+ self.unpack_actual_value(ty_b, |b| {
+ debug!("unsize_ty(a={}, b={})", a.repr(self.tcx()), b.repr(self.tcx()));
+ match (&a.sty, &b.sty) {
+ (&ty::ty_vec(t_a, Some(len)), &ty::ty_vec(_, None)) => {
+ let ty = ty::mk_vec(tcx, t_a, None);
+ Some((ty, ty::UnsizeLength(len)))
}
- }
- (_, &ty::ty_trait(ref data)) => {
- Some((ty_b, ty::UnsizeVtable(ty::TyTrait { principal: data.principal.clone(),
- bounds: data.bounds.clone() },
- ty_a)))
- }
- (&ty::ty_struct(did_a, substs_a), &ty::ty_struct(did_b, substs_b))
- if did_a == did_b => {
- debug!("unsizing a struct");
- // Try unsizing each type param in turn to see if we end up with ty_b.
- let ty_substs_a = substs_a.types.get_slice(subst::TypeSpace);
- let ty_substs_b = substs_b.types.get_slice(subst::TypeSpace);
- assert!(ty_substs_a.len() == ty_substs_b.len());
-
- let mut result = None;
- let tps = ty_substs_a.iter().zip(ty_substs_b.iter()).enumerate();
- for (i, (tp_a, tp_b)) in tps {
- if self.fcx.infcx().try(|_| self.subtype(*tp_a, *tp_b)).is_ok() {
- continue;
+ (&ty::ty_trait(ref data_a), &ty::ty_trait(ref data_b)) => {
+ // Upcasts permit two things:
+ //
+ // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo`
+ // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b`
+ //
+ // Note that neither of these changes requires any
+ // change at runtime. Eventually this will be
+ // generalized.
+ //
+ // We always upcast when we can because of reason
+ // #2 (region bounds).
+ if data_a.bounds.builtin_bounds.is_superset(&data_b.bounds.builtin_bounds) {
+ // construct a type `a1` which is a version of
+ // `a` using the upcast bounds from `b`
+ let bounds_a1 = ty::ExistentialBounds {
+ // From type b
+ region_bound: data_b.bounds.region_bound,
+ builtin_bounds: data_b.bounds.builtin_bounds,
+
+ // From type a
+ projection_bounds: data_a.bounds.projection_bounds.clone(),
+ };
+ let ty_a1 = ty::mk_trait(tcx, data_a.principal.clone(), bounds_a1);
+
+ // relate `a1` to `b`
+ let result = self.fcx.infcx().try(|_| {
+ // it's ok to upcast from Foo+'a to Foo+'b so long as 'a : 'b
+ try!(self.outlives(data_a.bounds.region_bound,
+ data_b.bounds.region_bound));
+ self.subtype(ty_a1, ty_b)
+ });
+
+ // if that was successful, we have a coercion
+ match result {
+ Ok(_) => Some((ty_b, ty::UnsizeUpcast(ty_b))),
+ Err(_) => None,
+ }
+ } else {
+ None
}
- match
- self.unpack_actual_value(
- *tp_a,
- |tp| self.unsize_ty(*tp_a, tp, *tp_b))
- {
- Some((new_tp, k)) => {
- // Check that the whole types match.
- let mut new_substs = substs_a.clone();
- new_substs.types.get_mut_slice(subst::TypeSpace)[i] = new_tp;
- let ty = ty::mk_struct(tcx, did_a, tcx.mk_substs(new_substs));
- if self.fcx.infcx().try(|_| self.subtype(ty, ty_b)).is_err() {
- debug!("Unsized type parameter '{}', but still \
- could not match types {} and {}",
- ppaux::ty_to_string(tcx, *tp_a),
- ppaux::ty_to_string(tcx, ty),
- ppaux::ty_to_string(tcx, ty_b));
- // We can only unsize a single type parameter, so
- // if we unsize one and it doesn't give us the
- // type we want, then we won't succeed later.
+ }
+ (_, &ty::ty_trait(ref data)) => {
+ Some((ty_b, ty::UnsizeVtable(ty::TyTrait {
+ principal: data.principal.clone(),
+ bounds: data.bounds.clone()
+ },
+ ty_a)))
+ }
+ (&ty::ty_struct(did_a, substs_a), &ty::ty_struct(did_b, substs_b))
+ if did_a == did_b => {
+ debug!("unsizing a struct");
+ // Try unsizing each type param in turn to see if we end up with ty_b.
+ let ty_substs_a = substs_a.types.get_slice(subst::TypeSpace);
+ let ty_substs_b = substs_b.types.get_slice(subst::TypeSpace);
+ assert!(ty_substs_a.len() == ty_substs_b.len());
+
+ let mut result = None;
+ let tps = ty_substs_a.iter().zip(ty_substs_b.iter()).enumerate();
+ for (i, (tp_a, tp_b)) in tps {
+ if self.fcx.infcx().try(|_| self.subtype(*tp_a, *tp_b)).is_ok() {
+ continue;
+ }
+ match self.unsize_ty(*tp_a, *tp_b) {
+ Some((new_tp, k)) => {
+ // Check that the whole types match.
+ let mut new_substs = substs_a.clone();
+ new_substs.types.get_mut_slice(subst::TypeSpace)[i] = new_tp;
+ let ty = ty::mk_struct(tcx, did_a, tcx.mk_substs(new_substs));
+ if self.fcx.infcx().try(|_| self.subtype(ty, ty_b)).is_err() {
+ debug!("Unsized type parameter '{}', but still \
+ could not match types {} and {}",
+ ppaux::ty_to_string(tcx, *tp_a),
+ ppaux::ty_to_string(tcx, ty),
+ ppaux::ty_to_string(tcx, ty_b));
+ // We can only unsize a single type parameter, so
+ // if we unsize one and it doesn't give us the
+ // type we want, then we won't succeed later.
+ break;
+ }
+
+ result = Some((ty, ty::UnsizeStruct(box k, i)));
break;
}
-
- result = Some((ty, ty::UnsizeStruct(box k, i)));
- break;
+ None => {}
}
- None => {}
}
+ result
}
- result
+ _ => None
}
- _ => None
- }
- )
+ })
+ })
}
fn coerce_from_fn_pointer(&self,
}
}
-// Checks that the type `actual` can be coerced to `expected`.
-pub fn coerce<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, sp: Span,
- expected: Ty<'tcx>, expr: &ast::Expr) {
+// Checks that the type of `expr` can be coerced to `expected`.
+pub fn coerce<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
+ sp: Span,
+ expected: Ty<'tcx>,
+ expr: &ast::Expr) {
let expr_ty = fcx.expr_ty(expr);
debug!("demand::coerce(expected = {}, expr_ty = {})",
expected.repr(fcx.ccx.tcx),
};
// this closure doesn't implement the right kind of `Fn` trait
- if closure_kind != kind {
+ if !closure_kind.extends(kind) {
continue;
}
// def-id of the closure, so that once we decide, we can easily go
// back and process them.
deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolutionHandler<'tcx>>>>,
+
+ deferred_cast_checks: RefCell<Vec<CastCheck<'tcx>>>,
}
trait DeferredCallResolution<'tcx> {
type DeferredCallResolutionHandler<'tcx> = Box<DeferredCallResolution<'tcx>+'tcx>;
+/// Reifies a cast check to be checked once we have full type information for
+/// a function context.
+struct CastCheck<'tcx> {
+ expr: ast::Expr,
+ expr_ty: Ty<'tcx>,
+ cast_ty: Ty<'tcx>,
+ span: Span,
+}
+
/// When type-checking an expression, we propagate downward
/// whatever type hint we are able in the form of an `Expectation`.
#[derive(Copy)]
substs: &subst::Substs<'tcx>)
-> ty::ClosureTy<'tcx>
{
- self.inh.closure_tys.borrow()[def_id].subst(self.tcx(), substs)
+ self.inh.closure_tys.borrow().get(&def_id).unwrap().subst(self.tcx(), substs)
}
fn closure_upvars(&self,
fn_sig_map: RefCell::new(NodeMap()),
fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
deferred_call_resolutions: RefCell::new(DefIdMap()),
+ deferred_cast_checks: RefCell::new(Vec::new()),
}
}
vtable::select_all_fcx_obligations_and_apply_defaults(&fcx);
upvar::closure_analyze_fn(&fcx, fn_id, decl, body);
vtable::select_all_fcx_obligations_or_error(&fcx);
+ fcx.check_casts();
regionck::regionck_fn(&fcx, fn_id, fn_span, decl, body);
writeback::resolve_type_vars_in_fn(&fcx, decl, body);
}
debug!("Local variable {} is assigned type {}",
self.fcx.pat_to_string(&*local.pat),
self.fcx.infcx().ty_to_string(
- self.fcx.inh.locals.borrow()[local.id].clone()));
+ self.fcx.inh.locals.borrow().get(&local.id).unwrap().clone()));
visit::walk_local(self, local);
}
debug!("Pattern binding {} is assigned to {} with type {}",
token::get_ident(path1.node),
self.fcx.infcx().ty_to_string(
- self.fcx.inh.locals.borrow()[p.id].clone()),
+ self.fcx.inh.locals.borrow().get(&p.id).unwrap().clone()),
var_ty.repr(self.fcx.tcx()));
}
}
}
-fn check_cast_inner<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
- span: Span,
- t_1: Ty<'tcx>,
- t_e: Ty<'tcx>,
- e: &ast::Expr) {
+fn check_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, cast: &CastCheck<'tcx>) {
fn cast_through_integer_err<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
span: Span,
t_1: Ty<'tcx>,
}, t_e, None);
}
+ let span = cast.span;
+ let e = &cast.expr;
+ let t_e = structurally_resolved_type(fcx, span, cast.expr_ty);
+ let t_1 = structurally_resolved_type(fcx, span, cast.cast_ty);
+
+ // Check for trivial casts.
+ if !ty::type_has_ty_infer(t_1) {
+ if let Ok(()) = coercion::mk_assignty(fcx, e, t_e, t_1) {
+ if ty::type_is_numeric(t_1) && ty::type_is_numeric(t_e) {
+ fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_NUMERIC_CASTS,
+ e.id,
+ span,
+ format!("trivial numeric cast: `{}` as `{}`",
+ fcx.infcx().ty_to_string(t_e),
+ fcx.infcx().ty_to_string(t_1)));
+ } else {
+ fcx.tcx().sess.add_lint(lint::builtin::TRIVIAL_CASTS,
+ e.id,
+ span,
+ format!("trivial cast: `{}` as `{}`",
+ fcx.infcx().ty_to_string(t_e),
+ fcx.infcx().ty_to_string(t_1)));
+ }
+ return;
+ }
+ }
+
let t_e_is_bare_fn_item = ty::type_is_bare_fn_item(t_e);
let t_e_is_scalar = ty::type_is_scalar(t_e);
let t_e_is_integral = ty::type_is_integral(t_e);
let t_1_is_trivial = t_1_is_scalar && !t_1_is_char && !t_1_is_bare_fn;
if t_e_is_bare_fn_item && t_1_is_bare_fn {
- demand::coerce(fcx, e.span, t_1, &*e);
+ demand::coerce(fcx, e.span, t_1, &e);
} else if t_1_is_char {
let t_e = fcx.infcx().shallow_resolve(t_e);
if t_e.sty != ty::ty_uint(ast::TyU8) {
fcx.type_error_message(span, |actual| {
- format!("only `u8` can be cast as \
- `char`, not `{}`", actual)
+ format!("only `u8` can be cast as `char`, not `{}`", actual)
}, t_e, None);
}
} else if t_1.sty == ty::ty_bool {
span_err!(fcx.tcx().sess, span, E0054,
- "cannot cast as `bool`, compare with zero instead");
+ "cannot cast as `bool`, compare with zero instead");
} else if t_1_is_float && (t_e_is_scalar || t_e_is_c_enum) && !(
t_e_is_integral || t_e_is_float || t_e.sty == ty::ty_bool) {
// Casts to float must go through an integer or boolean
/* this case is allowed */
}
_ => {
- demand::coerce(fcx, e.span, t_1, &*e);
+ demand::coerce(fcx, e.span, t_1, &e);
}
}
} else if !(t_e_is_scalar && t_1_is_trivial) {
}
}
-fn check_cast<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
- cast_expr: &ast::Expr,
- e: &'tcx ast::Expr,
- t: &ast::Ty) {
- let id = cast_expr.id;
- let span = cast_expr.span;
-
- // Find the type of `e`. Supply hints based on the type we are casting to,
- // if appropriate.
- let t_1 = fcx.to_ty(t);
- let t_1 = structurally_resolved_type(fcx, span, t_1);
-
- check_expr_with_expectation(fcx, e, ExpectCastableToType(t_1));
-
- let t_e = fcx.expr_ty(e);
-
- debug!("t_1={}", fcx.infcx().ty_to_string(t_1));
- debug!("t_e={}", fcx.infcx().ty_to_string(t_e));
-
- if ty::type_is_error(t_e) {
- fcx.write_error(id);
- return
- }
-
- if !fcx.type_is_known_to_be_sized(t_1, cast_expr.span) {
- report_cast_to_unsized_type(fcx, span, t.span, e.span, t_1, t_e, id);
- return
- }
-
- if ty::type_is_trait(t_1) {
- // This will be looked up later on.
- vtable::check_object_cast(fcx, cast_expr, e, t_1);
- fcx.write_ty(id, t_1);
- return
- }
-
- let t_1 = structurally_resolved_type(fcx, span, t_1);
- let t_e = structurally_resolved_type(fcx, span, t_e);
-
- check_cast_inner(fcx, span, t_1, t_e, e);
- fcx.write_ty(id, t_1);
-}
-
impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> {
fn tcx(&self) -> &ty::ctxt<'tcx> { self.ccx.tcx }
}
pub fn tag(&self) -> String {
- format!("{:?}", self as *const FnCtxt)
+ let self_ptr: *const FnCtxt = self;
+ format!("{:?}", self_ptr)
}
pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
self.inh.node_types.borrow_mut().insert(node_id, ty);
}
- pub fn write_object_cast(&self,
- key: ast::NodeId,
- trait_ref: ty::PolyTraitRef<'tcx>) {
- debug!("write_object_cast key={} trait_ref={}",
- key, trait_ref.repr(self.tcx()));
- self.inh.object_cast_map.borrow_mut().insert(key, trait_ref);
- }
-
pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::ItemSubsts<'tcx>) {
if !substs.substs.is_noop() {
debug!("write_substs({}, {}) in fcx {}",
o_field.map(|f| ty::lookup_field_type(self.tcx(), class_id, f.id, substs))
.map(|t| self.normalize_associated_types_in(span, &t))
}
+
+ fn check_casts(&self) {
+ let mut deferred_cast_checks = self.inh.deferred_cast_checks.borrow_mut();
+ for check in deferred_cast_checks.iter() {
+ check_cast(self, check);
+ }
+
+ deferred_cast_checks.clear();
+ }
}
impl<'a, 'tcx> RegionScope for FnCtxt<'a, 'tcx> {
let mut missing_fields = Vec::new();
for class_field in field_types {
let name = class_field.name;
- let (_, seen) = class_field_map[name];
+ let (_, seen) = *class_field_map.get(&name).unwrap();
if !seen {
missing_fields.push(
format!("`{}`", &token::get_name(name)))
if let ast::TyFixedLengthVec(_, ref count_expr) = t.node {
check_expr_with_hint(fcx, &**count_expr, tcx.types.uint);
}
- check_cast(fcx, expr, &**e, &**t);
+
+ // Find the type of `e`. Supply hints based on the type we are casting to,
+ // if appropriate.
+ let t_1 = fcx.to_ty(t);
+ let t_1 = structurally_resolved_type(fcx, expr.span, t_1);
+ check_expr_with_expectation(fcx, e, ExpectCastableToType(t_1));
+ let t_e = fcx.expr_ty(e);
+
+ // Eagerly check for some obvious errors.
+ if ty::type_is_error(t_e) {
+ fcx.write_error(id);
+ } else if !fcx.type_is_known_to_be_sized(t_1, expr.span) {
+ report_cast_to_unsized_type(fcx, expr.span, t.span, e.span, t_1, t_e, id);
+ } else {
+ // Write a type for the whole expression, assuming everything is going
+ // to work out Ok.
+ fcx.write_ty(id, t_1);
+
+ // Defer other checks until we're done type checking.
+ let mut deferred_cast_checks = fcx.inh.deferred_cast_checks.borrow_mut();
+ deferred_cast_checks.push(CastCheck {
+ expr: (**e).clone(),
+ expr_ty: t_e,
+ cast_ty: t_1,
+ span: expr.span,
+ });
+ }
}
ast::ExprVec(ref args) => {
let uty = expected.to_option(fcx).and_then(|uty| {
}
pub fn check_decl_initializer<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
- nid: ast::NodeId,
+ local: &'tcx ast::Local,
init: &'tcx ast::Expr)
{
- let local_ty = fcx.local_ty(init.span, nid);
- check_expr_coercable_to_type(fcx, init, local_ty)
+ let ref_bindings = fcx.tcx().pat_contains_ref_binding(&local.pat);
+
+ let local_ty = fcx.local_ty(init.span, local.id);
+ if !ref_bindings {
+ check_expr_coercable_to_type(fcx, init, local_ty)
+ } else {
+ // Somewhat subtle: if we have a `ref` binding in the pattern,
+ // we want to avoid introducing coercions for the RHS. This is
+ // both because it helps preserve sanity and, in the case of
+ // ref mut, for soundness (issue #23116). In particular, in
+ // the latter case, we need to be clear that the type of the
+ // referent for the reference that results is *equal to* the
+ // type of the lvalue it is referencing, and not some
+ // supertype thereof.
+ check_expr(fcx, init);
+ let init_ty = fcx.expr_ty(init);
+ demand::eqtype(fcx, init.span, init_ty, local_ty);
+ };
}
pub fn check_decl_local<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, local: &'tcx ast::Local) {
fcx.write_ty(local.id, t);
if let Some(ref init) = local.init {
- check_decl_initializer(fcx, local.id, &**init);
+ check_decl_initializer(fcx, local, &**init);
let init_ty = fcx.expr_ty(&**init);
if ty::type_is_error(init_ty) {
fcx.write_ty(local.id, init_ty);
let inh = static_inherited_fields(ccx);
let rty = ty::node_id_to_type(ccx.tcx, id);
let fcx = blank_fn_ctxt(ccx, &inh, ty::FnConverging(rty), e.id);
- let declty = (*fcx.ccx.tcx.tcache.borrow())[local_def(id)].ty;
+ let declty = fcx.ccx.tcx.tcache.borrow().get(&local_def(id)).unwrap().ty;
check_const_with_ty(&fcx, sp, e, declty);
}
check_expr_with_hint(fcx, e, declty);
demand::coerce(fcx, e.span, declty, e);
vtable::select_all_fcx_obligations_or_error(fcx);
+ fcx.check_casts();
regionck::regionck_expr(fcx, e);
writeback::resolve_type_vars_in_expr(fcx, e);
}
ty: attr::IntType,
disr: ty::Disr) -> bool {
fn uint_in_range(ccx: &CrateCtxt, ty: ast::UintTy, disr: ty::Disr) -> bool {
+ #![allow(trivial_numeric_casts)]
+
match ty {
ast::TyU8 => disr as u8 as Disr == disr,
ast::TyU16 => disr as u16 as Disr == disr,
id: ast::NodeId,
hint: attr::ReprAttr)
-> Vec<Rc<ty::VariantInfo<'tcx>>> {
+ #![allow(trivial_numeric_casts)]
use std::num::Int;
let rty = ty::node_id_to_type(ccx.tcx, id);
mutbl: ast::MutImmutable
}))
}
- "copy_memory" | "copy_nonoverlapping_memory" |
+ "copy" | "copy_nonoverlapping" |
"volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
(1,
vec!(
),
ty::mk_nil(tcx))
}
- "set_memory" | "volatile_set_memory" => {
+ "write_bytes" | "volatile_set_memory" => {
(1,
vec!(
ty::mk_ptr(tcx, ty::mt {
let closure_def_id = ast_util::local_def(closure_id);
let mut closure_kinds = self.fcx.inh.closure_kinds.borrow_mut();
- let existing_kind = closure_kinds[closure_def_id];
+ let existing_kind = *closure_kinds.get(&closure_def_id).unwrap();
debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
closure_id, existing_kind, new_kind);
// except according to those terms.
use check::{FnCtxt};
-use check::demand;
use middle::traits::{self, ObjectSafetyViolation, MethodViolationCode};
use middle::traits::{Obligation, ObligationCause};
use middle::traits::report_fulfillment_errors;
use util::nodemap::FnvHashSet;
use util::ppaux::{Repr, UserString};
-pub fn check_object_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
- cast_expr: &ast::Expr,
- source_expr: &ast::Expr,
- target_object_ty: Ty<'tcx>)
-{
- let tcx = fcx.tcx();
- debug!("check_object_cast(cast_expr={}, target_object_ty={})",
- cast_expr.repr(tcx),
- target_object_ty.repr(tcx));
-
- // Look up vtables for the type we're casting to,
- // passing in the source and target type. The source
- // must be a pointer type suitable to the object sigil,
- // e.g.: `&x as &Trait` or `box x as Box<Trait>`
-
- // First, construct a fresh type that we can feed into `<expr>`
- // within `<expr> as <type>` to inform type inference (e.g. to
- // tell it that we are expecting a `Box<_>` or an `&_`).
- let fresh_ty = fcx.infcx().next_ty_var();
- let (object_trait_ty, source_expected_ty) = match target_object_ty.sty {
- ty::ty_uniq(object_trait_ty) => {
- (object_trait_ty, ty::mk_uniq(fcx.tcx(), fresh_ty))
- }
- ty::ty_rptr(target_region, ty::mt { ty: object_trait_ty,
- mutbl: target_mutbl }) => {
- (object_trait_ty,
- ty::mk_rptr(fcx.tcx(),
- target_region, ty::mt { ty: fresh_ty,
- mutbl: target_mutbl }))
- }
- _ => {
- fcx.tcx().sess.span_bug(source_expr.span, "expected object type");
- }
- };
-
- let source_ty = fcx.expr_ty(source_expr);
- debug!("check_object_cast pre unify source_ty={}", source_ty.repr(tcx));
-
- // This ensures that the source_ty <: source_expected_ty, which
- // will ensure e.g. that &'a T <: &'b T when doing `&'a T as &'b Trait`
- //
- // FIXME (pnkfelix): do we need to use suptype_with_fn in order to
- // override the error message emitted when the types do not work
- // out in the manner desired?
- demand::suptype(fcx, source_expr.span, source_expected_ty, source_ty);
-
- debug!("check_object_cast postunify source_ty={}", source_ty.repr(tcx));
-
- let object_trait = object_trait(&object_trait_ty);
-
- // Ensure that if Ptr<T> is cast to Ptr<Trait>, then T : Trait.
- push_cast_obligation(fcx, cast_expr, object_trait, fresh_ty);
- check_object_safety(tcx, object_trait, source_expr.span);
-
- fn object_trait<'a, 'tcx>(t: &'a Ty<'tcx>) -> &'a ty::TyTrait<'tcx> {
- match t.sty {
- ty::ty_trait(ref ty_trait) => &**ty_trait,
- _ => panic!("expected ty_trait")
- }
- }
-
- fn push_cast_obligation<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
- cast_expr: &ast::Expr,
- object_trait: &ty::TyTrait<'tcx>,
- referent_ty: Ty<'tcx>) {
- let object_trait_ref =
- register_object_cast_obligations(fcx,
- cast_expr.span,
- object_trait,
- referent_ty);
-
- // Finally record the object_trait_ref for use during trans
- // (it would prob be better not to do this, but it's just kind
- // of a pain to have to reconstruct it).
- fcx.write_object_cast(cast_expr.id, object_trait_ref);
- }
-}
// Check that a trait is 'object-safe'. This should be checked whenever a trait object
// is created (by casting or coercion, etc.). A trait is object-safe if all its
fn get_self_type_for_implementation(&self, impl_did: DefId)
-> TypeScheme<'tcx> {
- self.crate_context.tcx.tcache.borrow()[impl_did].clone()
+ self.crate_context.tcx.tcache.borrow().get(&impl_did).unwrap().clone()
}
// Converts an implementation in the AST to a vector of items.
};
for &impl_did in &*trait_impls.borrow() {
- let items = &(*impl_items)[impl_did];
+ let items = impl_items.get(&impl_did).unwrap();
if items.len() < 1 {
// We'll error out later. For now, just don't ICE.
continue;
tcx: &'cx ty::ctxt<'tcx>
}
-impl<'cx, 'tcx,'v> visit::Visitor<'v> for UnsafetyChecker<'cx, 'tcx> {
- fn visit_item(&mut self, item: &'v ast::Item) {
- match item.node {
- ast::ItemImpl(unsafety, polarity, _, _, _, _) => {
- match ty::impl_trait_ref(self.tcx, ast_util::local_def(item.id)) {
- None => {
- // Inherent impl.
- match unsafety {
- ast::Unsafety::Normal => { /* OK */ }
- ast::Unsafety::Unsafe => {
- span_err!(self.tcx.sess, item.span, E0197,
- "inherent impls cannot be declared as unsafe");
- }
- }
+impl<'cx, 'tcx, 'v> UnsafetyChecker<'cx, 'tcx> {
+ fn check_unsafety_coherence(&mut self, item: &'v ast::Item,
+ unsafety: ast::Unsafety,
+ polarity: ast::ImplPolarity) {
+ match ty::impl_trait_ref(self.tcx, ast_util::local_def(item.id)) {
+ None => {
+ // Inherent impl.
+ match unsafety {
+ ast::Unsafety::Normal => { /* OK */ }
+ ast::Unsafety::Unsafe => {
+ span_err!(self.tcx.sess, item.span, E0197,
+ "inherent impls cannot be declared as unsafe");
}
+ }
+ }
- Some(trait_ref) => {
- let trait_def = ty::lookup_trait_def(self.tcx, trait_ref.def_id);
- match (trait_def.unsafety, unsafety, polarity) {
- (ast::Unsafety::Unsafe,
- ast::Unsafety::Unsafe, ast::ImplPolarity::Negative) => {
- span_err!(self.tcx.sess, item.span, E0198,
- "negative implementations are not unsafe");
- }
+ Some(trait_ref) => {
+ let trait_def = ty::lookup_trait_def(self.tcx, trait_ref.def_id);
+ match (trait_def.unsafety, unsafety, polarity) {
+ (ast::Unsafety::Unsafe,
+ ast::Unsafety::Unsafe, ast::ImplPolarity::Negative) => {
+ span_err!(self.tcx.sess, item.span, E0198,
+ "negative implementations are not unsafe");
+ }
- (ast::Unsafety::Normal, ast::Unsafety::Unsafe, _) => {
- span_err!(self.tcx.sess, item.span, E0199,
- "implementing the trait `{}` is not unsafe",
- trait_ref.user_string(self.tcx));
- }
+ (ast::Unsafety::Normal, ast::Unsafety::Unsafe, _) => {
+ span_err!(self.tcx.sess, item.span, E0199,
+ "implementing the trait `{}` is not unsafe",
+ trait_ref.user_string(self.tcx));
+ }
- (ast::Unsafety::Unsafe,
- ast::Unsafety::Normal, ast::ImplPolarity::Positive) => {
- span_err!(self.tcx.sess, item.span, E0200,
- "the trait `{}` requires an `unsafe impl` declaration",
- trait_ref.user_string(self.tcx));
- }
+ (ast::Unsafety::Unsafe,
+ ast::Unsafety::Normal, ast::ImplPolarity::Positive) => {
+ span_err!(self.tcx.sess, item.span, E0200,
+ "the trait `{}` requires an `unsafe impl` declaration",
+ trait_ref.user_string(self.tcx));
+ }
- (ast::Unsafety::Unsafe,
- ast::Unsafety::Normal, ast::ImplPolarity::Negative) |
- (ast::Unsafety::Unsafe,
- ast::Unsafety::Unsafe, ast::ImplPolarity::Positive) |
- (ast::Unsafety::Normal, ast::Unsafety::Normal, _) => {
- /* OK */
- }
- }
+ (ast::Unsafety::Unsafe,
+ ast::Unsafety::Normal, ast::ImplPolarity::Negative) |
+ (ast::Unsafety::Unsafe,
+ ast::Unsafety::Unsafe, ast::ImplPolarity::Positive) |
+ (ast::Unsafety::Normal, ast::Unsafety::Normal, _) => {
+ /* OK */
}
}
}
+ }
+ }
+}
+
+impl<'cx, 'tcx,'v> visit::Visitor<'v> for UnsafetyChecker<'cx, 'tcx> {
+ fn visit_item(&mut self, item: &'v ast::Item) {
+ match item.node {
+ ast::ItemDefaultImpl(unsafety, _) => {
+ self.check_unsafety_coherence(item, unsafety, ast::ImplPolarity::Positive);
+ }
+ ast::ItemImpl(unsafety, polarity, _, _, _, _) => {
+ self.check_unsafety_coherence(item, unsafety, polarity);
+ }
_ => { }
}
fn method_ty(&self, method_id: ast::NodeId) -> Rc<ty::Method<'tcx>> {
let def_id = local_def(method_id);
- match self.tcx.impl_or_trait_items.borrow()[def_id] {
+ match *self.tcx.impl_or_trait_items.borrow().get(&def_id).unwrap() {
ty::MethodTraitItem(ref mty) => mty.clone(),
ty::TypeTraitItem(..) => {
self.tcx.sess.bug(&format!("method with id {} has the wrong type", method_id));
-> bool
{
if let ast::TyPath(None, _) = ast_ty.node {
- let path_res = tcx.def_map.borrow()[ast_ty.id];
+ let path_res = *tcx.def_map.borrow().get(&ast_ty.id).unwrap();
match path_res.base_def {
def::DefSelfTy(node_id) =>
path_res.depth == 0 && node_id == param_id,
}
}
-fn convert_associated_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
+fn as_refsociated_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
container: ImplOrTraitItemContainer,
ident: ast::Ident,
id: ast::NodeId,
&enum_definition.variants);
},
ast::ItemDefaultImpl(_, ref ast_trait_ref) => {
- let trait_ref = astconv::instantiate_trait_ref(&ccx.icx(&()),
- &ExplicitRscope,
- ast_trait_ref,
- Some(it.id),
- None,
- None);
+ let trait_ref =
+ astconv::instantiate_mono_trait_ref(&ccx.icx(&()),
+ &ExplicitRscope,
+ ast_trait_ref,
+ None);
ty::record_trait_has_default_impl(tcx, trait_ref.def_id);
+
+ tcx.impl_trait_refs.borrow_mut().insert(it.id, trait_ref);
}
ast::ItemImpl(_, _,
ref generics,
"associated items are not allowed in inherent impls");
}
- convert_associated_type(ccx, ImplContainer(local_def(it.id)),
+ as_refsociated_type(ccx, ImplContainer(local_def(it.id)),
impl_item.ident, impl_item.id, impl_item.vis);
let typ = ccx.icx(&ty_predicates).to_ty(&ExplicitRscope, ty);
}
}
- if let Some(ref trait_ref) = *opt_trait_ref {
- astconv::instantiate_trait_ref(&ccx.icx(&ty_predicates),
- &ExplicitRscope,
- trait_ref,
- Some(it.id),
- Some(selfty),
- None);
+ if let Some(ref ast_trait_ref) = *opt_trait_ref {
+ let trait_ref =
+ astconv::instantiate_mono_trait_ref(&ccx.icx(&ty_predicates),
+ &ExplicitRscope,
+ ast_trait_ref,
+ Some(selfty));
+
+ tcx.impl_trait_refs.borrow_mut().insert(it.id, trait_ref);
}
enforce_impl_ty_params_are_constrained(tcx,
match trait_item.node {
ast::MethodTraitItem(..) => {}
ast::TypeTraitItem(..) => {
- convert_associated_type(ccx, TraitContainer(local_def(it.id)),
+ as_refsociated_type(ccx, TraitContainer(local_def(it.id)),
trait_item.ident, trait_item.id, ast::Public);
}
}
tcx.predicates.borrow_mut().insert(local_def(ctor_id), predicates);
} else if struct_def.fields[0].node.kind.is_unnamed() {
// Tuple-like.
- let inputs: Vec<_> = struct_def.fields.iter().map(
- |field| (*tcx.tcache.borrow())[
- local_def(field.node.id)].ty).collect();
+ let inputs: Vec<_> =
+ struct_def.fields
+ .iter()
+ .map(|field| tcx.tcache.borrow().get(&local_def(field.node.id))
+ .unwrap()
+ .ty)
+ .collect();
let ctor_fn_ty = ty::mk_ctor_fn(tcx,
local_def(ctor_id),
&inputs[..],
builtin_bounds,
trait_bounds,
region_bounds
- } = astconv::partition_bounds(tcx, span, ast_bounds.as_slice());
+ } = astconv::partition_bounds(tcx, span, &ast_bounds);
let mut projection_bounds = Vec::new();
#![feature(collections)]
#![feature(core)]
#![feature(int_uint)]
-#![feature(std_misc)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
let src = match cx.input {
Input::File(ref path) => path.clone(),
- Input::Str(_) => PathBuf::new("") // FIXME: this is wrong
+ Input::Str(_) => PathBuf::new() // FIXME: this is wrong
};
Crate {
/// For parameterized types, so the consumer of the JSON don't go
/// looking for types which don't exist anywhere.
Generic(String),
- /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
+ /// Primitives are the fixed-size numeric types (plus int/uint/float), char,
+ /// arrays, slices, and tuples.
Primitive(PrimitiveType),
/// extern "ABI" fn
BareFunction(Box<BareFunctionDecl>),
Bool,
Str,
Slice,
+ Array,
PrimitiveTuple,
}
"str" => Some(Str),
"f32" => Some(F32),
"f64" => Some(F64),
+ "array" => Some(Array),
"slice" => Some(Slice),
"tuple" => Some(PrimitiveTuple),
_ => None,
Str => "str",
Bool => "bool",
Char => "char",
+ Array => "array",
Slice => "slice",
PrimitiveTuple => "tuple",
}
macro_rules! load_or_return {
($input: expr, $cant_read: expr, $not_utf8: expr) => {
{
- let input = PathBuf::new($input);
+ let input = PathBuf::from(&$input[..]);
match ::externalfiles::load_string(&input) {
Err(e) => {
let _ = writeln!(&mut io::stderr(),
if ast_util::is_local(did) || cache.inlined.contains(&did) {
Some(repeat("../").take(loc.len()).collect::<String>())
} else {
- match cache.extern_locations[did.krate] {
+ match cache.extern_locations[&did.krate] {
render::Remote(ref s) => Some(s.to_string()),
render::Local => {
Some(repeat("../").take(loc.len()).collect::<String>())
needs_termination = true;
}
Some(&cnum) => {
- let path = &m.paths[ast::DefId {
+ let path = &m.paths[&ast::DefId {
krate: cnum,
node: ast::CRATE_NODE_ID,
}];
- let loc = match m.extern_locations[cnum] {
+ let loc = match m.extern_locations[&cnum] {
render::Remote(ref s) => Some(s.to_string()),
render::Local => {
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
primitive_link(f, clean::Slice, &format!("[{}]", **t))
}
clean::FixedVector(ref t, ref s) => {
- primitive_link(f, clean::Slice,
+ primitive_link(f, clean::PrimitiveType::Array,
&format!("[{}; {}]", **t, *s))
}
clean::Bottom => f.write_str("!"),
stripped_filtered_line(l).unwrap_or(l)
}).collect::<Vec<&str>>().connect("\n");
let krate = krate.as_ref().map(|s| &**s);
- let test = test::maketest(&test, krate, false, false);
+ let test = test::maketest(&test, krate, false, false, true);
s.push_str(&format!("<span class='rusttest'>{}</span>", Escape(&test)));
});
s.push_str(&highlight::highlight(&text,
};
(*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
= &mut opaque as *mut _ as *mut libc::c_void;
- (*renderer).blockcode = Some(block as blockcodefn);
- (*renderer).header = Some(header as headerfn);
+ (*renderer).blockcode = Some(block);
+ (*renderer).header = Some(header);
let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
hoedown_document_render(document, ob, s.as_ptr(),
unsafe {
let ob = hoedown_buffer_new(DEF_OUNIT);
let renderer = hoedown_html_renderer_new(0, 0);
- (*renderer).blockcode = Some(block as blockcodefn);
- (*renderer).header = Some(header as headerfn);
+ (*renderer).blockcode = Some(block);
+ (*renderer).header = Some(header);
(*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
= tests as *mut _ as *mut libc::c_void;
unsafe {
let ob = hoedown_buffer_new(DEF_OUNIT);
let mut plain_renderer: hoedown_renderer = ::std::mem::zeroed();
- let renderer = &mut plain_renderer as *mut hoedown_renderer;
+ let renderer: *mut hoedown_renderer = &mut plain_renderer;
(*renderer).opaque = ob as *mut libc::c_void;
- (*renderer).link = Some(link as linkfn);
- (*renderer).normal_text = Some(normal_text as normaltextfn);
+ (*renderer).link = Some(link);
+ (*renderer).normal_text = Some(normal_text);
let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
hoedown_document_render(document, ob, md.as_ptr(),
passes: HashSet<String>) -> io::Result<()> {
let src_root = match krate.src.parent() {
Some(p) => p.to_path_buf(),
- None => PathBuf::new(""),
+ None => PathBuf::new(),
};
let mut cx = Context {
dst: dst,
impl<'a> SourceCollector<'a> {
/// Renders the given filename into its corresponding HTML source file.
fn emit_source(&mut self, filename: &str) -> io::Result<()> {
- let p = PathBuf::new(filename);
+ let p = PathBuf::from(filename);
// If we couldn't open this file, then just returns because it
// probably means that it's some standard library macro thing and we
let mut fname = p.file_name().expect("source has no filename")
.to_os_string();
fname.push(".html");
- cur.push(&fname);
+ cur.push(&fname[..]);
let mut w = BufWriter::new(try!(File::create(&cur)));
let title = format!("{} -- source", cur.file_name().unwrap()
match item {
clean::Item{ attrs, inner: clean::ImplItem(i), .. } => {
use clean::{Primitive, Vector, ResolvedPath, BorrowedRef};
- use clean::{FixedVector, Slice, Tuple, PrimitiveTuple};
+ use clean::PrimitiveType::{Array, Slice, PrimitiveTuple};
+ use clean::{FixedVector, Tuple};
// extract relevant documentation for this impl
let dox = match attrs.into_iter().find(|a| {
Some(ast_util::local_def(p.to_node_id()))
}
- // In a DST world, we may only need
- // Vector/FixedVector, but for now we also pick up
- // borrowed references
- Vector(..) | FixedVector(..) |
- BorrowedRef{ type_: box Vector(..), .. } |
- BorrowedRef{ type_: box FixedVector(..), .. } =>
+ FixedVector(..) |
+ BorrowedRef { type_: box FixedVector(..), .. } =>
+ {
+ Some(ast_util::local_def(Array.to_node_id()))
+ }
+
+ // In a DST world, we may only need Vector, but for now we
+ // also pick up borrowed references
+ Vector(..) |
+ BorrowedRef{ type_: box Vector(..), .. } =>
{
Some(ast_util::local_def(Slice.to_node_id()))
}
// located, then we return `None`.
} else {
let cache = cache();
- let path = &cache.external_paths[self.item.def_id];
- let root = match cache.extern_locations[self.item.def_id.krate] {
+ let path = &cache.external_paths[&self.item.def_id];
+ let root = match cache.extern_locations[&self.item.def_id.krate] {
Remote(ref s) => s.to_string(),
Local => self.cx.root_path.clone(),
Unknown => return None,
path = if ast_util::is_local(it.def_id) {
cx.current.connect("/")
} else {
- let path = &cache.external_paths[it.def_id];
+ let path = &cache.external_paths[&it.def_id];
path[..path.len() - 1].connect("/")
},
ty = shortty(it).to_static_str(),
#![feature(file_path)]
#![feature(path_ext)]
#![feature(path_relative_from)]
+#![feature(convert)]
extern crate arena;
extern crate getopts;
extern crate serialize;
extern crate syntax;
extern crate "test" as testing;
+extern crate unicode;
#[macro_use] extern crate log;
extern crate "serialize" as rustc_serialize; // used by deriving
let should_test = matches.opt_present("test");
let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
- let output = matches.opt_str("o").map(|s| PathBuf::new(&s));
+ let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
let cfgs = matches.opt_strs("cfg");
let external_html = match ExternalHtml::load(
return test::run(input, cfgs, libs, externs, test_args, crate_name)
}
(false, true) => return markdown::render(input,
- output.unwrap_or(PathBuf::new("doc")),
+ output.unwrap_or(PathBuf::from("doc")),
&matches, &external_html,
!matches.opt_present("markdown-no-toc")),
(false, false) => {}
match matches.opt_str("w").as_ref().map(|s| &**s) {
Some("html") | None => {
match html::render::run(krate, &external_html,
- output.unwrap_or(PathBuf::new("doc")),
+ output.unwrap_or(PathBuf::from("doc")),
passes.into_iter().collect()) {
Ok(()) => {}
Err(e) => panic!("failed to generate documentation: {}", e),
}
Some("json") => {
match json_output(krate, json_plugins,
- output.unwrap_or(PathBuf::new("doc.json"))) {
+ output.unwrap_or(PathBuf::from("doc.json"))) {
Ok(()) => {}
Err(e) => panic!("failed to write json: {}", e),
}
let cfgs = matches.opt_strs("cfg");
let triple = matches.opt_str("target");
- let cr = PathBuf::new(cratefile);
+ let cr = PathBuf::from(cratefile);
info!("starting to run rustc");
let (tx, rx) = channel();
mut test_args: Vec<String>) -> int {
let input_str = load_or_return!(input, 1, 2);
- let mut collector = Collector::new(input.to_string(), libs, externs, true);
+ let mut collector = Collector::new(input.to_string(), libs, externs, true, false);
find_testable_code(&input_str, &mut collector);
test_args.insert(0, "rustdoctest".to_string());
testing::test_main(&test_args, collector.tests);
mut test_args: Vec<String>,
crate_name: Option<String>)
-> int {
- let input_path = PathBuf::new(input);
+ let input_path = PathBuf::from(input);
let input = config::Input::File(input_path.clone());
let sessopts = config::Options {
"rustdoc-test", None)
.expect("phase_2_configure_and_expand aborted in rustdoc!");
+ let inject_crate = should_inject_crate(&krate);
+
let ctx = core::DocContext {
krate: &krate,
maybe_typed: core::NotTyped(sess),
let mut collector = Collector::new(krate.name.to_string(),
libs,
externs,
- false);
+ false,
+ inject_crate);
collector.fold_crate(krate);
test_args.insert(0, "rustdoctest".to_string());
0
}
+// Look for #![doc(test(no_crate_inject))], used by crates in the std facade
+fn should_inject_crate(krate: &::syntax::ast::Crate) -> bool {
+ use syntax::attr::AttrMetaMethods;
+
+ let mut inject_crate = true;
+
+ for attr in &krate.attrs {
+ if attr.check_name("doc") {
+ for list in attr.meta_item_list().into_iter() {
+ for attr in list {
+ if attr.check_name("test") {
+ for list in attr.meta_item_list().into_iter() {
+ for attr in list {
+ if attr.check_name("no_crate_inject") {
+ inject_crate = false;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return inject_crate;
+}
+
#[allow(deprecated)]
fn runtest(test: &str, cratename: &str, libs: SearchPaths,
externs: core::Externs,
- should_panic: bool, no_run: bool, as_test_harness: bool) {
+ should_panic: bool, no_run: bool, as_test_harness: bool,
+ inject_crate: bool) {
// the test harness wants its own `main` & top level functions, so
// never wrap the test in `fn main() { ... }`
- let test = maketest(test, Some(cratename), true, as_test_harness);
+ let test = maketest(test, Some(cratename), true, as_test_harness,
+ inject_crate);
let input = config::Input::Str(test.to_string());
let sessopts = config::Options {
}
}
-pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main: bool) -> String {
+pub fn maketest(s: &str, cratename: Option<&str>, lints: bool,
+ dont_insert_main: bool, inject_crate: bool) -> String {
+ let (crate_attrs, everything_else) = partition_source(s);
+
let mut prog = String::new();
+
+ // First push any outer attributes from the example, assuming they
+ // are intended to be crate attributes.
+ prog.push_str(&crate_attrs);
+
if lints {
prog.push_str(r"
#![allow(unused_variables, unused_assignments, unused_mut, unused_attributes, dead_code)]
// Don't inject `extern crate std` because it's already injected by the
// compiler.
- if !s.contains("extern crate") && cratename != Some("std") {
+ if !s.contains("extern crate") && inject_crate {
match cratename {
Some(cratename) => {
if s.contains(cratename) {
}
}
if dont_insert_main || s.contains("fn main") {
- prog.push_str(s);
+ prog.push_str(&everything_else);
} else {
prog.push_str("fn main() {\n ");
- prog.push_str(&s.replace("\n", "\n "));
+ prog.push_str(&everything_else.replace("\n", "\n "));
prog.push_str("\n}");
}
+ info!("final test program: {}", prog);
+
return prog
}
+fn partition_source(s: &str) -> (String, String) {
+ use unicode::str::UnicodeStr;
+
+ let mut after_header = false;
+ let mut before = String::new();
+ let mut after = String::new();
+
+ for line in s.lines() {
+ let trimline = line.trim();
+ let header = trimline.is_whitespace() ||
+ trimline.starts_with("#![feature");
+ if !header || after_header {
+ after_header = true;
+ after.push_str(line);
+ after.push_str("\n");
+ } else {
+ before.push_str(line);
+ before.push_str("\n");
+ }
+ }
+
+ return (before, after);
+}
+
pub struct Collector {
pub tests: Vec<testing::TestDescAndFn>,
names: Vec<String>,
use_headers: bool,
current_header: Option<String>,
cratename: String,
+ inject_crate: bool
}
impl Collector {
pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
- use_headers: bool) -> Collector {
+ use_headers: bool, inject_crate: bool) -> Collector {
Collector {
tests: Vec::new(),
names: Vec::new(),
use_headers: use_headers,
current_header: None,
cratename: cratename,
+ inject_crate: inject_crate
}
}
pub fn add_test(&mut self, test: String,
- should_panic: bool, no_run: bool, should_ignore: bool, as_test_harness: bool) {
+ should_panic: bool, no_run: bool, should_ignore: bool,
+ as_test_harness: bool) {
let name = if self.use_headers {
let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
format!("{}_{}", s, self.cnt)
let libs = self.libs.clone();
let externs = self.externs.clone();
let cratename = self.cratename.to_string();
+ let inject_crate = self.inject_crate;
debug!("Creating test {}: {}", name, test);
self.tests.push(testing::TestDescAndFn {
desc: testing::TestDesc {
externs,
should_panic,
no_run,
- as_test_harness);
+ as_test_harness,
+ inject_crate);
}))
});
}
Some(tcx) => tcx,
None => return false
};
- let def = tcx.def_map.borrow()[id].def_id();
+ let def = tcx.def_map.borrow()[&id].def_id();
if !ast_util::is_local(def) { return false }
let analysis = match self.analysis {
Some(analysis) => analysis, None => return false
/// # Examples
///
/// ```
+ /// # #![feature(rustc_private)]
/// extern crate serialize;
/// use serialize::hex::ToHex;
///
/// This converts a string literal to hexadecimal and back.
///
/// ```
+ /// # #![feature(rustc_private)]
/// extern crate serialize;
/// use serialize::hex::{FromHex, ToHex};
///
}
}
+#[cfg(stage0)]
impl<'a> Index<&'a str> for Json {
type Output = Json;
}
}
+#[cfg(not(stage0))]
+impl<'a> Index<&'a str> for Json {
+ type Output = Json;
+
+ fn index(&self, idx: &'a str) -> &Json {
+ self.find(idx).unwrap()
+ }
+}
+
+#[cfg(stage0)]
impl Index<uint> for Json {
type Output = Json;
}
}
+#[cfg(not(stage0))]
+impl Index<uint> for Json {
+ type Output = Json;
+
+ fn index<'a>(&'a self, idx: uint) -> &'a Json {
+ match self {
+ &Json::Array(ref v) => &v[idx],
+ _ => panic!("can only index Json with uint if it is an array")
+ }
+ }
+}
+
/// The output of the streaming parser.
#[derive(PartialEq, Clone, Debug)]
pub enum JsonEvent {
macro_rules! to_json_impl_i64 {
($($t:ty), +) => (
$(impl ToJson for $t {
- fn to_json(&self) -> Json { Json::I64(*self as i64) }
+ fn to_json(&self) -> Json {
+ #![allow(trivial_numeric_casts)]
+ Json::I64(*self as i64)
+ }
})+
)
}
macro_rules! to_json_impl_u64 {
($($t:ty), +) => (
$(impl ToJson for $t {
- fn to_json(&self) -> Json { Json::U64(*self as u64) }
+ fn to_json(&self) -> Json {
+ #![allow(trivial_numeric_casts)]
+ Json::U64(*self as u64)
+ }
})+
)
}
#![feature(std_misc)]
#![feature(unicode)]
#![feature(str_char)]
-#![cfg_attr(test, feature(test))]
+#![feature(convert)]
+#![cfg_attr(test, feature(test, old_io))]
// test harness access
#[cfg(test)] extern crate test;
impl Decodable for path::PathBuf {
fn decode<D: Decoder>(d: &mut D) -> Result<path::PathBuf, D::Error> {
let bytes: String = try!(Decodable::decode(d));
- Ok(path::PathBuf::new(&bytes))
+ Ok(path::PathBuf::from(bytes))
}
}
--- /dev/null
+// Copyright 2015 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.
+
+//! The fixed-size array type (`[T; n]`).
+
+#![doc(primitive = "array")]
/// # Examples
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::collections::HashMap;
/// use std::collections::hash_map::RandomState;
///
/// # Examples
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::collections::HashMap;
/// use std::collections::hash_map::RandomState;
///
/// # Examples
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::collections::HashMap;
///
/// let mut a = HashMap::new();
/// Some(x) => *x = "b",
/// None => (),
/// }
- /// assert_eq!(map[1], "b");
+ /// assert_eq!(map[&1], "b");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
///
/// map.insert(37, "b");
/// assert_eq!(map.insert(37, "c"), Some("b"));
- /// assert_eq!(map[37], "c");
+ /// assert_eq!(map[&37], "c");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn insert(&mut self, k: K, v: V) -> Option<V> {
}
}
+#[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, Q: ?Sized, V, S> Index<Q> for HashMap<K, V, S>
where K: Eq + Hash + Borrow<Q>,
}
}
+#[cfg(not(stage0))]
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
+ where K: Eq + Hash + Borrow<Q>,
+ Q: Eq + Hash,
+ S: HashState,
+{
+ type Output = V;
+
+ #[inline]
+ fn index(&self, index: &Q) -> &V {
+ self.get(index).expect("no entry found for key")
+ }
+}
+
/// HashMap iterator.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter<'a, K: 'a, V: 'a> {
}
/// A view into a single occupied location in a HashMap.
-#[unstable(feature = "std_misc",
- reason = "precise API still being fleshed out")]
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
elem: FullBucket<K, V, &'a mut RawTable<K, V>>,
}
/// A view into a single empty location in a HashMap.
-#[unstable(feature = "std_misc",
- reason = "precise API still being fleshed out")]
+#[stable(feature = "rust1", since = "1.0.0")]
pub struct VacantEntry<'a, K: 'a, V: 'a> {
hash: SafeHash,
key: K,
}
/// A view into a single location in a map, which may be vacant or occupied.
-#[unstable(feature = "std_misc",
- reason = "precise API still being fleshed out")]
+#[stable(feature = "rust1", since = "1.0.0")]
pub enum Entry<'a, K: 'a, V: 'a> {
/// An occupied Entry.
+ #[stable(feature = "rust1", since = "1.0.0")]
Occupied(OccupiedEntry<'a, K, V>),
+
/// A vacant Entry.
+ #[stable(feature = "rust1", since = "1.0.0")]
Vacant(VacantEntry<'a, K, V>),
}
#[inline] fn len(&self) -> usize { self.inner.len() }
}
-#[unstable(feature = "std_misc",
- reason = "matches collection reform v2 specification, waiting for dust to settle")]
impl<'a, K, V> Entry<'a, K, V> {
/// Returns a mutable reference to the entry if occupied, or the VacantEntry if vacant.
+ #[unstable(feature = "std_misc",
+ reason = "will soon be replaced by or_insert")]
pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
match self {
Occupied(entry) => Ok(entry.into_mut()),
map.insert(2, 1);
map.insert(3, 4);
- assert_eq!(map[2], 1);
+ assert_eq!(map[&2], 1);
}
#[test]
map.insert(2, 1);
map.insert(3, 4);
- map[4];
+ map[&4];
}
#[test]
/// # Examples
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::collections::HashSet;
/// use std::collections::hash_map::RandomState;
///
/// # Examples
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::collections::HashSet;
/// use std::collections::hash_map::RandomState;
///
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::HashSet;
/// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
/// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::HashSet;
/// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
/// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::HashSet;
/// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
/// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::HashSet;
/// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
/// let b: HashSet<_> = [4, 2, 3, 4].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::HashSet;
///
/// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::HashSet;
///
/// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::HashSet;
///
/// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
/// # Examples
///
/// ```
+ /// # #![feature(core)]
/// use std::collections::HashSet;
///
/// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
}
}
+impl<'a, K> Clone for Iter<'a, K> {
+ fn clone(&self) -> Iter<'a, K> { Iter { iter: self.iter.clone() } }
+}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K> Iterator for Iter<'a, K> {
type Item = &'a K;
fn len(&self) -> usize { self.iter.len() }
}
+impl<'a, T, S> Clone for Intersection<'a, T, S> {
+ fn clone(&self) -> Intersection<'a, T, S> {
+ Intersection { iter: self.iter.clone(), ..*self }
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T, S> Iterator for Intersection<'a, T, S>
where T: Eq + Hash, S: HashState
}
}
+impl<'a, T, S> Clone for Difference<'a, T, S> {
+ fn clone(&self) -> Difference<'a, T, S> {
+ Difference { iter: self.iter.clone(), ..*self }
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T, S> Iterator for Difference<'a, T, S>
where T: Eq + Hash, S: HashState
}
}
+impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
+ fn clone(&self) -> SymmetricDifference<'a, T, S> {
+ SymmetricDifference { iter: self.iter.clone() }
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
where T: Eq + Hash, S: HashState
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
+impl<'a, T, S> Clone for Union<'a, T, S> {
+ fn clone(&self) -> Union<'a, T, S> { Union { iter: self.iter.clone() } }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T, S> Iterator for Union<'a, T, S>
where T: Eq + Hash, S: HashState
//! #### Counting the number of times each character in a string occurs
//!
//! ```
+//! # #![feature(collections)]
//! use std::collections::btree_map::{BTreeMap, Entry};
//!
//! let mut count = BTreeMap::new();
//! #### Tracking the inebriation of customers at a bar
//!
//! ```
+//! # #![feature(collections)]
//! use std::collections::btree_map::{BTreeMap, Entry};
//!
//! // A client of the bar. They have an id and a blood alcohol level.
use ffi::{OsString, AsOsStr};
use fmt;
use io;
-use path::{AsPath, PathBuf};
+use path::{Path, PathBuf};
use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering};
use sync::{StaticMutex, MUTEX_INIT};
use sys::os as os_imp;
/// println!("Successfully changed working directory to {}!", root.display());
/// ```
#[stable(feature = "env", since = "1.0.0")]
-pub fn set_current_dir<P: AsPath + ?Sized>(p: &P) -> io::Result<()> {
- os_imp::chdir(p.as_path())
+pub fn set_current_dir<P: AsRef<Path> + ?Sized>(p: &P) -> io::Result<()> {
+ os_imp::chdir(p.as_ref())
}
static ENV_LOCK: StaticMutex = MUTEX_INIT;
/// # Examples
///
/// ```
+/// # #![feature(convert)]
/// use std::env;
/// use std::path::PathBuf;
///
/// if let Some(path) = env::var_os("PATH") {
/// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
-/// paths.push(PathBuf::new("/home/xyz/bin"));
+/// paths.push(PathBuf::from("/home/xyz/bin"));
/// let new_path = env::join_paths(paths.iter()).unwrap();
/// env::set_var("PATH", &new_path);
/// }
fn split_paths_windows() {
fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
split_paths(unparsed).collect::<Vec<_>>() ==
- parsed.iter().map(|s| PathBuf::new(*s)).collect::<Vec<_>>()
+ parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
}
assert!(check_parse("", &mut [""]));
fn split_paths_unix() {
fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
split_paths(unparsed).collect::<Vec<_>>() ==
- parsed.iter().map(|s| PathBuf::new(*s)).collect::<Vec<_>>()
+ parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
}
assert!(check_parse("", &mut [""]));
#![unstable(feature = "std_misc")]
+use convert::Into;
use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
use error::{Error, FromError};
use fmt;
/// # Examples
///
/// ```no_run
+/// # #![feature(libc)]
/// # extern crate libc;
/// # fn main() {
/// use std::ffi::CString;
/// Inspecting a foreign C string
///
/// ```no_run
+/// # #![feature(libc)]
/// extern crate libc;
/// use std::ffi::CStr;
///
/// Passing a Rust-originating C string
///
/// ```no_run
+/// # #![feature(libc)]
/// extern crate libc;
/// use std::ffi::{CString, CStr};
///
/// A conversion trait used by the constructor of `CString` for types that can
/// be converted to a vector of bytes.
+#[deprecated(since = "1.0.0", reason = "use std::convert::Into<Vec<u8>> instead")]
+#[unstable(feature = "std_misc")]
pub trait IntoBytes {
/// Consumes this container, returning a vector of bytes.
fn into_bytes(self) -> Vec<u8>;
/// # Examples
///
/// ```no_run
+ /// # #![feature(libc)]
/// extern crate libc;
/// use std::ffi::CString;
///
/// internal 0 byte. The error returned will contain the bytes as well as
/// the position of the nul byte.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn new<T: IntoBytes>(t: T) -> Result<CString, NulError> {
- let bytes = t.into_bytes();
+ pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
+ let bytes = t.into();
match bytes.iter().position(|x| *x == 0) {
Some(i) => Err(NulError(i, bytes)),
None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
/// # Examples
///
/// ```no_run
+ /// # #![feature(libc)]
/// extern crate libc;
/// use std::ffi::CString;
///
/// # Examples
///
/// ```no_run
+ /// # #![feature(libc)]
/// # extern crate libc;
/// # fn main() {
/// use std::ffi::CStr;
slice::from_raw_parts(*(raw as *const _ as *const *const u8), len as usize)
}
+#[allow(deprecated)]
impl<'a> IntoBytes for &'a str {
fn into_bytes(self) -> Vec<u8> { self.as_bytes().to_vec() }
}
+#[allow(deprecated)]
impl<'a> IntoBytes for &'a [u8] {
fn into_bytes(self) -> Vec<u8> { self.to_vec() }
}
+#[allow(deprecated)]
impl IntoBytes for String {
fn into_bytes(self) -> Vec<u8> { self.into_bytes() }
}
+#[allow(deprecated)]
impl IntoBytes for Vec<u8> {
fn into_bytes(self) -> Vec<u8> { self }
}
impl OsString {
/// Constructs an `OsString` at no cost by consuming a `String`.
#[stable(feature = "rust1", since = "1.0.0")]
+ #[deprecated(since = "1.0.0", reason = "use `from` instead")]
pub fn from_string(s: String) -> OsString {
- OsString { inner: Buf::from_string(s) }
+ OsString::from(s)
}
/// Constructs an `OsString` by copying from a `&str` slice.
///
/// Equivalent to: `OsString::from_string(String::from_str(s))`.
#[stable(feature = "rust1", since = "1.0.0")]
+ #[deprecated(since = "1.0.0", reason = "use `from` instead")]
pub fn from_str(s: &str) -> OsString {
- OsString { inner: Buf::from_str(s) }
+ OsString::from(s)
}
/// Constructs a new empty `OsString`.
/// Extend the string with the given `&OsStr` slice.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn push<T: AsOsStr + ?Sized>(&mut self, s: &T) {
- self.inner.push_slice(&s.as_os_str().inner)
+ pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
+ self.inner.push_slice(&s.as_ref().inner)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl From<String> for OsString {
+ fn from(s: String) -> OsString {
+ OsString { inner: Buf::from_string(s) }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a String> for OsString {
+ fn from(s: &'a String) -> OsString {
+ OsString { inner: Buf::from_str(s) }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a str> for OsString {
+ fn from(s: &'a str) -> OsString {
+ OsString { inner: Buf::from_str(s) }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a OsStr> for OsString {
+ fn from(s: &'a OsStr) -> OsString {
+ OsString { inner: s.inner.to_owned() }
}
}
+#[cfg(stage0)]
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for OsString {
type Output = OsStr;
}
}
+#[cfg(not(stage0))]
+#[stable(feature = "rust1", since = "1.0.0")]
+impl ops::Index<ops::RangeFull> for OsString {
+ type Output = OsStr;
+
+ #[inline]
+ fn index(&self, _index: ops::RangeFull) -> &OsStr {
+ unsafe { mem::transmute(self.inner.as_slice()) }
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for OsString {
type Target = OsStr;
}
#[stable(feature = "rust1", since = "1.0.0")]
+#[deprecated(since = "1.0.0", reason = "trait is deprecated")]
impl<'a, T: AsOsStr + ?Sized> AsOsStr for &'a T {
fn as_os_str(&self) -> &OsStr {
(*self).as_os_str()
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+#[deprecated(since = "1.0.0", reason = "trait is deprecated")]
impl AsOsStr for OsStr {
fn as_os_str(&self) -> &OsStr {
self
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+#[deprecated(since = "1.0.0", reason = "trait is deprecated")]
impl AsOsStr for OsString {
fn as_os_str(&self) -> &OsStr {
&self[..]
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+#[deprecated(since = "1.0.0", reason = "trait is deprecated")]
impl AsOsStr for str {
fn as_os_str(&self) -> &OsStr {
OsStr::from_str(self)
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+#[deprecated(since = "1.0.0", reason = "trait is deprecated")]
impl AsOsStr for String {
fn as_os_str(&self) -> &OsStr {
OsStr::from_str(&self[..])
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<OsStr> for OsStr {
+ fn as_ref(&self) -> &OsStr {
+ self
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<OsStr> for OsString {
+ fn as_ref(&self) -> &OsStr {
+ self
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<OsStr> for str {
+ fn as_ref(&self) -> &OsStr {
+ OsStr::from_str(self)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<OsStr> for String {
+ fn as_ref(&self) -> &OsStr {
+ OsStr::from_str(&self[..])
+ }
+}
+
#[allow(deprecated)]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[deprecated(since = "1.0.0", reason = "trait is deprecated")]
impl AsOsStr for Path {
#[cfg(unix)]
fn as_os_str(&self) -> &OsStr {
use core::prelude::*;
use io::{self, Error, ErrorKind, SeekFrom, Seek, Read, Write};
-use path::{AsPath, Path, PathBuf};
+use path::{Path, PathBuf};
use sys::fs2 as fs_imp;
use sys_common::{AsInnerMut, FromInner, AsInner};
use vec::Vec;
///
/// This function will return an error if `path` does not already exist.
/// Other errors may also be returned according to `OpenOptions::open`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::fs::File;
+ ///
+ /// # fn foo() -> std::io::Result<()> {
+ /// let mut f = try!(File::open("foo.txt"));
+ /// # Ok(())
+ /// # }
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn open<P: AsPath>(path: P) -> io::Result<File> {
+ pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
OpenOptions::new().read(true).open(path)
}
/// and will truncate it if it does.
///
/// See the `OpenOptions::open` function for more details.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::fs::File;
+ ///
+ /// # fn foo() -> std::io::Result<()> {
+ /// let mut f = try!(File::create("foo.txt"));
+ /// # Ok(())
+ /// # }
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn create<P: AsPath>(path: P) -> io::Result<File> {
+ pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
OpenOptions::new().write(true).create(true).truncate(true).open(path)
}
///
/// This function will attempt to ensure that all in-core data reaches the
/// filesystem before returning.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::fs::File;
+ ///
+ /// # fn foo() -> std::io::Result<()> {
+ /// let mut f = try!(File::create("foo.txt"));
+ /// try!(f.write_all(b"Hello, world!"));
+ ///
+ /// try!(f.sync_all());
+ /// # Ok(())
+ /// # }
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn sync_all(&self) -> io::Result<()> {
self.inner.fsync()
///
/// Note that some platforms may simply implement this in terms of
/// `sync_all`.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::fs::File;
+ ///
+ /// # fn foo() -> std::io::Result<()> {
+ /// let mut f = try!(File::create("foo.txt"));
+ /// try!(f.write_all(b"Hello, world!"));
+ ///
+ /// try!(f.sync_data());
+ /// # Ok(())
+ /// # }
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn sync_data(&self) -> io::Result<()> {
self.inner.datasync()
/// be shrunk. If it is greater than the current file's size, then the file
/// will be extended to `size` and have all of the intermediate data filled
/// in with 0s.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::fs::File;
+ ///
+ /// # fn foo() -> std::io::Result<()> {
+ /// let mut f = try!(File::open("foo.txt"));
+ /// try!(f.set_len(0));
+ /// # Ok(())
+ /// # }
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn set_len(&self, size: u64) -> io::Result<()> {
self.inner.truncate(size)
}
/// Queries metadata about the underlying file.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// use std::fs::File;
+ ///
+ /// # fn foo() -> std::io::Result<()> {
+ /// let mut f = try!(File::open("foo.txt"));
+ /// let metadata = try!(f.metadata());
+ /// # Ok(())
+ /// # }
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn metadata(&self) -> io::Result<Metadata> {
self.inner.file_attr().map(Metadata)
/// permissions for
/// * Filesystem-level errors (full disk, etc)
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn open<P: AsPath>(&self, path: P) -> io::Result<File> {
- let path = path.as_path();
+ pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
+ let path = path.as_ref();
let inner = try!(fs_imp::File::open(path, &self.0));
Ok(File { path: path.to_path_buf(), inner: inner })
}
/// user lacks permissions to remove the file, or if some other filesystem-level
/// error occurs.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn remove_file<P: AsPath>(path: P) -> io::Result<()> {
- fs_imp::unlink(path.as_path())
+pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
+ fs_imp::unlink(path.as_ref())
}
/// Given a path, query the file system to get information about a file,
/// permissions to perform a `metadata` call on the given `path` or if there
/// is no entry in the filesystem at the provided path.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn metadata<P: AsPath>(path: P) -> io::Result<Metadata> {
- fs_imp::stat(path.as_path()).map(Metadata)
+pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
+ fs_imp::stat(path.as_ref()).map(Metadata)
}
/// Rename a file or directory to a new name.
/// reside on separate filesystems, or if some other intermittent I/O error
/// occurs.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn rename<P: AsPath, Q: AsPath>(from: P, to: Q) -> io::Result<()> {
- fs_imp::rename(from.as_path(), to.as_path())
+pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
+ fs_imp::rename(from.as_ref(), to.as_ref())
}
/// Copies the contents of one file to another. This function will also
/// * The current process does not have the permission rights to access
/// `from` or write `to`
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn copy<P: AsPath, Q: AsPath>(from: P, to: Q) -> io::Result<u64> {
- let from = from.as_path();
- let to = to.as_path();
+pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
+ let from = from.as_ref();
+ let to = to.as_ref();
if !from.is_file() {
return Err(Error::new(ErrorKind::InvalidInput,
"the source path is not an existing file",
/// The `dst` path will be a link pointing to the `src` path. Note that systems
/// often require these two paths to both be located on the same filesystem.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn hard_link<P: AsPath, Q: AsPath>(src: P, dst: Q) -> io::Result<()> {
- fs_imp::link(src.as_path(), dst.as_path())
+pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
+ fs_imp::link(src.as_ref(), dst.as_ref())
}
/// Creates a new soft link on the filesystem.
///
/// The `dst` path will be a soft link pointing to the `src` path.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn soft_link<P: AsPath, Q: AsPath>(src: P, dst: Q) -> io::Result<()> {
- fs_imp::symlink(src.as_path(), dst.as_path())
+pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
+ fs_imp::symlink(src.as_ref(), dst.as_ref())
}
/// Reads a soft link, returning the file that the link points to.
/// reading a file that does not exist or reading a file that is not a soft
/// link.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn read_link<P: AsPath>(path: P) -> io::Result<PathBuf> {
- fs_imp::readlink(path.as_path())
+pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
+ fs_imp::readlink(path.as_ref())
}
/// Create a new, empty directory at the provided path
/// This function will return an error if the user lacks permissions to make a
/// new directory at the provided `path`, or if the directory already exists.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn create_dir<P: AsPath>(path: P) -> io::Result<()> {
- fs_imp::mkdir(path.as_path())
+pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
+ fs_imp::mkdir(path.as_ref())
}
/// Recursively create a directory and all of its parent components if they
/// error conditions for when a directory is being created (after it is
/// determined to not exist) are outlined by `fs::create_dir`.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn create_dir_all<P: AsPath>(path: P) -> io::Result<()> {
- let path = path.as_path();
- if path.is_dir() { return Ok(()) }
+pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
+ let path = path.as_ref();
+ if path == Path::new("") || path.is_dir() { return Ok(()) }
if let Some(p) = path.parent() { try!(create_dir_all(p)) }
create_dir(path)
}
/// This function will return an error if the user lacks permissions to remove
/// the directory at the provided `path`, or if the directory isn't empty.
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn remove_dir<P: AsPath>(path: P) -> io::Result<()> {
- fs_imp::rmdir(path.as_path())
+pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
+ fs_imp::rmdir(path.as_ref())
}
/// Removes a directory at this path, after removing all its contents. Use
///
/// See `file::remove_file` and `fs::remove_dir`
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn remove_dir_all<P: AsPath>(path: P) -> io::Result<()> {
- let path = path.as_path();
+pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
+ let path = path.as_ref();
for child in try!(read_dir(path)) {
let child = try!(child).path();
let stat = try!(lstat(&*child));
/// # Examples
///
/// ```
+/// # #![feature(path_ext)]
/// use std::io;
/// use std::fs::{self, PathExt, DirEntry};
/// use std::path::Path;
/// the process lacks permissions to view the contents or if the `path` points
/// at a non-directory file
#[stable(feature = "rust1", since = "1.0.0")]
-pub fn read_dir<P: AsPath>(path: P) -> io::Result<ReadDir> {
- fs_imp::readdir(path.as_path()).map(ReadDir)
+pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
+ fs_imp::readdir(path.as_ref()).map(ReadDir)
}
/// Returns an iterator that will recursively walk the directory structure
reason = "the precise semantics and defaults for a recursive walk \
may change and this may end up accounting for files such \
as symlinks differently")]
-pub fn walk_dir<P: AsPath>(path: P) -> io::Result<WalkDir> {
+pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
let start = try!(read_dir(path));
Ok(WalkDir { cur: Some(start), stack: Vec::new() })
}
reason = "the argument type of u64 is not quite appropriate for \
this function and may change if the standard library \
gains a type to represent a moment in time")]
-pub fn set_file_times<P: AsPath>(path: P, accessed: u64,
+pub fn set_file_times<P: AsRef<Path>>(path: P, accessed: u64,
modified: u64) -> io::Result<()> {
- fs_imp::utimes(path.as_path(), accessed, modified)
+ fs_imp::utimes(path.as_ref(), accessed, modified)
}
/// Changes the permissions found on a file or a directory.
/// # Examples
///
/// ```
+/// # #![feature(fs)]
/// # fn foo() -> std::io::Result<()> {
/// use std::fs;
///
reason = "a more granual ability to set specific permissions may \
be exposed on the Permissions structure itself and this \
method may not always exist")]
-pub fn set_permissions<P: AsPath>(path: P, perm: Permissions) -> io::Result<()> {
- fs_imp::set_perm(path.as_path(), perm.0)
+pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
+ fs_imp::set_perm(path.as_ref(), perm.0)
}
#[cfg(test)]
use env;
use io::{self, Error, ErrorKind};
use fs;
-use path::{self, PathBuf, AsPath};
+use path::{self, PathBuf};
use rand::{thread_rng, Rng};
/// A wrapper for a path to temporary directory implementing automatic
///
/// If no directory can be created, `Err` is returned.
#[allow(deprecated)] // rand usage
- pub fn new_in<P: AsPath + ?Sized>(tmpdir: &P, prefix: &str)
- -> io::Result<TempDir> {
+ pub fn new_in<P: AsRef<path::Path>>(tmpdir: P, prefix: &str) -> io::Result<TempDir> {
let storage;
- let mut tmpdir = tmpdir.as_path();
+ let mut tmpdir = tmpdir.as_ref();
if !tmpdir.is_absolute() {
let cur_dir = try!(env::current_dir());
storage = cur_dir.join(tmpdir);
}
#[stable(feature = "rust1", since = "1.0.0")]
-impl<W> error::Error for IntoInnerError<W> {
+impl<W: Send + fmt::Debug> error::Error for IntoInnerError<W> {
fn description(&self) -> &str {
error::Error::description(self.error())
}
use num::Int;
use slice;
-/// A `Cursor` is a type which wraps another I/O object to provide a `Seek`
+/// A `Cursor` is a type which wraps a non-I/O object to provide a `Seek`
/// implementation.
///
-/// Cursors are currently typically used with memory buffer objects in order to
-/// allow `Seek` plus `Read` and `Write` implementations. For example, common
-/// cursor types include:
+/// Cursors are typically used with memory buffer objects in order to allow
+/// `Seek`, `Read`, and `Write` implementations. For example, common cursor types
+/// include `Cursor<Vec<u8>>` and `Cursor<&[u8]>`.
///
-/// * `Cursor<Vec<u8>>`
-/// * `Cursor<&[u8]>`
-///
-/// Implementations of the I/O traits for `Cursor<T>` are not currently generic
+/// Implementations of the I/O traits for `Cursor<T>` are currently not generic
/// over `T` itself. Instead, specific implementations are provided for various
/// in-memory buffer types like `Vec<u8>` and `&[u8]`.
#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone, Debug)]
pub struct Cursor<T> {
inner: T,
pos: u64,
pub fn get(&'static self) -> Option<Arc<T>> {
let _g = self.lock.lock();
unsafe {
- let mut ptr = *self.ptr.get();
+ let ptr = *self.ptr.get();
if ptr.is_null() {
- ptr = boxed::into_raw(self.init());
- *self.ptr.get() = ptr;
+ Some(self.init())
} else if ptr as usize == 1 {
- return None
+ None
+ } else {
+ Some((*ptr).clone())
}
- Some((*ptr).clone())
}
}
- fn init(&'static self) -> Box<Arc<T>> {
- rt::at_exit(move || unsafe {
+ unsafe fn init(&'static self) -> Arc<T> {
+ // If we successfully register an at exit handler, then we cache the
+ // `Arc` allocation in our own internal box (it will get deallocated by
+ // the at exit handler). Otherwise we just return the freshly allocated
+ // `Arc`.
+ let registered = rt::at_exit(move || {
let g = self.lock.lock();
let ptr = *self.ptr.get();
*self.ptr.get() = 1 as *mut _;
drop(g);
drop(Box::from_raw(ptr))
});
- Box::new((self.init)())
+ let ret = (self.init)();
+ if registered.is_ok() {
+ *self.ptr.get() = boxed::into_raw(Box::new(ret.clone()));
+ }
+ return ret
}
}
/// This function does not perform any I/O, it simply informs this object
/// that some amount of its buffer, returned from `fill_buf`, has been
/// consumed and should no longer be returned.
+ ///
+ /// This function is used to tell the buffer how many bytes you've consumed
+ /// from the return value of `fill_buf`, and so may do odd things if
+ /// `fill_buf` isn't called before calling this.
+ ///
+ /// The `amt` must be `<=` the number of bytes in the buffer returned by `fill_buf`.
#[stable(feature = "rust1", since = "1.0.0")]
fn consume(&mut self, amt: usize);
//!
//! ## Vectors, slices and strings
//!
-//! The common container type, `Vec`, a growable vector backed by an
-//! array, lives in the [`vec`](vec/index.html) module. References to
-//! arrays, `&[T]`, more commonly called "slices", are built-in types
-//! for which the [`slice`](slice/index.html) module defines many
-//! methods.
+//! The common container type, `Vec`, a growable vector backed by an array,
+//! lives in the [`vec`](vec/index.html) module. Contiguous, unsized regions
+//! of memory, `[T]`, commonly called "slices", and their borrowed versions,
+//! `&[T]`, commonly called "borrowed slices", are built-in types for which the
+//! for which the [`slice`](slice/index.html) module defines many methods.
//!
//! `&str`, a UTF-8 string, is a built-in type, and the standard library
//! defines methods for it on a variety of traits in the
//!
//! The [`thread`](thread/index.html) module contains Rust's threading abstractions.
//! [`sync`](sync/index.html) contains further, primitive, shared memory types,
-//! including [`atomic`](sync/atomic/index.html), and [`mpsc`](sync/mpmc/index.html),
+//! including [`atomic`](sync/atomic/index.html), and [`mpsc`](sync/mpsc/index.html),
//! which contains the channel types for message passing.
//!
//! Common types of I/O, including files, TCP, UDP, pipes, Unix domain sockets,
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/")]
+#![doc(test(no_crate_inject))]
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
-#![feature(hash)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(linkage, thread_local, asm)]
#![feature(unsafe_destructor)]
#![feature(unsafe_no_drop_flag)]
#![feature(macro_reexport)]
-#![feature(hash)]
#![feature(int_uint)]
#![feature(unique)]
+#![feature(convert)]
#![feature(allow_internal_unstable)]
#![feature(str_char)]
-#![cfg_attr(test, feature(test, rustc_private))]
+#![feature(into_cow)]
+#![cfg_attr(test, feature(test, rustc_private, std_misc))]
// Don't link to std. We are std.
#![feature(no_std)]
#![no_std]
+#![allow(trivial_casts)]
+#![allow(trivial_numeric_casts)]
#![deny(missing_docs)]
#[cfg(test)] extern crate test;
pub use core::cell;
pub use core::clone;
#[cfg(not(test))] pub use core::cmp;
+pub use core::convert;
pub use core::default;
#[allow(deprecated)]
pub use core::finally;
/* Primitive types */
+// NB: slice and str are primitive types too, but their module docs + primitive doc pages
+// are inlined from the public re-exports of core_collections::{slice, str} above.
+
#[path = "num/float_macros.rs"]
#[macro_use]
mod float_macros;
/* Runtime and platform support */
#[macro_use]
-pub mod thread_local;
+pub mod thread;
+pub mod collections;
pub mod dynamic_lib;
+pub mod env;
pub mod ffi;
-pub mod old_io;
-pub mod io;
pub mod fs;
+pub mod io;
pub mod net;
+pub mod old_io;
+pub mod old_path;
pub mod os;
-pub mod env;
pub mod path;
-pub mod old_path;
pub mod process;
pub mod rand;
-pub mod time;
-
-/* Common data structures */
-
-pub mod collections;
-
-/* Threads and communication */
-
-pub mod thread;
pub mod sync;
+pub mod time;
#[macro_use]
#[path = "sys/common/mod.rs"] mod sys_common;
pub mod rt;
mod panicking;
-// Documentation for primitive types
+// Modules that exist purely to document + host impl docs for primitive types
+mod array;
mod bool;
mod unit;
mod tuple;
pub use rt; // used for panic!()
pub use vec; // used for vec![]
pub use cell; // used for tls!
- pub use thread_local; // used for thread_local!
+ pub use thread; // used for thread_local!
pub use marker; // used for tls!
pub use ops; // used for bitflags!
}
/// Helper macro for unwrapping `Result` values while returning early with an
-/// error if the value of the expression is `Err`. For more information, see
-/// `std::io`.
+/// error if the value of the expression is `Err`.
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! try {
/// # Examples
///
/// ```
+/// # #![feature(std_misc)]
/// use std::thread;
/// use std::sync::mpsc;
///
/// Some examples:
///
/// ```no_run
+/// # #![feature(net)]
/// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
///
/// fn main() {
.iter()
.map(|&seg| format!("{:x}", seg))
.collect::<Vec<String>>()
- .as_slice()
.connect(":")
}
/// # Examples
///
/// ```no_run
+/// # #![feature(net)]
/// use std::net;
///
/// # fn foo() -> std::io::Result<()> {
/// # Examples
///
/// ```no_run
+/// # #![feature(net)]
/// use std::io::prelude::*;
/// use std::net::TcpStream;
///
/// # Examples
///
/// ```no_run
+/// # #![feature(net)]
/// use std::net::{TcpListener, TcpStream};
/// use std::thread;
///
/// # Examples
///
/// ```no_run
+/// # #![feature(net)]
/// use std::net::UdpSocket;
///
/// # fn foo() -> std::io::Result<()> {
/// Returns the `NaN` value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let nan: f32 = Float::nan();
/// Returns the infinite value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns the negative infinite value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns `0.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let inf: f32 = Float::infinity();
/// Returns `-0.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let inf: f32 = Float::infinity();
/// Returns `1.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let one: f32 = Float::one();
/// Returns the smallest finite value that this type can represent.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// Returns the largest finite value that this type can represent.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// Returns `true` if this value is `NaN` and false otherwise.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// false otherwise.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns `true` if this number is neither infinite nor `NaN`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// [subnormal][subnormal], or `NaN`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// predicate instead.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::{Float, FpCategory};
/// use std::f32;
///
/// The floating point encoding is documented in the [Reference][floating-point].
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let num = 2.0f32;
/// number is `Float::nan()`.
///
/// ```
+ /// # #![feature(core, std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// - `Float::nan()` if the number is `Float::nan()`
///
/// ```
+ /// # #![feature(core, std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// a separate multiplication operation followed by an add.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let m = 10.0;
/// Take the reciprocal (inverse) of a number, `1/x`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 2.0;
/// Returns NaN if `self` is a negative number.
///
/// ```
+ /// # #![feature(core, std_misc)]
/// use std::num::Float;
///
/// let positive = 4.0;
/// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let f = 4.0;
/// Convert radians to degrees.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64::consts;
///
/// Convert degrees to radians.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64::consts;
///
/// Constructs a floating point number of `x*2^exp`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// // 3*2^2 - 12 == 0
/// * `0.5 <= abs(x) < 1.0`
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 4.0;
/// `other`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 1.0f32;
/// * Else: `self - other`
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 3.0;
/// Take the cubic root of a number.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 8.0;
/// legs of length `x` and `y`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 2.0;
/// Computes the sine of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Computes the cosine of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Computes the tangent of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// [-1, 1].
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// [-1, 1].
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// `(sin(x), cos(x))`.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// number is close to zero.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 7.0;
/// the operations were performed separately.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic sine function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic cosine function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic tangent function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Inverse hyperbolic sine function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
///
/// let x = 1.0;
/// Inverse hyperbolic cosine function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
///
/// let x = 1.0;
/// Inverse hyperbolic tangent function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Returns the `NaN` value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let nan: f32 = Float::nan();
/// Returns the infinite value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns the negative infinite value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns `0.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let inf: f32 = Float::infinity();
/// Returns `-0.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let inf: f32 = Float::infinity();
/// Returns `1.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let one: f32 = Float::one();
/// Returns the smallest finite value that this type can represent.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// Returns the largest finite value that this type can represent.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// Returns `true` if this value is `NaN` and false otherwise.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// false otherwise.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns `true` if this number is neither infinite nor `NaN`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// [subnormal][subnormal], or `NaN`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// predicate instead.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::{Float, FpCategory};
/// use std::f32;
///
/// The floating point encoding is documented in the [Reference][floating-point].
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let num = 2.0f32;
/// number is `Float::nan()`.
///
/// ```
+ /// # #![feature(core, std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// - `Float::nan()` if the number is `Float::nan()`
///
/// ```
+ /// # #![feature(core, std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// a separate multiplication operation followed by an add.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let m = 10.0;
/// Take the reciprocal (inverse) of a number, `1/x`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 2.0;
/// Returns NaN if `self` is a negative number.
///
/// ```
+ /// # #![feature(core, std_misc)]
/// use std::num::Float;
///
/// let positive = 4.0;
/// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let f = 4.0;
/// Convert radians to degrees.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64::consts;
///
/// Convert degrees to radians.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64::consts;
///
/// Constructs a floating point number of `x*2^exp`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// // 3*2^2 - 12 == 0
/// * `0.5 <= abs(x) < 1.0`
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 4.0;
/// `other`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 1.0f32;
/// * Else: `self - other`
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 3.0;
/// Take the cubic root of a number.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 8.0;
/// legs of length `x` and `y`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 2.0;
/// Computes the sine of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Computes the cosine of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Computes the tangent of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// [-1, 1].
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// [-1, 1].
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// `(sin(x), cos(x))`.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// number is close to zero.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 7.0;
/// the operations were performed separately.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic sine function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic cosine function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic tangent function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Inverse hyperbolic tangent function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Returns the `NaN` value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let nan: f32 = Float::nan();
/// Returns the infinite value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns the negative infinite value.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns `0.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let inf: f32 = Float::infinity();
/// Returns `-0.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let inf: f32 = Float::infinity();
/// Returns `1.0`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let one: f32 = Float::one();
/// Returns the smallest finite value that this type can represent.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// Returns the largest finite value that this type can represent.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// Returns `true` if this value is `NaN` and false otherwise.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// false otherwise.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// Returns `true` if this number is neither infinite nor `NaN`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// [subnormal][subnormal], or `NaN`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f32;
///
/// predicate instead.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::{Float, FpCategory};
/// use std::f32;
///
/// The floating point encoding is documented in the [Reference][floating-point].
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let num = 2.0f32;
/// number is `Float::nan()`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// - `Float::nan()` if the number is `Float::nan()`
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
/// use std::f64;
///
/// a separate multiplication operation followed by an add.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let m = 10.0;
/// Take the reciprocal (inverse) of a number, `1/x`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 2.0;
/// Returns NaN if `self` is a negative number.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let positive = 4.0;
/// Take the reciprocal (inverse) square root of a number, `1/sqrt(x)`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let f = 4.0;
/// Convert radians to degrees.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64::consts;
///
/// Convert degrees to radians.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64::consts;
///
/// Constructs a floating point number of `x*2^exp`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// // 3*2^2 - 12 == 0
/// * `0.5 <= abs(x) < 1.0`
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 4.0;
/// `other`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 1.0f32;
/// * Else: `self - other`
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 3.0;
/// Take the cubic root of a number.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 8.0;
/// legs of length `x` and `y`.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 2.0;
/// Computes the sine of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Computes the cosine of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Computes the tangent of a number (in radians).
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// [-1, 1].
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// [-1, 1].
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// `(sin(x), cos(x))`.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// number is close to zero.
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::num::Float;
///
/// let x = 7.0;
/// the operations were performed separately.
///
/// ```
+ /// # #![feature(std_misc, core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic sine function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic cosine function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Hyperbolic tangent function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// Inverse hyperbolic tangent function.
///
/// ```
+ /// # #![feature(core)]
/// use std::num::Float;
/// use std::f64;
///
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// use std::old_io::*;
/// use std::old_path::Path;
///
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// use std::old_io::*;
/// use std::old_path::Path;
///
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
/// use std::old_path::Path;
/// # Examples
///
/// ```
+/// # #![feature(old_io)]
/// use std::sync::mpsc::channel;
/// use std::old_io::*;
///
/// # Examples
///
/// ```
+/// # #![feature(old_io, io)]
/// # #![allow(unused_must_use)]
/// use std::sync::mpsc::channel;
/// use std::old_io::*;
/// that many bytes are parsed. For example, if `size` is 4, then a
/// 32-bit value is parsed.
pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 {
- use ptr::{copy_nonoverlapping_memory};
+ use ptr::{copy_nonoverlapping};
assert!(size <= 8);
unsafe {
let ptr = data.as_ptr().offset(start as int);
let out = buf.as_mut_ptr();
- copy_nonoverlapping_memory(out.offset((8 - size) as int), ptr, size);
+ copy_nonoverlapping(out.offset((8 - size) as int), ptr, size);
(*(out as *const u64)).to_be()
}
}
//! # Examples
//!
//! ```rust
+//! # #![feature(old_io, io, old_path)]
//! # #![allow(unused_must_use)]
//! use std::old_io::fs::PathExtensions;
//! use std::old_io::*;
/// # Examples
///
/// ```rust,should_fail
+ /// # #![feature(old_io, old_path)]
/// use std::old_io::*;
/// use std::old_path::Path;
///
/// # Examples
///
/// ```
+ /// # #![feature(old_io, old_path)]
/// use std::old_io::*;
/// use std::old_path::Path;
///
/// # Examples
///
/// ```
+ /// # #![feature(old_io, old_path, io)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
/// use std::old_path::Path;
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
/// use std::old_path::Path;
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// use std::old_io::*;
/// use std::old_path::Path;
///
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
/// use std::old_path::Path;
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
/// use std::old_path::Path;
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// # #![allow(unused_must_use)]
/// use std::old_io;
/// use std::old_io::*;
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path, old_fs)]
/// # #![allow(unused_must_use)]
/// use std::old_io;
/// use std::old_io::*;
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
/// use std::old_path::Path;
/// # Examples
///
/// ```
+/// # #![feature(old_io, old_path)]
/// use std::old_io::fs::PathExtensions;
/// use std::old_io;
/// use std::old_io::*;
/// # Examples
///
/// ```
+/// # #![feature(old_io, io)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
///
/// # Examples
///
/// ```
+/// # #![feature(old_io)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
///
/// # Examples
///
/// ```
+/// # #![feature(old_io, io)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
///
/// # Examples
///
/// ```
+/// # #![feature(old_io)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
///
//! * Read lines from stdin
//!
//! ```rust
+//! # #![feature(old_io, old_path)]
//! use std::old_io as io;
//! use std::old_io::*;
//!
//! * Read a complete file
//!
//! ```rust
+//! # #![feature(old_io, old_path)]
//! use std::old_io::*;
//! use std::old_path::Path;
//!
//! * Write a line to a file
//!
//! ```rust
+//! # #![feature(old_io, old_path)]
//! # #![allow(unused_must_use)]
//! use std::old_io::*;
//! use std::old_path::Path;
//! * Iterate over the lines of a file
//!
//! ```rust,no_run
+//! # #![feature(old_io, old_path)]
//! use std::old_io::*;
//! use std::old_path::Path;
//!
//! * Pull the lines of a file into a vector of strings
//!
//! ```rust,no_run
+//! # #![feature(old_io, old_path)]
//! use std::old_io::*;
//! use std::old_path::Path;
//!
//! * Make a simple TCP client connection and request
//!
//! ```rust
+//! # #![feature(old_io)]
//! # #![allow(unused_must_use)]
//! use std::old_io::*;
//!
//! * Make a simple TCP server
//!
//! ```rust
+//! # #![feature(old_io)]
//! # fn main() { }
//! # fn foo() {
//! # #![allow(dead_code)]
//! If you wanted to handle the error though you might write:
//!
//! ```rust
+//! # #![feature(old_io, old_path)]
//! # #![allow(unused_must_use)]
//! use std::old_io::*;
//! use std::old_path::Path;
//! If you wanted to read several `u32`s from a file and return their product:
//!
//! ```rust
+//! # #![feature(old_io, old_path)]
//! use std::old_io::*;
//! use std::old_path::Path;
//!
/// # Examples
///
/// ```
+/// # #![feature(old_io)]
/// use std::old_io as io;
/// use std::old_io::*;
/// use std::old_io::util::LimitReader;
/// # Examples
///
/// ```
+/// # #![feature(old_io)]
/// use std::old_io::util::TeeReader;
/// use std::old_io::*;
///
/// # Examples
///
/// ```
+ /// # #![feature(old_io)]
/// use std::old_io::*;
///
/// let mut reader = BufReader::new(b"hello\nworld");
/// # Examples
///
/// ```
+/// # #![feature(old_io)]
/// use std::old_io as io;
///
/// let eof = io::standard_error(io::EndOfFile);
/// # Examples
///
/// ```no_run
+/// # #![feature(old_io, old_path)]
///
/// use std::old_io::fs::PathExtensions;
/// use std::old_path::Path;
/// Some examples:
///
/// ```rust,no_run
+/// # #![feature(old_io, core)]
/// # #![allow(unused_must_use)]
///
/// use std::old_io::{TcpStream, TcpListener};
/// # Examples
///
/// ```
+ /// # #![feature(old_io, old_path, io)]
/// # #![allow(unused_must_use)]
/// use std::old_io::net::pipe::UnixStream;
/// use std::old_io::*;
/// # Examples
///
/// ```
+ /// # #![feature(old_io, io, old_path)]
/// # fn foo() {
/// use std::old_io::net::pipe::UnixListener;
/// use std::old_io::*;
/// # Examples
///
/// ```no_run
+/// # #![feature(old_io, io)]
/// use std::old_io::*;
///
/// {
/// # Examples
///
/// ```no_run
+ /// # #![feature(old_io, std_misc)]
/// # #![allow(unused_must_use)]
/// use std::old_io::*;
/// use std::time::Duration;
/// # Examples
///
/// ```
+/// # #![feature(old_io)]
/// # fn foo() {
/// use std::old_io::*;
/// use std::thread;
/// # Examples
///
/// ```no_run
+ /// # #![feature(old_io, io)]
/// use std::old_io::*;
///
/// let mut a = TcpListener::bind("127.0.0.1:8482").listen().unwrap();
/// # Examples
///
/// ```
+ /// # #![feature(old_io, io)]
/// use std::old_io::*;
/// use std::thread;
///
/// # Examples
///
/// ```rust,no_run
+/// # #![feature(old_io)]
/// # #![allow(unused_must_use)]
///
/// use std::old_io::net::udp::UdpSocket;
/// # Examples
///
/// ```{rust,no_run}
+ /// # #![feature(old_io, libc, io)]
/// # #![allow(unused_must_use)]
/// extern crate libc;
///
/// # Examples
///
/// ```should_fail
+/// # #![feature(old_io)]
/// use std::old_io::*;
///
/// let mut child = match Command::new("/bin/cat").arg("file.txt").spawn() {
/// to be changed (for example, by adding arguments) prior to spawning:
///
/// ```
+/// # #![feature(old_io)]
/// use std::old_io::*;
///
/// let mut process = match Command::new("sh").arg("-c").arg("echo hello").spawn() {
/// # Examples
///
/// ```
+ /// # #![feature(old_io, core)]
/// use std::old_io::Command;
///
/// let output = match Command::new("cat").arg("foot.txt").output() {
/// # Examples
///
/// ```
+ /// # #![feature(old_io)]
/// use std::old_io::Command;
///
/// let status = match Command::new("ls").status() {
/// # Examples
///
/// ```no_run
+ /// # #![feature(old_io, io)]
/// use std::old_io::{Command, IoResult};
/// use std::old_io::process::ProcessExit;
///
//! # Examples
//!
//! ```rust
+//! # #![feature(old_io)]
//! # #![allow(unused_must_use)]
//! use std::old_io;
//! use std::old_io::*;
/// # Examples
///
/// ```
+ /// # #![feature(old_io)]
/// use std::old_io;
/// use std::old_io::*;
///
STDIN = boxed::into_raw(box stdin);
// Make sure to free it at exit
- rt::at_exit(|| {
+ let _ = rt::at_exit(|| {
Box::from_raw(STDIN);
STDIN = ptr::null_mut();
});
// })
// })
fn with_task_stdout<F>(f: F) where F: FnOnce(&mut Writer) -> IoResult<()> {
- let mut my_stdout = LOCAL_STDOUT.with(|slot| {
+ let mut my_stdout: Box<Writer + Send> = LOCAL_STDOUT.with(|slot| {
slot.borrow_mut().take()
}).unwrap_or_else(|| {
- box stdout() as Box<Writer + Send>
+ box stdout()
});
let result = f(&mut *my_stdout);
let mut var = Some(my_stdout);
/// # Examples
///
/// ```no_run
+/// # #![feature(old_io, old_path)]
/// use std::old_io::*;
/// use std::old_path::{Path, GenericPath};
///
/// # Examples
///
/// ```
+/// # #![feature(old_io, std_misc)]
/// # fn foo() {
/// use std::old_io::Timer;
/// use std::time::Duration;
/// the `old_io::timer` module.
///
/// ```
+/// # #![feature(old_io, std_misc)]
/// # fn foo() {
/// use std::old_io::timer;
/// use std::time::Duration;
/// # Examples
///
/// ```
+ /// # #![feature(old_io, std_misc)]
/// use std::old_io::Timer;
/// use std::time::Duration;
///
/// ```
///
/// ```
+ /// # #![feature(old_io, std_misc)]
/// use std::old_io::Timer;
/// use std::time::Duration;
///
/// # Examples
///
/// ```
+ /// # #![feature(old_io, std_misc)]
/// use std::old_io::Timer;
/// use std::time::Duration;
///
/// ```
///
/// ```
+ /// # #![feature(old_io, std_misc)]
/// use std::old_io::Timer;
/// use std::time::Duration;
///
//! ## Examples
//!
//! ```rust
+//! # #![feature(old_path, old_io)]
//! use std::old_io::fs::PathExtensions;
//! use std::old_path::{Path, GenericPath};
//!
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// # foo();
/// # #[cfg(windows)] fn foo() {}
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// println!("{}", Path::new(r"C:\some\path").display());
/// ```
/// # Examples
///
/// ```
+ /// # #![feature(old_path)]
/// use std::old_path::{Path, GenericPath};
/// let path = Path::new_opt(r"C:\some\path");
///
use boxed::Box;
use clone::Clone;
+use convert::From;
use env;
use error::{FromError, Error};
use ffi::{OsString, OsStr};
#[cfg(windows)]
fn path2new(path: &Path) -> PathBuf {
- PathBuf::new(path.as_str().unwrap())
+ PathBuf::from(path.as_str().unwrap())
}
#[cfg(unix)]
fn path2new(path: &Path) -> PathBuf {
use os::unix::prelude::*;
- PathBuf::new(<OsStr as OsStrExt>::from_bytes(path.as_vec()))
+ PathBuf::from(<OsStr as OsStrExt>::from_bytes(path.as_vec()))
}
#[cfg(unix)]
/// # Examples
///
/// ```
+/// # #![feature(os, old_path)]
/// use std::os;
/// use std::old_path::{Path, GenericPath};
///
/// # Examples
///
/// ```
+/// # #![feature(os)]
/// use std::os;
///
/// // We will iterate through the references to the element returned by os::env();
/// # Examples
///
/// ```
+/// # #![feature(os)]
/// use std::os;
///
/// let key = "HOME";
/// # Examples
///
/// ```
+/// # #![feature(os)]
/// use std::os;
///
/// let key = "KEY";
/// # Examples
///
/// ```
+/// # #![feature(old_path, os)]
/// use std::os;
/// use std::old_path::{Path, GenericPath};
///
/// # Examples
///
/// ```
+/// # #![feature(os, old_path, core)]
/// use std::os;
/// use std::old_path::Path;
///
/// # Examples
///
/// ```
+/// # #![feature(os, old_path)]
/// use std::os;
/// use std::old_path::{Path, GenericPath};
///
/// # Examples
///
/// ```
+/// # #![feature(os, old_path)]
/// use std::os;
/// use std::old_path::{Path, GenericPath};
///
/// # Examples
///
/// ```
+/// # #![feature(os, old_path)]
/// use std::os;
/// use std::old_path::{Path, GenericPath};
///
/// # Examples
///
/// ```
+/// # #![feature(os, old_path)]
/// use std::os;
/// use std::old_path::{Path, GenericPath};
///
/// # Examples
///
/// ```
+/// # #![feature(os, old_path)]
/// use std::os;
/// use std::old_path::{Path, GenericPath};
///
/// # Examples
///
/// ```
+/// # #![feature(os)]
/// use std::os;
///
/// // Same as println!("{}", last_os_error());
/// # Examples
///
/// ```
+/// # #![feature(os)]
/// use std::os;
///
/// // Prints each argument on a separate line
//! To build or modify paths, use `PathBuf`:
//!
//! ```rust
+//! # #![feature(convert)]
//! use std::path::PathBuf;
//!
-//! let mut path = PathBuf::new("c:\\");
+//! let mut path = PathBuf::from("c:\\");
//! path.push("windows");
//! path.push("system32");
//! path.set_extension("dll");
use iter::{self, IntoIterator};
use mem;
use ops::{self, Deref};
+use string::String;
use vec::Vec;
use fmt;
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> AsRef<OsStr> for Component<'a> {
+ fn as_ref(&self) -> &OsStr {
+ self.as_os_str()
+ }
+}
+
/// The core iterator giving the components of a path.
///
/// See the module documentation for an in-depth explanation of components and
}
/// Extract a slice corresponding to the portion of the path remaining for iteration.
+ #[stable(feature = "rust1", since = "1.0.0")]
pub fn as_path(&self) -> &'a Path {
let mut comps = self.clone();
if comps.front == State::Body { comps.trim_left(); }
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> AsRef<Path> for Components<'a> {
+ fn as_ref(&self) -> &Path {
+ self.as_path()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> AsRef<OsStr> for Components<'a> {
+ fn as_ref(&self) -> &OsStr {
+ self.as_path().as_os_str()
+ }
+}
+
impl<'a> Iter<'a> {
/// Extract a slice corresponding to the portion of the path remaining for iteration.
#[stable(feature = "rust1", since = "1.0.0")]
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> AsRef<Path> for Iter<'a> {
+ fn as_ref(&self) -> &Path {
+ self.as_path()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> AsRef<OsStr> for Iter<'a> {
+ fn as_ref(&self) -> &OsStr {
+ self.as_path().as_os_str()
+ }
+}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> Iterator for Iter<'a> {
type Item = &'a OsStr;
/// # Examples
///
/// ```
+/// # #![feature(convert)]
/// use std::path::PathBuf;
///
-/// let mut path = PathBuf::new("c:\\");
+/// let mut path = PathBuf::from("c:\\");
/// path.push("windows");
/// path.push("system32");
/// path.set_extension("dll");
unsafe { mem::transmute(self) }
}
- /// Allocate a `PathBuf` with initial contents given by the
- /// argument.
+ /// Allocate an empty `PathBuf`.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn new<S: AsOsStr>(s: S) -> PathBuf {
- PathBuf { inner: s.as_os_str().to_os_string() }
+ pub fn new() -> PathBuf {
+ PathBuf { inner: OsString::new() }
}
/// Extend `self` with `path`.
/// replaces everything except for the prefix (if any) of `self`.
/// * if `path` has a prefix but no root, it replaces `self.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn push<P: AsPath>(&mut self, path: P) {
- let path = path.as_path();
+ pub fn push<P: AsRef<Path>>(&mut self, path: P) {
+ let path = path.as_ref();
// in general, a separator is needed if the rightmost byte is not a separator
let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
/// # Examples
///
/// ```
+ /// # #![feature(convert)]
/// use std::path::PathBuf;
///
- /// let mut buf = PathBuf::new("/");
+ /// let mut buf = PathBuf::from("/");
/// assert!(buf.file_name() == None);
/// buf.set_file_name("bar");
- /// assert!(buf == PathBuf::new("/bar"));
+ /// assert!(buf == PathBuf::from("/bar"));
/// assert!(buf.file_name().is_some());
/// buf.set_file_name("baz.txt");
- /// assert!(buf == PathBuf::new("/baz.txt"));
+ /// assert!(buf == PathBuf::from("/baz.txt"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn set_file_name<S: AsOsStr>(&mut self, file_name: S) {
+ pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
if self.file_name().is_some() {
let popped = self.pop();
debug_assert!(popped);
}
- self.push(file_name.as_os_str());
+ self.push(file_name.as_ref());
}
/// Updates `self.extension()` to `extension`.
/// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
/// is added; otherwise it is replaced.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn set_extension<S: AsOsStr>(&mut self, extension: S) -> bool {
+ pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
if self.file_name().is_none() { return false; }
let mut stem = match self.file_stem() {
Some(stem) => stem.to_os_string(),
- None => OsString::from_str(""),
+ None => OsString::new(),
};
- let extension = extension.as_os_str();
+ let extension = extension.as_ref();
if os_str_as_u8_slice(extension).len() > 0 {
stem.push(".");
stem.push(extension);
}
#[stable(feature = "rust1", since = "1.0.0")]
-impl<P: AsPath> iter::FromIterator<P> for PathBuf {
+impl<'a> From<&'a Path> for PathBuf {
+ fn from(s: &'a Path) -> PathBuf {
+ s.to_path_buf()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a str> for PathBuf {
+ fn from(s: &'a str) -> PathBuf {
+ PathBuf::from(OsString::from(s))
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a String> for PathBuf {
+ fn from(s: &'a String) -> PathBuf {
+ PathBuf::from(OsString::from(s))
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl From<String> for PathBuf {
+ fn from(s: String) -> PathBuf {
+ PathBuf::from(OsString::from(s))
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a OsStr> for PathBuf {
+ fn from(s: &'a OsStr) -> PathBuf {
+ PathBuf::from(OsString::from(s))
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a> From<&'a OsString> for PathBuf {
+ fn from(s: &'a OsString) -> PathBuf {
+ PathBuf::from(s.to_os_string())
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl From<OsString> for PathBuf {
+ fn from(s: OsString) -> PathBuf {
+ PathBuf { inner: s }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf {
fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
- let mut buf = PathBuf::new("");
+ let mut buf = PathBuf::new();
buf.extend(iter);
buf
}
}
#[stable(feature = "rust1", since = "1.0.0")]
-impl<P: AsPath> iter::Extend<P> for PathBuf {
+impl<P: AsRef<Path>> iter::Extend<P> for PathBuf {
fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
for p in iter {
self.push(p)
}
#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<OsStr> for PathBuf {
+ fn as_ref(&self) -> &OsStr {
+ &self.inner[..]
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+#[deprecated(since = "1.0.0", reason = "trait is deprecated")]
impl AsOsStr for PathBuf {
fn as_os_str(&self) -> &OsStr {
&self.inner[..]
}
}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl Into<OsString> for PathBuf {
+ fn into(self) -> OsString {
+ self.inner
+ }
+}
+
/// A slice of a path (akin to `str`).
///
/// This type supports a number of operations for inspecting a path, including
///
/// This is a cost-free conversion.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn new<S: ?Sized + AsOsStr>(s: &S) -> &Path {
- unsafe { mem::transmute(s.as_os_str()) }
+ pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
+ unsafe { mem::transmute(s.as_ref()) }
+ }
+
+ /// Yield the underlying `OsStr` slice.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn as_os_str(&self) -> &OsStr {
+ &self.inner
}
/// Yield a `&str` slice if the `Path` is valid unicode.
/// Convert a `Path` to an owned `PathBuf`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_path_buf(&self) -> PathBuf {
- PathBuf::new(self)
+ PathBuf::from(self.inner.to_os_string())
}
/// A path is *absolute* if it is independent of the current directory.
}
/// Returns a path that, when joined onto `base`, yields `self`.
+ ///
+ /// If `base` is not a prefix of `self` (i.e. `starts_with`
+ /// returns false), then `relative_from` returns `None`.
#[unstable(feature = "path_relative_from", reason = "see #23284")]
- pub fn relative_from<'a, P: ?Sized>(&'a self, base: &'a P) -> Option<&Path> where
- P: AsPath
+ pub fn relative_from<'a, P: ?Sized + AsRef<Path>>(&'a self, base: &'a P) -> Option<&Path>
{
- iter_after(self.components(), base.as_path().components()).map(|c| c.as_path())
+ iter_after(self.components(), base.as_ref().components()).map(|c| c.as_path())
}
/// Determines whether `base` is a prefix of `self`.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn starts_with<P: AsPath>(&self, base: P) -> bool {
- iter_after(self.components(), base.as_path().components()).is_some()
+ pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
+ iter_after(self.components(), base.as_ref().components()).is_some()
}
/// Determines whether `child` is a suffix of `self`.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn ends_with<P: AsPath>(&self, child: P) -> bool {
- iter_after(self.components().rev(), child.as_path().components().rev()).is_some()
+ pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
+ iter_after(self.components().rev(), child.as_ref().components().rev()).is_some()
}
/// Extract the stem (non-extension) portion of `self.file()`.
///
/// See `PathBuf::push` for more details on what it means to adjoin a path.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn join<P: AsPath>(&self, path: P) -> PathBuf {
+ pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
let mut buf = self.to_path_buf();
buf.push(path);
buf
///
/// See `PathBuf::set_file_name` for more details.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn with_file_name<S: AsOsStr>(&self, file_name: S) -> PathBuf {
+ pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
let mut buf = self.to_path_buf();
buf.set_file_name(file_name);
buf
///
/// See `PathBuf::set_extension` for more details.
#[stable(feature = "rust1", since = "1.0.0")]
- pub fn with_extension<S: AsOsStr>(&self, extension: S) -> PathBuf {
+ pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
let mut buf = self.to_path_buf();
buf.set_extension(extension);
buf
}
#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<OsStr> for Path {
+ fn as_ref(&self) -> &OsStr {
+ &self.inner
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+#[deprecated(since = "1.0.0", reason = "trait is deprecated")]
impl AsOsStr for Path {
fn as_os_str(&self) -> &OsStr {
&self.inner
/// Freely convertible to a `Path`.
#[unstable(feature = "std_misc")]
+#[deprecated(since = "1.0.0", reason = "use std::convert::AsRef<Path> instead")]
pub trait AsPath {
/// Convert to a `Path`.
#[unstable(feature = "std_misc")]
}
#[unstable(feature = "std_misc")]
+#[deprecated(since = "1.0.0", reason = "use std::convert::AsRef<Path> instead")]
+#[allow(deprecated)]
impl<T: AsOsStr + ?Sized> AsPath for T {
fn as_path(&self) -> &Path { Path::new(self.as_os_str()) }
}
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<Path> for Path {
+ fn as_ref(&self) -> &Path { self }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<Path> for OsStr {
+ fn as_ref(&self) -> &Path { Path::new(self) }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<Path> for OsString {
+ fn as_ref(&self) -> &Path { Path::new(self) }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<Path> for str {
+ fn as_ref(&self) -> &Path { Path::new(self) }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<Path> for String {
+ fn as_ref(&self) -> &Path { Path::new(self) }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl AsRef<Path> for PathBuf {
+ fn as_ref(&self) -> &Path { self }
+}
+
#[cfg(test)]
mod tests {
use super::*;
let static_path = Path::new("/home/foo");
let static_cow_path: Cow<'static, Path> = static_path.into_cow();
- let pathbuf = PathBuf::new("/home/foo");
+ let pathbuf = PathBuf::from("/home/foo");
{
let path: &Path = &pathbuf;
pub fn test_push() {
macro_rules! tp(
($path:expr, $push:expr, $expected:expr) => ( {
- let mut actual = PathBuf::new($path);
+ let mut actual = PathBuf::from($path);
actual.push($push);
assert!(actual.to_str() == Some($expected),
"pushing {:?} onto {:?}: Expected {:?}, got {:?}",
pub fn test_pop() {
macro_rules! tp(
($path:expr, $expected:expr, $output:expr) => ( {
- let mut actual = PathBuf::new($path);
+ let mut actual = PathBuf::from($path);
let output = actual.pop();
assert!(actual.to_str() == Some($expected) && output == $output,
"popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
pub fn test_set_file_name() {
macro_rules! tfn(
($path:expr, $file:expr, $expected:expr) => ( {
- let mut p = PathBuf::new($path);
+ let mut p = PathBuf::from($path);
p.set_file_name($file);
assert!(p.to_str() == Some($expected),
"setting file name of {:?} to {:?}: Expected {:?}, got {:?}",
pub fn test_set_extension() {
macro_rules! tfe(
($path:expr, $ext:expr, $expected:expr, $output:expr) => ( {
- let mut p = PathBuf::new($path);
+ let mut p = PathBuf::from($path);
let output = p.set_extension($ext);
assert!(p.to_str() == Some($expected) && output == $output,
"setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}",
#[doc(no_inline)] pub use clone::Clone;
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use cmp::{PartialEq, PartialOrd, Eq, Ord};
+#[unstable(feature = "convert")]
+#[doc(no_inline)] pub use convert::{AsRef, AsMut, Into, From};
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use iter::DoubleEndedIterator;
#[stable(feature = "rust1", since = "1.0.0")]
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use result::Result::{self, Ok, Err};
#[stable(feature = "rust1", since = "1.0.0")]
+#[allow(deprecated)]
#[doc(no_inline)] pub use slice::{SliceConcatExt, AsSlice};
#[stable(feature = "rust1", since = "1.0.0")]
+#[allow(deprecated)]
#[doc(no_inline)] pub use str::Str;
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)] pub use string::{String, ToString};
use ffi::AsOsStr;
use fmt;
use io::{self, Error, ErrorKind};
-use path::AsPath;
use libc;
+use path;
use sync::mpsc::{channel, Receiver};
use sys::pipe2::{self, AnonPipe};
use sys::process2::Process as ProcessImp;
/// Set the working directory for the child process.
#[stable(feature = "process", since = "1.0.0")]
- pub fn current_dir<P: AsPath>(&mut self, dir: P) -> &mut Command {
- self.inner.cwd(dir.as_path().as_os_str());
+ pub fn current_dir<P: AsRef<path::Path>>(&mut self, dir: P) -> &mut Command {
+ self.inner.cwd(dir.as_ref().as_os_str());
self
}
// test changing to the parent of os::getcwd() because we know
// the path exists (and os::getcwd() is not expected to be root)
let parent_dir = os::getcwd().unwrap().dir_path();
- let result = pwd_cmd().current_dir(&parent_dir).output().unwrap();
+ let result = pwd_cmd().current_dir(parent_dir.as_str().unwrap()).output().unwrap();
let output = String::from_utf8(result.stdout).unwrap();
let child_dir = old_path::Path::new(output.trim());
//! # Examples
//!
//! ```rust
+//! # #![feature(rand)]
//! use std::rand;
//! use std::rand::Rng;
//!
//! ```
//!
//! ```rust
+//! # #![feature(rand)]
//! use std::rand;
//!
//! let tuple = rand::random::<(f64, char)>();
//! multiply this fraction by 4.
//!
//! ```
+//! # #![feature(rand)]
//! use std::rand;
//! use std::rand::distributions::{IndependentSample, Range};
//!
//! [Monty Hall Problem]: http://en.wikipedia.org/wiki/Monty_Hall_problem
//!
//! ```
+//! # #![feature(rand)]
//! use std::rand;
//! use std::rand::Rng;
//! use std::rand::distributions::{IndependentSample, Range};
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
///
/// let x: u8 = rand::random();
/// Caching the thread local random number generator:
///
/// ```
+/// # #![feature(rand)]
/// use std::rand;
/// use std::rand::Rng;
///
/// # Examples
///
/// ```
+/// # #![feature(rand)]
/// use std::rand::{thread_rng, sample};
///
/// let mut rng = thread_rng();
/// # Examples
///
/// ```
+/// # #![feature(rand, old_io)]
/// use std::rand::{reader, Rng};
/// use std::old_io::MemReader;
///
//!
//! Documentation can be found on the `rt::at_exit` function.
+// FIXME: switch this to use atexit. Currently this
+// segfaults (the queue's memory is mysteriously gone), so
+// instead the cleanup is tied to the `std::rt` entry point.
+
use boxed;
use boxed::Box;
use vec::Vec;
static LOCK: Mutex = MUTEX_INIT;
static mut QUEUE: *mut Queue = 0 as *mut Queue;
-unsafe fn init() {
+// The maximum number of times the cleanup routines will be run. While running
+// the at_exit closures new ones may be registered, and this count is the number
+// of times the new closures will be allowed to register successfully. After
+// this number of iterations all new registrations will return `false`.
+const ITERS: usize = 10;
+
+unsafe fn init() -> bool {
if QUEUE.is_null() {
let state: Box<Queue> = box Vec::new();
QUEUE = boxed::into_raw(state);
- } else {
+ } else if QUEUE as usize == 1 {
// can't re-init after a cleanup
- rtassert!(QUEUE as uint != 1);
+ return false
}
- // FIXME: switch this to use atexit as below. Currently this
- // segfaults (the queue's memory is mysteriously gone), so
- // instead the cleanup is tied to the `std::rt` entry point.
- //
- // ::libc::atexit(cleanup);
+ return true
}
pub fn cleanup() {
- unsafe {
- LOCK.lock();
- let queue = QUEUE;
- QUEUE = 1 as *mut _;
- LOCK.unlock();
+ for i in 0..ITERS {
+ unsafe {
+ LOCK.lock();
+ let queue = QUEUE;
+ QUEUE = if i == ITERS - 1 {1} else {0} as *mut _;
+ LOCK.unlock();
- // make sure we're not recursively cleaning up
- rtassert!(queue as uint != 1);
+ // make sure we're not recursively cleaning up
+ rtassert!(queue as usize != 1);
- // If we never called init, not need to cleanup!
- if queue as uint != 0 {
- let queue: Box<Queue> = Box::from_raw(queue);
- for to_run in *queue {
- to_run.invoke(());
+ // If we never called init, not need to cleanup!
+ if queue as usize != 0 {
+ let queue: Box<Queue> = Box::from_raw(queue);
+ for to_run in *queue {
+ to_run.invoke(());
+ }
}
}
}
}
-pub fn push(f: Thunk<'static>) {
+pub fn push(f: Thunk<'static>) -> bool {
+ let mut ret = true;
unsafe {
LOCK.lock();
- init();
- (*QUEUE).push(f);
+ if init() {
+ (*QUEUE).push(f);
+ } else {
+ ret = false;
+ }
LOCK.unlock();
}
+ return ret
}
//! time being.
#![unstable(feature = "std_misc")]
-
-// FIXME: this should not be here.
#![allow(missing_docs)]
-#![allow(dead_code)]
-
-use marker::Send;
-use ops::FnOnce;
+use prelude::v1::*;
use sys;
use thunk::Thunk;
use usize;
use thread::Thread;
let something_around_the_top_of_the_stack = 1;
- let addr = &something_around_the_top_of_the_stack as *const int;
+ let addr = &something_around_the_top_of_the_stack as *const _ as *const int;
let my_stack_top = addr as uint;
// FIXME #11359 we just assume that this thread has a stack of a
/// Enqueues a procedure to run when the main thread exits.
///
-/// It is forbidden for procedures to register more `at_exit` handlers when they
-/// are running, and doing so will lead to a process abort.
+/// Currently these closures are only run once the main *Rust* thread exits.
+/// Once the `at_exit` handlers begin running, more may be enqueued, but not
+/// infinitely so. Eventually a handler registration will be forced to fail.
///
-/// Note that other threads may still be running when `at_exit` routines start
-/// running.
-pub fn at_exit<F: FnOnce() + Send + 'static>(f: F) {
- at_exit_imp::push(Thunk::new(f));
+/// Returns `Ok` if the handler was successfully registered, meaning that the
+/// closure will be run once the main thread exits. Returns `Err` to indicate
+/// that the closure could not be registered, meaning that it is not scheduled
+/// to be rune.
+pub fn at_exit<F: FnOnce() + Send + 'static>(f: F) -> Result<(), ()> {
+ if at_exit_imp::push(Thunk::new(f)) {Ok(())} else {Err(())}
}
/// One-time runtime cleanup.
/// # Examples
///
/// ```
+/// # #![feature(std_misc)]
/// use std::sync::{StaticCondvar, CONDVAR_INIT};
///
/// static CVAR: StaticCondvar = CONDVAR_INIT;
//! # Examples
//!
//! ```
+//! # #![feature(std_misc)]
//! use std::sync::Future;
//!
//! // a fake, for now
//! after 10 seconds no matter what:
//!
//! ```no_run
+//! # #![feature(std_misc, old_io)]
//! use std::sync::mpsc::channel;
//! use std::old_io::timer::Timer;
//! use std::time::Duration;
//! has been inactive for 5 seconds:
//!
//! ```no_run
+//! # #![feature(std_misc, old_io)]
//! use std::sync::mpsc::channel;
//! use std::old_io::timer::Timer;
//! use std::time::Duration;
}
#[stable(feature = "rust1", since = "1.0.0")]
-impl<T> error::Error for SendError<T> {
+impl<T: Send> error::Error for SendError<T> {
fn description(&self) -> &str {
"sending on a closed channel"
}
#[stable(feature = "rust1", since = "1.0.0")]
-impl<T> error::Error for TrySendError<T> {
+impl<T: Send> error::Error for TrySendError<T> {
fn description(&self) -> &str {
match *self {
//! # Examples
//!
//! ```rust
+//! # #![feature(std_misc)]
//! use std::sync::mpsc::channel;
//!
//! let (tx1, rx1) = channel();
/// # Examples
///
/// ```
+ /// # #![feature(std_misc)]
/// use std::sync::mpsc::Select;
///
/// let select = Select::new();
/// To recover from a poisoned mutex:
///
/// ```
+/// # #![feature(std_misc)]
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// # Examples
///
/// ```
+/// # #![feature(std_misc)]
/// use std::sync::{StaticMutex, MUTEX_INIT};
///
/// static LOCK: StaticMutex = MUTEX_INIT;
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Display for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- self.description().fmt(f)
+ "poisoned lock: another task failed inside".fmt(f)
}
}
-impl<T> Error for PoisonError<T> {
+impl<T: Send> Error for PoisonError<T> {
fn description(&self) -> &str {
"poisoned lock: another task failed inside"
}
}
#[stable(feature = "rust1", since = "1.0.0")]
-impl<T> fmt::Display for TryLockError<T> {
+impl<T: Send> fmt::Display for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
-impl<T> Error for TryLockError<T> {
+impl<T: Send> Error for TryLockError<T> {
fn description(&self) -> &str {
match *self {
TryLockError::Poisoned(ref p) => p.description(),
/// # Examples
///
/// ```
+/// # #![feature(std_misc)]
/// use std::sync::{StaticRwLock, RW_LOCK_INIT};
///
/// static LOCK: StaticRwLock = RW_LOCK_INIT;
/// # Examples
///
/// ```
+/// # #![feature(std_misc)]
/// use std::sync::Semaphore;
///
/// // Create a semaphore that represents 5 resources
/// # Examples
///
/// ```
+/// # #![feature(std_misc, core)]
/// use std::sync::TaskPool;
/// use std::iter::AdditiveIterator;
/// use std::sync::mpsc::channel;
self.cond.notify_one()
});
- rt::at_exit(move || { self.shutdown() });
+ let _ = rt::at_exit(move || { self.shutdown() });
*self.initialized.get() = true;
} else if *self.chan.get() as uint == 1 {
panic!("cannot continue usage after shutdown");
use cell::RefCell;
use string::String;
use thread::Thread;
-use thread_local::State;
+use thread::LocalKeyState;
struct ThreadInfo {
stack_guard: uint,
impl ThreadInfo {
fn with<R, F>(f: F) -> R where F: FnOnce(&mut ThreadInfo) -> R {
- if THREAD_INFO.state() == State::Destroyed {
+ if THREAD_INFO.state() == LocalKeyState::Destroyed {
panic!("Use of std::thread::current() is not possible after \
the thread's local data has been destroyed");
}
///
/// Panics when `begin` and `end` do not point to code point boundaries,
/// or point beyond the end of the string.
+#[cfg(stage0)]
impl ops::Index<ops::Range<usize>> for Wtf8 {
type Output = Wtf8;
}
}
+/// Return a slice of the given string for the byte range [`begin`..`end`).
+///
+/// # Panics
+///
+/// Panics when `begin` and `end` do not point to code point boundaries,
+/// or point beyond the end of the string.
+#[cfg(not(stage0))]
+impl ops::Index<ops::Range<usize>> for Wtf8 {
+ type Output = Wtf8;
+
+ #[inline]
+ fn index(&self, range: ops::Range<usize>) -> &Wtf8 {
+ // is_code_point_boundary checks that the index is in [0, .len()]
+ if range.start <= range.end &&
+ is_code_point_boundary(self, range.start) &&
+ is_code_point_boundary(self, range.end) {
+ unsafe { slice_unchecked(self, range.start, range.end) }
+ } else {
+ slice_error_fail(self, range.start, range.end)
+ }
+ }
+}
+
/// Return a slice of the given string from byte `begin` to its end.
///
/// # Panics
///
/// Panics when `begin` is not at a code point boundary,
/// or is beyond the end of the string.
+#[cfg(stage0)]
impl ops::Index<ops::RangeFrom<usize>> for Wtf8 {
type Output = Wtf8;
}
}
+/// Return a slice of the given string from byte `begin` to its end.
+///
+/// # Panics
+///
+/// Panics when `begin` is not at a code point boundary,
+/// or is beyond the end of the string.
+#[cfg(not(stage0))]
+impl ops::Index<ops::RangeFrom<usize>> for Wtf8 {
+ type Output = Wtf8;
+
+ #[inline]
+ fn index(&self, range: ops::RangeFrom<usize>) -> &Wtf8 {
+ // is_code_point_boundary checks that the index is in [0, .len()]
+ if is_code_point_boundary(self, range.start) {
+ unsafe { slice_unchecked(self, range.start, self.len()) }
+ } else {
+ slice_error_fail(self, range.start, self.len())
+ }
+ }
+}
+
/// Return a slice of the given string from its beginning to byte `end`.
///
/// # Panics
///
/// Panics when `end` is not at a code point boundary,
/// or is beyond the end of the string.
+#[cfg(stage0)]
impl ops::Index<ops::RangeTo<usize>> for Wtf8 {
type Output = Wtf8;
}
}
+/// Return a slice of the given string from its beginning to byte `end`.
+///
+/// # Panics
+///
+/// Panics when `end` is not at a code point boundary,
+/// or is beyond the end of the string.
+#[cfg(not(stage0))]
+impl ops::Index<ops::RangeTo<usize>> for Wtf8 {
+ type Output = Wtf8;
+
+ #[inline]
+ fn index(&self, range: ops::RangeTo<usize>) -> &Wtf8 {
+ // is_code_point_boundary checks that the index is in [0, .len()]
+ if is_code_point_boundary(self, range.end) {
+ unsafe { slice_unchecked(self, 0, range.end) }
+ } else {
+ slice_error_fail(self, 0, range.end)
+ }
+ }
+}
+
+#[cfg(stage0)]
impl ops::Index<ops::RangeFull> for Wtf8 {
type Output = Wtf8;
}
}
+#[cfg(not(stage0))]
+impl ops::Index<ops::RangeFull> for Wtf8 {
+ type Output = Wtf8;
+
+ #[inline]
+ fn index(&self, _range: ops::RangeFull) -> &Wtf8 {
+ self
+ }
+}
+
#[inline]
fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 {
// The first byte is assumed to be 0xED
}));
buf.set_len(n as usize);
}
- let s: OsString = OsStringExt::from_vec(buf);
- Ok(PathBuf::new(&s))
+ Ok(PathBuf::from(OsString::from_vec(buf)))
}
pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
const TMPBUF_SZ: usize = 128;
fn bytes2path(b: &[u8]) -> PathBuf {
- PathBuf::new(<OsStr as OsStrExt>::from_bytes(b))
+ PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
}
fn os2path(os: OsString) -> PathBuf {
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err != 0 { return Err(io::Error::last_os_error()); }
v.set_len(sz as uint - 1); // chop off trailing NUL
- Ok(PathBuf::new(OsString::from_vec(v)))
+ Ok(PathBuf::from(OsString::from_vec(v)))
}
}
pub fn temp_dir() -> PathBuf {
getenv("TMPDIR".as_os_str()).map(os2path).unwrap_or_else(|| {
if cfg!(target_os = "android") {
- PathBuf::new("/data/local/tmp")
+ PathBuf::from("/data/local/tmp")
} else {
- PathBuf::new("/tmp")
+ PathBuf::from("/tmp")
}
})
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub unsafe fn set_name(name: &str) {
- // pthread_setname_np() since glibc 2.12
- // availability autodetected via weak linkage
- type F = unsafe extern fn(libc::pthread_t, *const libc::c_char)
- -> libc::c_int;
+ // pthread wrapper only appeared in glibc 2.12, so we use syscall directly.
extern {
- #[linkage = "extern_weak"]
- static pthread_setname_np: *const ();
- }
- if !pthread_setname_np.is_null() {
- let cname = CString::new(name).unwrap();
- mem::transmute::<*const (), F>(pthread_setname_np)(pthread_self(),
- cname.as_ptr());
+ fn prctl(option: libc::c_int, arg2: libc::c_ulong, arg3: libc::c_ulong,
+ arg4: libc::c_ulong, arg5: libc::c_ulong) -> libc::c_int;
}
+ const PR_SET_NAME: libc::c_int = 15;
+ let cname = CString::new(name).unwrap_or_else(|_| {
+ panic!("thread name may not contain interior null bytes")
+ });
+ prctl(PR_SET_NAME, cname.as_ptr() as libc::c_ulong, 0, 0, 0);
}
#[cfg(any(target_os = "freebsd",
// is created in an application with big thread-local storage requirements.
// See #6233 for rationale and details.
//
-// Link weakly to the symbol for compatibility with older versions of glibc.
-// Assumes that we've been dynamically linked to libpthread but that is
-// currently always the case. Note that you need to check that the symbol
-// is non-null before calling it!
+// Use dlsym to get the symbol value at runtime, both for
+// compatibility with older versions of glibc, and to avoid creating
+// dependencies on GLIBC_PRIVATE symbols. Assumes that we've been
+// dynamically linked to libpthread but that is currently always the
+// case. We previously used weak linkage (under the same assumption),
+// but that caused Debian to detect an unnecessarily strict versioned
+// dependency on libc6 (#23628).
#[cfg(target_os = "linux")]
fn min_stack_size(attr: *const libc::pthread_attr_t) -> libc::size_t {
+ use dynamic_lib::DynamicLibrary;
+ use sync::{Once, ONCE_INIT};
+
type F = unsafe extern "C" fn(*const libc::pthread_attr_t) -> libc::size_t;
- extern {
- #[linkage = "extern_weak"]
- static __pthread_get_minstack: *const ();
- }
- if __pthread_get_minstack.is_null() {
- PTHREAD_STACK_MIN
- } else {
- unsafe { mem::transmute::<*const (), F>(__pthread_get_minstack)(attr) }
+ static INIT: Once = ONCE_INIT;
+ static mut __pthread_get_minstack: Option<F> = None;
+
+ INIT.call_once(|| {
+ let lib = DynamicLibrary::open(None).unwrap();
+ unsafe {
+ if let Ok(f) = lib.symbol("__pthread_get_minstack") {
+ __pthread_get_minstack = Some(mem::transmute::<*const (), F>(f));
+ }
+ }
+ });
+
+ match unsafe { __pthread_get_minstack } {
+ None => PTHREAD_STACK_MIN,
+ Some(f) => unsafe { f(attr) },
}
}
-// __pthread_get_minstack() is marked as weak but extern_weak linkage is
-// not supported on OS X, hence this kludge...
+// No point in looking up __pthread_get_minstack() on non-glibc
+// platforms.
#[cfg(not(target_os = "linux"))]
fn min_stack_size(_: *const libc::pthread_attr_t) -> libc::size_t {
PTHREAD_STACK_MIN
sz - 1,
libc::VOLUME_NAME_DOS)
}, |s| OsStringExt::from_wide(s)));
- Ok(PathBuf::new(&ret))
+ Ok(PathBuf::from(&ret))
}
pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
}
fn os2path(s: &[u16]) -> PathBuf {
- let os = <OsString as OsStringExt>::from_wide(s);
- // FIXME(#22751) should consume `os`
- PathBuf::new(&os)
+ PathBuf::from(OsString::from_wide(s))
}
pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
if *self.cur == 0 { return None }
let p = &*self.cur;
let mut len = 0;
- while *(p as *const _).offset(len) != 0 {
+ while *(p as *const u16).offset(len) != 0 {
len += 1;
}
let p = p as *const u16;
pub fn home_dir() -> Option<PathBuf> {
getenv("HOME".as_os_str()).or_else(|| {
getenv("USERPROFILE".as_os_str())
- }).map(|os| {
- // FIXME(#22751) should consume `os`
- PathBuf::new(&os)
- }).or_else(|| unsafe {
+ }).map(PathBuf::from).or_else(|| unsafe {
let me = c::GetCurrentProcess();
let mut token = ptr::null_mut();
if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
+++ /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.
-
-//! Native threads
-//!
-//! ## The threading model
-//!
-//! An executing Rust program consists of a collection of native OS threads,
-//! each with their own stack and local state.
-//!
-//! Communication between threads can be done through
-//! [channels](../../std/sync/mpsc/index.html), Rust's message-passing
-//! types, along with [other forms of thread
-//! synchronization](../../std/sync/index.html) and shared-memory data
-//! structures. In particular, types that are guaranteed to be
-//! threadsafe are easily shared between threads using the
-//! atomically-reference-counted container,
-//! [`Arc`](../../std/sync/struct.Arc.html).
-//!
-//! Fatal logic errors in Rust cause *thread panic*, during which
-//! a thread will unwind the stack, running destructors and freeing
-//! owned resources. Thread panic is unrecoverable from within
-//! the panicking thread (i.e. there is no 'try/catch' in Rust), but
-//! the panic may optionally be detected from a different thread. If
-//! the main thread panics, the application will exit with a non-zero
-//! exit code.
-//!
-//! When the main thread of a Rust program terminates, the entire program shuts
-//! down, even if other threads are still running. However, this module provides
-//! convenient facilities for automatically waiting for the termination of a
-//! child thread (i.e., join).
-//!
-//! ## The `Thread` type
-//!
-//! Threads are represented via the `Thread` type, which you can
-//! get in one of two ways:
-//!
-//! * By spawning a new thread, e.g. using the `thread::spawn` function.
-//! * By requesting the current thread, using the `thread::current` function.
-//!
-//! Threads can be named, and provide some built-in support for low-level
-//! synchronization (described below).
-//!
-//! The `thread::current()` function is available even for threads not spawned
-//! by the APIs of this module.
-//!
-//! ## Spawning a thread
-//!
-//! A new thread can be spawned using the `thread::spawn` function:
-//!
-//! ```rust
-//! use std::thread;
-//!
-//! thread::spawn(move || {
-//! // some work here
-//! });
-//! ```
-//!
-//! In this example, the spawned thread is "detached" from the current
-//! thread. This means that it can outlive its parent (the thread that spawned
-//! it), unless this parent is the main thread.
-//!
-//! ## Scoped threads
-//!
-//! Often a parent thread uses a child thread to perform some particular task,
-//! and at some point must wait for the child to complete before continuing.
-//! For this scenario, use the `thread::scoped` function:
-//!
-//! ```rust
-//! use std::thread;
-//!
-//! let guard = thread::scoped(move || {
-//! // some work here
-//! });
-//!
-//! // do some other work in the meantime
-//! let output = guard.join();
-//! ```
-//!
-//! The `scoped` function doesn't return a `Thread` directly; instead,
-//! it returns a *join guard*. The join guard is an RAII-style guard
-//! that will automatically join the child thread (block until it
-//! terminates) when it is dropped. You can join the child thread in
-//! advance by calling the `join` method on the guard, which will also
-//! return the result produced by the thread. A handle to the thread
-//! itself is available via the `thread` method of the join guard.
-//!
-//! ## Configuring threads
-//!
-//! A new thread can be configured before it is spawned via the `Builder` type,
-//! which currently allows you to set the name, stack size, and writers for
-//! `println!` and `panic!` for the child thread:
-//!
-//! ```rust
-//! use std::thread;
-//!
-//! thread::Builder::new().name("child1".to_string()).spawn(move || {
-//! println!("Hello, world!");
-//! });
-//! ```
-//!
-//! ## Blocking support: park and unpark
-//!
-//! Every thread is equipped with some basic low-level blocking support, via the
-//! `park` and `unpark` functions.
-//!
-//! Conceptually, each `Thread` handle has an associated token, which is
-//! initially not present:
-//!
-//! * The `thread::park()` function blocks the current thread unless or until
-//! the token is available for its thread handle, at which point it atomically
-//! consumes the token. It may also return *spuriously*, without consuming the
-//! token. `thread::park_timeout()` does the same, but allows specifying a
-//! maximum time to block the thread for.
-//!
-//! * The `unpark()` method on a `Thread` atomically makes the token available
-//! if it wasn't already.
-//!
-//! In other words, each `Thread` acts a bit like a semaphore with initial count
-//! 0, except that the semaphore is *saturating* (the count cannot go above 1),
-//! and can return spuriously.
-//!
-//! The API is typically used by acquiring a handle to the current thread,
-//! placing that handle in a shared data structure so that other threads can
-//! find it, and then `park`ing. When some desired condition is met, another
-//! thread calls `unpark` on the handle.
-//!
-//! The motivation for this design is twofold:
-//!
-//! * It avoids the need to allocate mutexes and condvars when building new
-//! synchronization primitives; the threads already provide basic blocking/signaling.
-//!
-//! * It can be implemented very efficiently on many platforms.
-
-#![stable(feature = "rust1", since = "1.0.0")]
-
-use prelude::v1::*;
-
-use any::Any;
-use cell::UnsafeCell;
-use fmt;
-use io;
-use marker::PhantomData;
-use rt::{self, unwind};
-use sync::{Mutex, Condvar, Arc};
-use sys::thread as imp;
-use sys_common::{stack, thread_info};
-use thunk::Thunk;
-use time::Duration;
-
-#[allow(deprecated)] use old_io::Writer;
-
-/// Thread configuration. Provides detailed control over the properties
-/// and behavior of new threads.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Builder {
- // A name for the thread-to-be, for identification in panic messages
- name: Option<String>,
- // The size of the stack for the spawned thread
- stack_size: Option<usize>,
-}
-
-impl Builder {
- /// Generate the base configuration for spawning a thread, from which
- /// configuration methods can be chained.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn new() -> Builder {
- Builder {
- name: None,
- stack_size: None,
- }
- }
-
- /// Name the thread-to-be. Currently the name is used for identification
- /// only in panic messages.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn name(mut self, name: String) -> Builder {
- self.name = Some(name);
- self
- }
-
- /// Set the size of the stack for the new thread.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn stack_size(mut self, size: usize) -> Builder {
- self.stack_size = Some(size);
- self
- }
-
- /// Redirect thread-local stdout.
- #[unstable(feature = "std_misc",
- reason = "Will likely go away after proc removal")]
- #[deprecated(since = "1.0.0",
- reason = "the old I/O module is deprecated and this function \
- will be removed with no replacement")]
- #[allow(deprecated)]
- pub fn stdout(self, _stdout: Box<Writer + Send + 'static>) -> Builder {
- self
- }
-
- /// Redirect thread-local stderr.
- #[unstable(feature = "std_misc",
- reason = "Will likely go away after proc removal")]
- #[deprecated(since = "1.0.0",
- reason = "the old I/O module is deprecated and this function \
- will be removed with no replacement")]
- #[allow(deprecated)]
- pub fn stderr(self, _stderr: Box<Writer + Send + 'static>) -> Builder {
- self
- }
-
- /// Spawn a new thread, and return a join handle for it.
- ///
- /// The child thread may outlive the parent (unless the parent thread
- /// is the main thread; the whole process is terminated when the main
- /// thread finishes.) The join handle can be used to block on
- /// termination of the child thread, including recovering its panics.
- ///
- /// # Errors
- ///
- /// Unlike the `spawn` free function, this method yields an
- /// `io::Result` to capture any failure to create the thread at
- /// the OS level.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn spawn<F>(self, f: F) -> io::Result<JoinHandle> where
- F: FnOnce(), F: Send + 'static
- {
- self.spawn_inner(Thunk::new(f)).map(|i| JoinHandle(i))
- }
-
- /// Spawn a new child thread that must be joined within a given
- /// scope, and return a `JoinGuard`.
- ///
- /// The join guard can be used to explicitly join the child thread (via
- /// `join`), returning `Result<T>`, or it will implicitly join the child
- /// upon being dropped. Because the child thread may refer to data on the
- /// current thread's stack (hence the "scoped" name), it cannot be detached;
- /// it *must* be joined before the relevant stack frame is popped. See the
- /// module documentation for additional details.
- ///
- /// # Errors
- ///
- /// Unlike the `scoped` free function, this method yields an
- /// `io::Result` to capture any failure to create the thread at
- /// the OS level.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn scoped<'a, T, F>(self, f: F) -> io::Result<JoinGuard<'a, T>> where
- T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
- {
- self.spawn_inner(Thunk::new(f)).map(|inner| {
- JoinGuard { inner: inner, _marker: PhantomData }
- })
- }
-
- fn spawn_inner<T: Send>(self, f: Thunk<(), T>) -> io::Result<JoinInner<T>> {
- let Builder { name, stack_size } = self;
-
- let stack_size = stack_size.unwrap_or(rt::min_stack());
-
- let my_thread = Thread::new(name);
- let their_thread = my_thread.clone();
-
- let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
- let their_packet = Packet(my_packet.0.clone());
-
- // Spawning a new OS thread guarantees that __morestack will never get
- // triggered, but we must manually set up the actual stack bounds once
- // this function starts executing. This raises the lower limit by a bit
- // because by the time that this function is executing we've already
- // consumed at least a little bit of stack (we don't know the exact byte
- // address at which our stack started).
- let main = move || {
- let something_around_the_top_of_the_stack = 1;
- let addr = &something_around_the_top_of_the_stack as *const i32;
- let my_stack_top = addr as usize;
- let my_stack_bottom = my_stack_top - stack_size + 1024;
- unsafe {
- if let Some(name) = their_thread.name() {
- imp::set_name(name);
- }
- stack::record_os_managed_stack_bounds(my_stack_bottom,
- my_stack_top);
- thread_info::set(imp::guard::current(), their_thread);
- }
-
- let mut output = None;
- let try_result = {
- let ptr = &mut output;
-
- // There are two primary reasons that general try/catch is
- // unsafe. The first is that we do not support nested
- // try/catch. The fact that this is happening in a newly-spawned
- // thread suffices. The second is that unwinding while unwinding
- // is not defined. We take care of that by having an
- // 'unwinding' flag in the thread itself. For these reasons,
- // this unsafety should be ok.
- unsafe {
- unwind::try(move || *ptr = Some(f.invoke(())))
- }
- };
- unsafe {
- *their_packet.0.get() = Some(match (output, try_result) {
- (Some(data), Ok(_)) => Ok(data),
- (None, Err(cause)) => Err(cause),
- _ => unreachable!()
- });
- }
- };
-
- Ok(JoinInner {
- native: try!(unsafe { imp::create(stack_size, Thunk::new(main)) }),
- thread: my_thread,
- packet: my_packet,
- joined: false,
- })
- }
-}
-
-/// Spawn a new thread, returning a `JoinHandle` for it.
-///
-/// The join handle will implicitly *detach* the child thread upon being
-/// dropped. In this case, the child thread may outlive the parent (unless
-/// the parent thread is the main thread; the whole process is terminated when
-/// the main thread finishes.) Additionally, the join handle provides a `join`
-/// method that can be used to join the child thread. If the child thread
-/// panics, `join` will return an `Err` containing the argument given to
-/// `panic`.
-///
-/// # Panics
-///
-/// Panicks if the OS fails to create a thread; use `Builder::spawn`
-/// to recover from such errors.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub fn spawn<F>(f: F) -> JoinHandle where F: FnOnce(), F: Send + 'static {
- Builder::new().spawn(f).unwrap()
-}
-
-/// Spawn a new *scoped* thread, returning a `JoinGuard` for it.
-///
-/// The join guard can be used to explicitly join the child thread (via
-/// `join`), returning `Result<T>`, or it will implicitly join the child
-/// upon being dropped. Because the child thread may refer to data on the
-/// current thread's stack (hence the "scoped" name), it cannot be detached;
-/// it *must* be joined before the relevant stack frame is popped. See the
-/// module documentation for additional details.
-///
-/// # Panics
-///
-/// Panicks if the OS fails to create a thread; use `Builder::scoped`
-/// to recover from such errors.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
- T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
-{
- Builder::new().scoped(f).unwrap()
-}
-
-/// Gets a handle to the thread that invokes it.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub fn current() -> Thread {
- thread_info::current_thread()
-}
-
-/// Cooperatively give up a timeslice to the OS scheduler.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub fn yield_now() {
- unsafe { imp::yield_now() }
-}
-
-/// Determines whether the current thread is unwinding because of panic.
-#[inline]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub fn panicking() -> bool {
- unwind::panicking()
-}
-
-/// Put the current thread to sleep for the specified amount of time.
-///
-/// The thread may sleep longer than the duration specified due to scheduling
-/// specifics or platform-dependent functionality. Note that on unix platforms
-/// this function will not return early due to a signal being received or a
-/// spurious wakeup.
-#[unstable(feature = "thread_sleep",
- reason = "recently added, needs an RFC, and `Duration` itself is \
- unstable")]
-pub fn sleep(dur: Duration) {
- imp::sleep(dur)
-}
-
-/// Block unless or until the current thread's token is made available (may wake spuriously).
-///
-/// See the module doc for more detail.
-//
-// The implementation currently uses the trivial strategy of a Mutex+Condvar
-// with wakeup flag, which does not actually allow spurious wakeups. In the
-// future, this will be implemented in a more efficient way, perhaps along the lines of
-// http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
-// or futuxes, and in either case may allow spurious wakeups.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub fn park() {
- let thread = current();
- let mut guard = thread.inner.lock.lock().unwrap();
- while !*guard {
- guard = thread.inner.cvar.wait(guard).unwrap();
- }
- *guard = false;
-}
-
-/// Block unless or until the current thread's token is made available or
-/// the specified duration has been reached (may wake spuriously).
-///
-/// The semantics of this function are equivalent to `park()` except that the
-/// thread will be blocked for roughly no longer than *duration*. This method
-/// should not be used for precise timing due to anomalies such as
-/// preemption or platform differences that may not cause the maximum
-/// amount of time waited to be precisely *duration* long.
-///
-/// See the module doc for more detail.
-#[unstable(feature = "std_misc", reason = "recently introduced, depends on Duration")]
-pub fn park_timeout(duration: Duration) {
- let thread = current();
- let mut guard = thread.inner.lock.lock().unwrap();
- if !*guard {
- let (g, _) = thread.inner.cvar.wait_timeout(guard, duration).unwrap();
- guard = g;
- }
- *guard = false;
-}
-
-/// The internal representation of a `Thread` handle
-struct Inner {
- name: Option<String>,
- lock: Mutex<bool>, // true when there is a buffered unpark
- cvar: Condvar,
-}
-
-unsafe impl Sync for Inner {}
-
-#[derive(Clone)]
-#[stable(feature = "rust1", since = "1.0.0")]
-/// A handle to a thread.
-pub struct Thread {
- inner: Arc<Inner>,
-}
-
-impl Thread {
- // Used only internally to construct a thread object without spawning
- fn new(name: Option<String>) -> Thread {
- Thread {
- inner: Arc::new(Inner {
- name: name,
- lock: Mutex::new(false),
- cvar: Condvar::new(),
- })
- }
- }
-
- /// Deprecated: use module-level free function.
- #[deprecated(since = "1.0.0", reason = "use module-level free function")]
- #[unstable(feature = "std_misc",
- reason = "may change with specifics of new Send semantics")]
- pub fn spawn<F>(f: F) -> Thread where F: FnOnce(), F: Send + 'static {
- Builder::new().spawn(f).unwrap().thread().clone()
- }
-
- /// Deprecated: use module-level free function.
- #[deprecated(since = "1.0.0", reason = "use module-level free function")]
- #[unstable(feature = "std_misc",
- reason = "may change with specifics of new Send semantics")]
- pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
- T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
- {
- Builder::new().scoped(f).unwrap()
- }
-
- /// Deprecated: use module-level free function.
- #[deprecated(since = "1.0.0", reason = "use module-level free function")]
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn current() -> Thread {
- thread_info::current_thread()
- }
-
- /// Deprecated: use module-level free function.
- #[deprecated(since = "1.0.0", reason = "use module-level free function")]
- #[unstable(feature = "std_misc", reason = "name may change")]
- pub fn yield_now() {
- unsafe { imp::yield_now() }
- }
-
- /// Deprecated: use module-level free function.
- #[deprecated(since = "1.0.0", reason = "use module-level free function")]
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn panicking() -> bool {
- unwind::panicking()
- }
-
- /// Deprecated: use module-level free function.
- #[deprecated(since = "1.0.0", reason = "use module-level free function")]
- #[unstable(feature = "std_misc", reason = "recently introduced")]
- pub fn park() {
- let thread = current();
- let mut guard = thread.inner.lock.lock().unwrap();
- while !*guard {
- guard = thread.inner.cvar.wait(guard).unwrap();
- }
- *guard = false;
- }
-
- /// Deprecated: use module-level free function.
- #[deprecated(since = "1.0.0", reason = "use module-level free function")]
- #[unstable(feature = "std_misc", reason = "recently introduced")]
- pub fn park_timeout(duration: Duration) {
- let thread = current();
- let mut guard = thread.inner.lock.lock().unwrap();
- if !*guard {
- let (g, _) = thread.inner.cvar.wait_timeout(guard, duration).unwrap();
- guard = g;
- }
- *guard = false;
- }
-
- /// Atomically makes the handle's token available if it is not already.
- ///
- /// See the module doc for more detail.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn unpark(&self) {
- let mut guard = self.inner.lock.lock().unwrap();
- if !*guard {
- *guard = true;
- self.inner.cvar.notify_one();
- }
- }
-
- /// Get the thread's name.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn name(&self) -> Option<&str> {
- self.inner.name.as_ref().map(|s| &**s)
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl fmt::Debug for Thread {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- fmt::Debug::fmt(&self.name(), f)
- }
-}
-
-// a hack to get around privacy restrictions
-impl thread_info::NewThread for Thread {
- fn new(name: Option<String>) -> Thread { Thread::new(name) }
-}
-
-/// Indicates the manner in which a thread exited.
-///
-/// A thread that completes without panicking is considered to exit successfully.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
-
-struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
-
-unsafe impl<T:Send> Send for Packet<T> {}
-unsafe impl<T> Sync for Packet<T> {}
-
-/// Inner representation for JoinHandle and JoinGuard
-struct JoinInner<T> {
- native: imp::rust_thread,
- thread: Thread,
- packet: Packet<T>,
- joined: bool,
-}
-
-impl<T> JoinInner<T> {
- fn join(&mut self) -> Result<T> {
- assert!(!self.joined);
- unsafe { imp::join(self.native) };
- self.joined = true;
- unsafe {
- (*self.packet.0.get()).take().unwrap()
- }
- }
-}
-
-/// An owned permission to join on a thread (block on its termination).
-///
-/// Unlike a `JoinGuard`, a `JoinHandle` *detaches* the child thread
-/// when it is dropped, rather than automatically joining on drop.
-///
-/// Due to platform restrictions, it is not possible to `Clone` this
-/// handle: the ability to join a child thread is a uniquely-owned
-/// permission.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct JoinHandle(JoinInner<()>);
-
-impl JoinHandle {
- /// Extract a handle to the underlying thread
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn thread(&self) -> &Thread {
- &self.0.thread
- }
-
- /// Wait for the associated thread to finish.
- ///
- /// If the child thread panics, `Err` is returned with the parameter given
- /// to `panic`.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn join(mut self) -> Result<()> {
- self.0.join()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl Drop for JoinHandle {
- fn drop(&mut self) {
- if !self.0.joined {
- unsafe { imp::detach(self.0.native) }
- }
- }
-}
-
-/// An RAII-style guard that will block until thread termination when dropped.
-///
-/// The type `T` is the return type for the thread's main function.
-///
-/// Joining on drop is necessary to ensure memory safety when stack
-/// data is shared between a parent and child thread.
-///
-/// Due to platform restrictions, it is not possible to `Clone` this
-/// handle: the ability to join a child thread is a uniquely-owned
-/// permission.
-#[must_use = "thread will be immediately joined if `JoinGuard` is not used"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct JoinGuard<'a, T: 'a> {
- inner: JoinInner<T>,
- _marker: PhantomData<&'a T>,
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}
-
-impl<'a, T: Send + 'a> JoinGuard<'a, T> {
- /// Extract a handle to the thread this guard will join on.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn thread(&self) -> &Thread {
- &self.inner.thread
- }
-
- /// Wait for the associated thread to finish, returning the result of the thread's
- /// calculation.
- ///
- /// # Panics
- ///
- /// Panics on the child thread are propagated by panicking the parent.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn join(mut self) -> T {
- match self.inner.join() {
- Ok(res) => res,
- Err(_) => panic!("child thread {:?} panicked", self.thread()),
- }
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T: Send> JoinGuard<'static, T> {
- /// Detaches the child thread, allowing it to outlive its parent.
- #[deprecated(since = "1.0.0", reason = "use spawn instead")]
- #[unstable(feature = "std_misc")]
- pub fn detach(mut self) {
- unsafe { imp::detach(self.inner.native) };
- self.inner.joined = true; // avoid joining in the destructor
- }
-}
-
-#[unsafe_destructor]
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
- fn drop(&mut self) {
- if !self.inner.joined {
- if self.inner.join().is_err() {
- panic!("child thread {:?} panicked", self.thread());
- }
- }
- }
-}
-
-#[cfg(test)]
-mod test {
- use prelude::v1::*;
-
- use any::Any;
- use sync::mpsc::{channel, Sender};
- use boxed::BoxAny;
- use result;
- use std::old_io::{ChanReader, ChanWriter};
- use super::{Builder};
- use thread;
- use thunk::Thunk;
- use time::Duration;
-
- // !!! These tests are dangerous. If something is buggy, they will hang, !!!
- // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
-
- #[test]
- fn test_unnamed_thread() {
- thread::spawn(move|| {
- assert!(thread::current().name().is_none());
- }).join().ok().unwrap();
- }
-
- #[test]
- fn test_named_thread() {
- Builder::new().name("ada lovelace".to_string()).scoped(move|| {
- assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
- }).unwrap().join();
- }
-
- #[test]
- fn test_run_basic() {
- let (tx, rx) = channel();
- thread::spawn(move|| {
- tx.send(()).unwrap();
- });
- rx.recv().unwrap();
- }
-
- #[test]
- fn test_join_success() {
- assert!(thread::scoped(move|| -> String {
- "Success!".to_string()
- }).join() == "Success!");
- }
-
- #[test]
- fn test_join_panic() {
- match thread::spawn(move|| {
- panic!()
- }).join() {
- result::Result::Err(_) => (),
- result::Result::Ok(()) => panic!()
- }
- }
-
- #[test]
- fn test_scoped_success() {
- let res = thread::scoped(move|| -> String {
- "Success!".to_string()
- }).join();
- assert!(res == "Success!");
- }
-
- #[test]
- #[should_fail]
- fn test_scoped_panic() {
- thread::scoped(|| panic!()).join();
- }
-
- #[test]
- #[should_fail]
- fn test_scoped_implicit_panic() {
- let _ = thread::scoped(|| panic!());
- }
-
- #[test]
- fn test_spawn_sched() {
- use clone::Clone;
-
- let (tx, rx) = channel();
-
- fn f(i: i32, tx: Sender<()>) {
- let tx = tx.clone();
- thread::spawn(move|| {
- if i == 0 {
- tx.send(()).unwrap();
- } else {
- f(i - 1, tx);
- }
- });
-
- }
- f(10, tx);
- rx.recv().unwrap();
- }
-
- #[test]
- fn test_spawn_sched_childs_on_default_sched() {
- let (tx, rx) = channel();
-
- thread::spawn(move|| {
- thread::spawn(move|| {
- tx.send(()).unwrap();
- });
- });
-
- rx.recv().unwrap();
- }
-
- fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk<'static>) {
- let (tx, rx) = channel();
-
- let x: Box<_> = box 1;
- let x_in_parent = (&*x) as *const i32 as usize;
-
- spawnfn(Thunk::new(move|| {
- let x_in_child = (&*x) as *const i32 as usize;
- tx.send(x_in_child).unwrap();
- }));
-
- let x_in_child = rx.recv().unwrap();
- assert_eq!(x_in_parent, x_in_child);
- }
-
- #[test]
- fn test_avoid_copying_the_body_spawn() {
- avoid_copying_the_body(|v| {
- thread::spawn(move || v.invoke(()));
- });
- }
-
- #[test]
- fn test_avoid_copying_the_body_thread_spawn() {
- avoid_copying_the_body(|f| {
- thread::spawn(move|| {
- f.invoke(());
- });
- })
- }
-
- #[test]
- fn test_avoid_copying_the_body_join() {
- avoid_copying_the_body(|f| {
- let _ = thread::spawn(move|| {
- f.invoke(())
- }).join();
- })
- }
-
- #[test]
- fn test_child_doesnt_ref_parent() {
- // If the child refcounts the parent task, this will stack overflow when
- // climbing the task tree to dereference each ancestor. (See #1789)
- // (well, it would if the constant were 8000+ - I lowered it to be more
- // valgrind-friendly. try this at home, instead..!)
- const GENERATIONS: u32 = 16;
- fn child_no(x: u32) -> Thunk<'static> {
- return Thunk::new(move|| {
- if x < GENERATIONS {
- thread::spawn(move|| child_no(x+1).invoke(()));
- }
- });
- }
- thread::spawn(|| child_no(0).invoke(()));
- }
-
- #[test]
- fn test_simple_newsched_spawn() {
- thread::spawn(move || {});
- }
-
- #[test]
- fn test_try_panic_message_static_str() {
- match thread::spawn(move|| {
- panic!("static string");
- }).join() {
- Err(e) => {
- type T = &'static str;
- assert!(e.is::<T>());
- assert_eq!(*e.downcast::<T>().unwrap(), "static string");
- }
- Ok(()) => panic!()
- }
- }
-
- #[test]
- fn test_try_panic_message_owned_str() {
- match thread::spawn(move|| {
- panic!("owned string".to_string());
- }).join() {
- Err(e) => {
- type T = String;
- assert!(e.is::<T>());
- assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
- }
- Ok(()) => panic!()
- }
- }
-
- #[test]
- fn test_try_panic_message_any() {
- match thread::spawn(move|| {
- panic!(box 413u16 as Box<Any + Send>);
- }).join() {
- Err(e) => {
- type T = Box<Any + Send>;
- assert!(e.is::<T>());
- let any = e.downcast::<T>().unwrap();
- assert!(any.is::<u16>());
- assert_eq!(*any.downcast::<u16>().unwrap(), 413);
- }
- Ok(()) => panic!()
- }
- }
-
- #[test]
- fn test_try_panic_message_unit_struct() {
- struct Juju;
-
- match thread::spawn(move|| {
- panic!(Juju)
- }).join() {
- Err(ref e) if e.is::<Juju>() => {}
- Err(_) | Ok(()) => panic!()
- }
- }
-
- #[test]
- fn test_park_timeout_unpark_before() {
- for _ in 0..10 {
- thread::current().unpark();
- thread::park_timeout(Duration::seconds(10_000_000));
- }
- }
-
- #[test]
- fn test_park_timeout_unpark_not_called() {
- for _ in 0..10 {
- thread::park_timeout(Duration::milliseconds(10));
- }
- }
-
- #[test]
- fn test_park_timeout_unpark_called_other_thread() {
- use std::old_io;
-
- for _ in 0..10 {
- let th = thread::current();
-
- let _guard = thread::spawn(move || {
- old_io::timer::sleep(Duration::milliseconds(50));
- th.unpark();
- });
-
- thread::park_timeout(Duration::seconds(10_000_000));
- }
- }
-
- #[test]
- fn sleep_smoke() {
- thread::sleep(Duration::milliseconds(2));
- thread::sleep(Duration::milliseconds(-2));
- }
-
- // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
- // to the test harness apparently interfering with stderr configuration.
-}
--- /dev/null
+// 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.
+//
+// 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.
+
+//! Thread local storage
+
+#![unstable(feature = "thread_local_internals")]
+
+use prelude::v1::*;
+
+use cell::UnsafeCell;
+
+// Sure wish we had macro hygiene, no?
+#[doc(hidden)]
+#[unstable(feature = "thread_local_internals")]
+pub mod __impl {
+ pub use super::imp::Key as KeyInner;
+ pub use super::imp::destroy_value;
+ pub use sys_common::thread_local::INIT_INNER as OS_INIT_INNER;
+ pub use sys_common::thread_local::StaticKey as OsStaticKey;
+}
+
+/// A thread local storage key which owns its contents.
+///
+/// This key uses the fastest possible implementation available to it for the
+/// target platform. It is instantiated with the `thread_local!` macro and the
+/// primary method is the `with` method.
+///
+/// The `with` method yields a reference to the contained value which cannot be
+/// sent across tasks or escape the given closure.
+///
+/// # Initialization and Destruction
+///
+/// Initialization is dynamically performed on the first call to `with()`
+/// within a thread, and values support destructors which will be run when a
+/// thread exits.
+///
+/// # Examples
+///
+/// ```
+/// use std::cell::RefCell;
+/// use std::thread;
+///
+/// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
+///
+/// FOO.with(|f| {
+/// assert_eq!(*f.borrow(), 1);
+/// *f.borrow_mut() = 2;
+/// });
+///
+/// // each thread starts out with the initial value of 1
+/// thread::spawn(move|| {
+/// FOO.with(|f| {
+/// assert_eq!(*f.borrow(), 1);
+/// *f.borrow_mut() = 3;
+/// });
+/// });
+///
+/// // we retain our original value of 2 despite the child thread
+/// FOO.with(|f| {
+/// assert_eq!(*f.borrow(), 2);
+/// });
+/// ```
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct LocalKey<T> {
+ // The key itself may be tagged with #[thread_local], and this `Key` is
+ // stored as a `static`, and it's not valid for a static to reference the
+ // address of another thread_local static. For this reason we kinda wonkily
+ // work around this by generating a shim function which will give us the
+ // address of the inner TLS key at runtime.
+ //
+ // This is trivially devirtualizable by LLVM because we never store anything
+ // to this field and rustc can declare the `static` as constant as well.
+ #[doc(hidden)]
+ #[unstable(feature = "thread_local_internals")]
+ pub inner: fn() -> &'static __impl::KeyInner<UnsafeCell<Option<T>>>,
+
+ // initialization routine to invoke to create a value
+ #[doc(hidden)]
+ #[unstable(feature = "thread_local_internals")]
+ pub init: fn() -> T,
+}
+
+/// Declare a new thread local storage key of type `std::thread::LocalKey`.
+#[macro_export]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[allow_internal_unstable]
+macro_rules! thread_local {
+ (static $name:ident: $t:ty = $init:expr) => (
+ static $name: ::std::thread::LocalKey<$t> = {
+ use std::cell::UnsafeCell as __UnsafeCell;
+ use std::thread::__local::__impl::KeyInner as __KeyInner;
+ use std::option::Option as __Option;
+ use std::option::Option::None as __None;
+
+ __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = {
+ __UnsafeCell { value: __None }
+ });
+ fn __init() -> $t { $init }
+ fn __getit() -> &'static __KeyInner<__UnsafeCell<__Option<$t>>> {
+ &__KEY
+ }
+ ::std::thread::LocalKey { inner: __getit, init: __init }
+ };
+ );
+ (pub static $name:ident: $t:ty = $init:expr) => (
+ pub static $name: ::std::thread::LocalKey<$t> = {
+ use std::cell::UnsafeCell as __UnsafeCell;
+ use std::thread::__local::__impl::KeyInner as __KeyInner;
+ use std::option::Option as __Option;
+ use std::option::Option::None as __None;
+
+ __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = {
+ __UnsafeCell { value: __None }
+ });
+ fn __init() -> $t { $init }
+ fn __getit() -> &'static __KeyInner<__UnsafeCell<__Option<$t>>> {
+ &__KEY
+ }
+ ::std::thread::LocalKey { inner: __getit, init: __init }
+ };
+ );
+}
+
+// Macro pain #4586:
+//
+// When cross compiling, rustc will load plugins and macros from the *host*
+// platform before search for macros from the target platform. This is primarily
+// done to detect, for example, plugins. Ideally the macro below would be
+// defined once per module below, but unfortunately this means we have the
+// following situation:
+//
+// 1. We compile libstd for x86_64-unknown-linux-gnu, this thread_local!() macro
+// will inject #[thread_local] statics.
+// 2. We then try to compile a program for arm-linux-androideabi
+// 3. The compiler has a host of linux and a target of android, so it loads
+// macros from the *linux* libstd.
+// 4. The macro generates a #[thread_local] field, but the android libstd does
+// not use #[thread_local]
+// 5. Compile error about structs with wrong fields.
+//
+// To get around this, we're forced to inject the #[cfg] logic into the macro
+// itself. Woohoo.
+
+#[macro_export]
+#[doc(hidden)]
+#[allow_internal_unstable]
+macro_rules! __thread_local_inner {
+ (static $name:ident: $t:ty = $init:expr) => (
+ #[cfg_attr(all(any(target_os = "macos", target_os = "linux"),
+ not(target_arch = "aarch64")),
+ thread_local)]
+ static $name: ::std::thread::__local::__impl::KeyInner<$t> =
+ __thread_local_inner!($init, $t);
+ );
+ (pub static $name:ident: $t:ty = $init:expr) => (
+ #[cfg_attr(all(any(target_os = "macos", target_os = "linux"),
+ not(target_arch = "aarch64")),
+ thread_local)]
+ pub static $name: ::std::thread::__local::__impl::KeyInner<$t> =
+ __thread_local_inner!($init, $t);
+ );
+ ($init:expr, $t:ty) => ({
+ #[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))]
+ const _INIT: ::std::thread::__local::__impl::KeyInner<$t> = {
+ ::std::thread::__local::__impl::KeyInner {
+ inner: ::std::cell::UnsafeCell { value: $init },
+ dtor_registered: ::std::cell::UnsafeCell { value: false },
+ dtor_running: ::std::cell::UnsafeCell { value: false },
+ }
+ };
+
+ #[allow(trivial_casts)]
+ #[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))]
+ const _INIT: ::std::thread::__local::__impl::KeyInner<$t> = {
+ ::std::thread::__local::__impl::KeyInner {
+ inner: ::std::cell::UnsafeCell { value: $init },
+ os: ::std::thread::__local::__impl::OsStaticKey {
+ inner: ::std::thread::__local::__impl::OS_INIT_INNER,
+ dtor: ::std::option::Option::Some(
+ ::std::thread::__local::__impl::destroy_value::<$t>
+ ),
+ },
+ }
+ };
+
+ _INIT
+ });
+}
+
+/// Indicator of the state of a thread local storage key.
+#[unstable(feature = "std_misc",
+ reason = "state querying was recently added")]
+#[derive(Eq, PartialEq, Copy)]
+pub enum LocalKeyState {
+ /// All keys are in this state whenever a thread starts. Keys will
+ /// transition to the `Valid` state once the first call to `with` happens
+ /// and the initialization expression succeeds.
+ ///
+ /// Keys in the `Uninitialized` state will yield a reference to the closure
+ /// passed to `with` so long as the initialization routine does not panic.
+ Uninitialized,
+
+ /// Once a key has been accessed successfully, it will enter the `Valid`
+ /// state. Keys in the `Valid` state will remain so until the thread exits,
+ /// at which point the destructor will be run and the key will enter the
+ /// `Destroyed` state.
+ ///
+ /// Keys in the `Valid` state will be guaranteed to yield a reference to the
+ /// closure passed to `with`.
+ Valid,
+
+ /// When a thread exits, the destructors for keys will be run (if
+ /// necessary). While a destructor is running, and possibly after a
+ /// destructor has run, a key is in the `Destroyed` state.
+ ///
+ /// Keys in the `Destroyed` states will trigger a panic when accessed via
+ /// `with`.
+ Destroyed,
+}
+
+impl<T: 'static> LocalKey<T> {
+ /// Acquire a reference to the value in this TLS key.
+ ///
+ /// This will lazily initialize the value if this thread has not referenced
+ /// this key yet.
+ ///
+ /// # Panics
+ ///
+ /// This function will `panic!()` if the key currently has its
+ /// destructor running, and it **may** panic if the destructor has
+ /// previously been run for this thread.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn with<F, R>(&'static self, f: F) -> R
+ where F: FnOnce(&T) -> R {
+ let slot = (self.inner)();
+ unsafe {
+ let slot = slot.get().expect("cannot access a TLS value during or \
+ after it is destroyed");
+ f(match *slot.get() {
+ Some(ref inner) => inner,
+ None => self.init(slot),
+ })
+ }
+ }
+
+ unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
+ // Execute the initialization up front, *then* move it into our slot,
+ // just in case initialization fails.
+ let value = (self.init)();
+ let ptr = slot.get();
+ *ptr = Some(value);
+ (*ptr).as_ref().unwrap()
+ }
+
+ /// Query the current state of this key.
+ ///
+ /// A key is initially in the `Uninitialized` state whenever a thread
+ /// starts. It will remain in this state up until the first call to `with`
+ /// within a thread has run the initialization expression successfully.
+ ///
+ /// Once the initialization expression succeeds, the key transitions to the
+ /// `Valid` state which will guarantee that future calls to `with` will
+ /// succeed within the thread.
+ ///
+ /// When a thread exits, each key will be destroyed in turn, and as keys are
+ /// destroyed they will enter the `Destroyed` state just before the
+ /// destructor starts to run. Keys may remain in the `Destroyed` state after
+ /// destruction has completed. Keys without destructors (e.g. with types
+ /// that are `Copy`), may never enter the `Destroyed` state.
+ ///
+ /// Keys in the `Uninitialized` can be accessed so long as the
+ /// initialization does not panic. Keys in the `Valid` state are guaranteed
+ /// to be able to be accessed. Keys in the `Destroyed` state will panic on
+ /// any call to `with`.
+ #[unstable(feature = "std_misc",
+ reason = "state querying was recently added")]
+ pub fn state(&'static self) -> LocalKeyState {
+ unsafe {
+ match (self.inner)().get() {
+ Some(cell) => {
+ match *cell.get() {
+ Some(..) => LocalKeyState::Valid,
+ None => LocalKeyState::Uninitialized,
+ }
+ }
+ None => LocalKeyState::Destroyed,
+ }
+ }
+ }
+
+ /// Deprecated
+ #[unstable(feature = "std_misc")]
+ #[deprecated(since = "1.0.0",
+ reason = "function renamed to state() and returns more info")]
+ pub fn destroyed(&'static self) -> bool { self.state() == LocalKeyState::Destroyed }
+}
+
+#[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))]
+mod imp {
+ use prelude::v1::*;
+
+ use cell::UnsafeCell;
+ use intrinsics;
+ use ptr;
+
+ #[doc(hidden)]
+ #[unstable(feature = "thread_local_internals")]
+ pub struct Key<T> {
+ // Place the inner bits in an `UnsafeCell` to currently get around the
+ // "only Sync statics" restriction. This allows any type to be placed in
+ // the cell.
+ //
+ // Note that all access requires `T: 'static` so it can't be a type with
+ // any borrowed pointers still.
+ #[unstable(feature = "thread_local_internals")]
+ pub inner: UnsafeCell<T>,
+
+ // Metadata to keep track of the state of the destructor. Remember that
+ // these variables are thread-local, not global.
+ #[unstable(feature = "thread_local_internals")]
+ pub dtor_registered: UnsafeCell<bool>, // should be Cell
+ #[unstable(feature = "thread_local_internals")]
+ pub dtor_running: UnsafeCell<bool>, // should be Cell
+ }
+
+ unsafe impl<T> ::marker::Sync for Key<T> { }
+
+ #[doc(hidden)]
+ impl<T> Key<T> {
+ pub unsafe fn get(&'static self) -> Option<&'static T> {
+ if intrinsics::needs_drop::<T>() && *self.dtor_running.get() {
+ return None
+ }
+ self.register_dtor();
+ Some(&*self.inner.get())
+ }
+
+ unsafe fn register_dtor(&self) {
+ if !intrinsics::needs_drop::<T>() || *self.dtor_registered.get() {
+ return
+ }
+
+ register_dtor(self as *const _ as *mut u8,
+ destroy_value::<T>);
+ *self.dtor_registered.get() = true;
+ }
+ }
+
+ // Since what appears to be glibc 2.18 this symbol has been shipped which
+ // GCC and clang both use to invoke destructors in thread_local globals, so
+ // let's do the same!
+ //
+ // Note, however, that we run on lots older linuxes, as well as cross
+ // compiling from a newer linux to an older linux, so we also have a
+ // fallback implementation to use as well.
+ //
+ // Due to rust-lang/rust#18804, make sure this is not generic!
+ #[cfg(target_os = "linux")]
+ unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
+ use boxed;
+ use mem;
+ use libc;
+ use sys_common::thread_local as os;
+
+ extern {
+ static __dso_handle: *mut u8;
+ #[linkage = "extern_weak"]
+ static __cxa_thread_atexit_impl: *const ();
+ }
+ if !__cxa_thread_atexit_impl.is_null() {
+ type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8),
+ arg: *mut u8,
+ dso_handle: *mut u8) -> libc::c_int;
+ mem::transmute::<*const (), F>(__cxa_thread_atexit_impl)
+ (dtor, t, __dso_handle);
+ return
+ }
+
+ // The fallback implementation uses a vanilla OS-based TLS key to track
+ // the list of destructors that need to be run for this thread. The key
+ // then has its own destructor which runs all the other destructors.
+ //
+ // The destructor for DTORS is a little special in that it has a `while`
+ // loop to continuously drain the list of registered destructors. It
+ // *should* be the case that this loop always terminates because we
+ // provide the guarantee that a TLS key cannot be set after it is
+ // flagged for destruction.
+ static DTORS: os::StaticKey = os::StaticKey {
+ inner: os::INIT_INNER,
+ dtor: Some(run_dtors as unsafe extern "C" fn(*mut u8)),
+ };
+ type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>;
+ if DTORS.get().is_null() {
+ let v: Box<List> = box Vec::new();
+ DTORS.set(boxed::into_raw(v) as *mut u8);
+ }
+ let list: &mut List = &mut *(DTORS.get() as *mut List);
+ list.push((t, dtor));
+
+ unsafe extern fn run_dtors(mut ptr: *mut u8) {
+ while !ptr.is_null() {
+ let list: Box<List> = Box::from_raw(ptr as *mut List);
+ for &(ptr, dtor) in &*list {
+ dtor(ptr);
+ }
+ ptr = DTORS.get();
+ DTORS.set(ptr::null_mut());
+ }
+ }
+ }
+
+ // OSX's analog of the above linux function is this _tlv_atexit function.
+ // The disassembly of thread_local globals in C++ (at least produced by
+ // clang) will have this show up in the output.
+ #[cfg(target_os = "macos")]
+ unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
+ extern {
+ fn _tlv_atexit(dtor: unsafe extern fn(*mut u8),
+ arg: *mut u8);
+ }
+ _tlv_atexit(dtor, t);
+ }
+
+ #[doc(hidden)]
+ #[unstable(feature = "thread_local_internals")]
+ pub unsafe extern fn destroy_value<T>(ptr: *mut u8) {
+ let ptr = ptr as *mut Key<T>;
+ // Right before we run the user destructor be sure to flag the
+ // destructor as running for this thread so calls to `get` will return
+ // `None`.
+ *(*ptr).dtor_running.get() = true;
+ ptr::read((*ptr).inner.get());
+ }
+}
+
+#[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))]
+mod imp {
+ use prelude::v1::*;
+
+ use alloc::boxed;
+ use cell::UnsafeCell;
+ use mem;
+ use ptr;
+ use sys_common::thread_local::StaticKey as OsStaticKey;
+
+ #[doc(hidden)]
+ #[unstable(feature = "thread_local_internals")]
+ pub struct Key<T> {
+ // Statically allocated initialization expression, using an `UnsafeCell`
+ // for the same reasons as above.
+ #[unstable(feature = "thread_local_internals")]
+ pub inner: UnsafeCell<T>,
+
+ // OS-TLS key that we'll use to key off.
+ #[unstable(feature = "thread_local_internals")]
+ pub os: OsStaticKey,
+ }
+
+ unsafe impl<T> ::marker::Sync for Key<T> { }
+
+ struct Value<T: 'static> {
+ key: &'static Key<T>,
+ value: T,
+ }
+
+ #[doc(hidden)]
+ impl<T> Key<T> {
+ pub unsafe fn get(&'static self) -> Option<&'static T> {
+ self.ptr().map(|p| &*p)
+ }
+
+ unsafe fn ptr(&'static self) -> Option<*mut T> {
+ let ptr = self.os.get() as *mut Value<T>;
+ if !ptr.is_null() {
+ if ptr as usize == 1 {
+ return None
+ }
+ return Some(&mut (*ptr).value as *mut T);
+ }
+
+ // If the lookup returned null, we haven't initialized our own local
+ // copy, so do that now.
+ //
+ // Also note that this transmute_copy should be ok because the value
+ // `inner` is already validated to be a valid `static` value, so we
+ // should be able to freely copy the bits.
+ let ptr: Box<Value<T>> = box Value {
+ key: self,
+ value: mem::transmute_copy(&self.inner),
+ };
+ let ptr: *mut Value<T> = boxed::into_raw(ptr);
+ self.os.set(ptr as *mut u8);
+ Some(&mut (*ptr).value as *mut T)
+ }
+ }
+
+ #[doc(hidden)]
+ #[unstable(feature = "thread_local_internals")]
+ pub unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
+ // The OS TLS ensures that this key contains a NULL value when this
+ // destructor starts to run. We set it back to a sentinel value of 1 to
+ // ensure that any future calls to `get` for this thread will return
+ // `None`.
+ //
+ // Note that to prevent an infinite loop we reset it back to null right
+ // before we return from the destructor ourselves.
+ let ptr: Box<Value<T>> = Box::from_raw(ptr as *mut Value<T>);
+ let key = ptr.key;
+ key.os.set(1 as *mut u8);
+ drop(ptr);
+ key.os.set(ptr::null_mut());
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use prelude::v1::*;
+
+ use sync::mpsc::{channel, Sender};
+ use cell::UnsafeCell;
+ use super::LocalKeyState;
+ use thread;
+
+ struct Foo(Sender<()>);
+
+ impl Drop for Foo {
+ fn drop(&mut self) {
+ let Foo(ref s) = *self;
+ s.send(()).unwrap();
+ }
+ }
+
+ #[test]
+ fn smoke_no_dtor() {
+ thread_local!(static FOO: UnsafeCell<i32> = UnsafeCell { value: 1 });
+
+ FOO.with(|f| unsafe {
+ assert_eq!(*f.get(), 1);
+ *f.get() = 2;
+ });
+ let (tx, rx) = channel();
+ let _t = thread::spawn(move|| {
+ FOO.with(|f| unsafe {
+ assert_eq!(*f.get(), 1);
+ });
+ tx.send(()).unwrap();
+ });
+ rx.recv().unwrap();
+
+ FOO.with(|f| unsafe {
+ assert_eq!(*f.get(), 2);
+ });
+ }
+
+ #[test]
+ fn states() {
+ struct Foo;
+ impl Drop for Foo {
+ fn drop(&mut self) {
+ assert!(FOO.state() == LocalKeyState::Destroyed);
+ }
+ }
+ fn foo() -> Foo {
+ assert!(FOO.state() == LocalKeyState::Uninitialized);
+ Foo
+ }
+ thread_local!(static FOO: Foo = foo());
+
+ thread::spawn(|| {
+ assert!(FOO.state() == LocalKeyState::Uninitialized);
+ FOO.with(|_| {
+ assert!(FOO.state() == LocalKeyState::Valid);
+ });
+ assert!(FOO.state() == LocalKeyState::Valid);
+ }).join().ok().unwrap();
+ }
+
+ #[test]
+ fn smoke_dtor() {
+ thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell {
+ value: None
+ });
+
+ let (tx, rx) = channel();
+ let _t = thread::spawn(move|| unsafe {
+ let mut tx = Some(tx);
+ FOO.with(|f| {
+ *f.get() = Some(Foo(tx.take().unwrap()));
+ });
+ });
+ rx.recv().unwrap();
+ }
+
+ #[test]
+ fn circular() {
+ struct S1;
+ struct S2;
+ thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell {
+ value: None
+ });
+ thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell {
+ value: None
+ });
+ static mut HITS: u32 = 0;
+
+ impl Drop for S1 {
+ fn drop(&mut self) {
+ unsafe {
+ HITS += 1;
+ if K2.state() == LocalKeyState::Destroyed {
+ assert_eq!(HITS, 3);
+ } else {
+ if HITS == 1 {
+ K2.with(|s| *s.get() = Some(S2));
+ } else {
+ assert_eq!(HITS, 3);
+ }
+ }
+ }
+ }
+ }
+ impl Drop for S2 {
+ fn drop(&mut self) {
+ unsafe {
+ HITS += 1;
+ assert!(K1.state() != LocalKeyState::Destroyed);
+ assert_eq!(HITS, 2);
+ K1.with(|s| *s.get() = Some(S1));
+ }
+ }
+ }
+
+ thread::spawn(move|| {
+ drop(S1);
+ }).join().ok().unwrap();
+ }
+
+ #[test]
+ fn self_referential() {
+ struct S1;
+ thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell {
+ value: None
+ });
+
+ impl Drop for S1 {
+ fn drop(&mut self) {
+ assert!(K1.state() == LocalKeyState::Destroyed);
+ }
+ }
+
+ thread::spawn(move|| unsafe {
+ K1.with(|s| *s.get() = Some(S1));
+ }).join().ok().unwrap();
+ }
+
+ #[test]
+ fn dtors_in_dtors_in_dtors() {
+ struct S1(Sender<()>);
+ thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell {
+ value: None
+ });
+ thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell {
+ value: None
+ });
+
+ impl Drop for S1 {
+ fn drop(&mut self) {
+ let S1(ref tx) = *self;
+ unsafe {
+ if K2.state() != LocalKeyState::Destroyed {
+ K2.with(|s| *s.get() = Some(Foo(tx.clone())));
+ }
+ }
+ }
+ }
+
+ let (tx, rx) = channel();
+ let _t = thread::spawn(move|| unsafe {
+ let mut tx = Some(tx);
+ K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
+ });
+ rx.recv().unwrap();
+ }
+}
+
+#[cfg(test)]
+mod dynamic_tests {
+ use prelude::v1::*;
+
+ use cell::RefCell;
+ use collections::HashMap;
+
+ #[test]
+ fn smoke() {
+ fn square(i: i32) -> i32 { i * i }
+ thread_local!(static FOO: i32 = square(3));
+
+ FOO.with(|f| {
+ assert_eq!(*f, 9);
+ });
+ }
+
+ #[test]
+ fn hashmap() {
+ fn map() -> RefCell<HashMap<i32, i32>> {
+ let mut m = HashMap::new();
+ m.insert(1, 2);
+ RefCell::new(m)
+ }
+ thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
+
+ FOO.with(|map| {
+ assert_eq!(map.borrow()[&1], 2);
+ });
+ }
+
+ #[test]
+ fn refcell_vec() {
+ thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
+
+ FOO.with(|vec| {
+ assert_eq!(vec.borrow().len(), 3);
+ vec.borrow_mut().push(4);
+ assert_eq!(vec.borrow()[3], 4);
+ });
+ }
+}
--- /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.
+
+//! Native threads
+//!
+//! ## The threading model
+//!
+//! An executing Rust program consists of a collection of native OS threads,
+//! each with their own stack and local state.
+//!
+//! Communication between threads can be done through
+//! [channels](../../std/sync/mpsc/index.html), Rust's message-passing
+//! types, along with [other forms of thread
+//! synchronization](../../std/sync/index.html) and shared-memory data
+//! structures. In particular, types that are guaranteed to be
+//! threadsafe are easily shared between threads using the
+//! atomically-reference-counted container,
+//! [`Arc`](../../std/sync/struct.Arc.html).
+//!
+//! Fatal logic errors in Rust cause *thread panic*, during which
+//! a thread will unwind the stack, running destructors and freeing
+//! owned resources. Thread panic is unrecoverable from within
+//! the panicking thread (i.e. there is no 'try/catch' in Rust), but
+//! the panic may optionally be detected from a different thread. If
+//! the main thread panics, the application will exit with a non-zero
+//! exit code.
+//!
+//! When the main thread of a Rust program terminates, the entire program shuts
+//! down, even if other threads are still running. However, this module provides
+//! convenient facilities for automatically waiting for the termination of a
+//! child thread (i.e., join).
+//!
+//! ## The `Thread` type
+//!
+//! Threads are represented via the `Thread` type, which you can
+//! get in one of two ways:
+//!
+//! * By spawning a new thread, e.g. using the `thread::spawn` function.
+//! * By requesting the current thread, using the `thread::current` function.
+//!
+//! Threads can be named, and provide some built-in support for low-level
+//! synchronization (described below).
+//!
+//! The `thread::current()` function is available even for threads not spawned
+//! by the APIs of this module.
+//!
+//! ## Spawning a thread
+//!
+//! A new thread can be spawned using the `thread::spawn` function:
+//!
+//! ```rust
+//! use std::thread;
+//!
+//! thread::spawn(move || {
+//! // some work here
+//! });
+//! ```
+//!
+//! In this example, the spawned thread is "detached" from the current
+//! thread. This means that it can outlive its parent (the thread that spawned
+//! it), unless this parent is the main thread.
+//!
+//! ## Scoped threads
+//!
+//! Often a parent thread uses a child thread to perform some particular task,
+//! and at some point must wait for the child to complete before continuing.
+//! For this scenario, use the `thread::scoped` function:
+//!
+//! ```rust
+//! use std::thread;
+//!
+//! let guard = thread::scoped(move || {
+//! // some work here
+//! });
+//!
+//! // do some other work in the meantime
+//! let output = guard.join();
+//! ```
+//!
+//! The `scoped` function doesn't return a `Thread` directly; instead,
+//! it returns a *join guard*. The join guard is an RAII-style guard
+//! that will automatically join the child thread (block until it
+//! terminates) when it is dropped. You can join the child thread in
+//! advance by calling the `join` method on the guard, which will also
+//! return the result produced by the thread. A handle to the thread
+//! itself is available via the `thread` method of the join guard.
+//!
+//! ## Configuring threads
+//!
+//! A new thread can be configured before it is spawned via the `Builder` type,
+//! which currently allows you to set the name, stack size, and writers for
+//! `println!` and `panic!` for the child thread:
+//!
+//! ```rust
+//! use std::thread;
+//!
+//! thread::Builder::new().name("child1".to_string()).spawn(move || {
+//! println!("Hello, world!");
+//! });
+//! ```
+//!
+//! ## Blocking support: park and unpark
+//!
+//! Every thread is equipped with some basic low-level blocking support, via the
+//! `park` and `unpark` functions.
+//!
+//! Conceptually, each `Thread` handle has an associated token, which is
+//! initially not present:
+//!
+//! * The `thread::park()` function blocks the current thread unless or until
+//! the token is available for its thread handle, at which point it atomically
+//! consumes the token. It may also return *spuriously*, without consuming the
+//! token. `thread::park_timeout()` does the same, but allows specifying a
+//! maximum time to block the thread for.
+//!
+//! * The `unpark()` method on a `Thread` atomically makes the token available
+//! if it wasn't already.
+//!
+//! In other words, each `Thread` acts a bit like a semaphore with initial count
+//! 0, except that the semaphore is *saturating* (the count cannot go above 1),
+//! and can return spuriously.
+//!
+//! The API is typically used by acquiring a handle to the current thread,
+//! placing that handle in a shared data structure so that other threads can
+//! find it, and then `park`ing. When some desired condition is met, another
+//! thread calls `unpark` on the handle.
+//!
+//! The motivation for this design is twofold:
+//!
+//! * It avoids the need to allocate mutexes and condvars when building new
+//! synchronization primitives; the threads already provide basic blocking/signaling.
+//!
+//! * It can be implemented very efficiently on many platforms.
+//!
+//! ## Thread-local storage
+//!
+//! This module also provides an implementation of thread local storage for Rust
+//! programs. Thread local storage is a method of storing data into a global
+//! variable which each thread in the program will have its own copy of.
+//! Threads do not share this data, so accesses do not need to be synchronized.
+//!
+//! At a high level, this module provides two variants of storage:
+//!
+//! * Owned thread-local storage. This is a type of thread local key which
+//! owns the value that it contains, and will destroy the value when the
+//! thread exits. This variant is created with the `thread_local!` macro and
+//! can contain any value which is `'static` (no borrowed pointers).
+//!
+//! * Scoped thread-local storage. This type of key is used to store a reference
+//! to a value into local storage temporarily for the scope of a function
+//! call. There are no restrictions on what types of values can be placed
+//! into this key.
+//!
+//! Both forms of thread local storage provide an accessor function, `with`,
+//! which will yield a shared reference to the value to the specified
+//! closure. Thread-local keys only allow shared access to values as there is no
+//! way to guarantee uniqueness if a mutable borrow was allowed. Most values
+//! will want to make use of some form of **interior mutability** through the
+//! `Cell` or `RefCell` types.
+
+#![stable(feature = "rust1", since = "1.0.0")]
+
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use self::__local::{LocalKey, LocalKeyState};
+
+#[unstable(feature = "scoped_tls",
+ reason = "scoped TLS has yet to have wide enough use to fully consider \
+ stabilizing its interface")]
+pub use self::__scoped::ScopedKey;
+
+use prelude::v1::*;
+
+use any::Any;
+use cell::UnsafeCell;
+use fmt;
+use io;
+use marker::PhantomData;
+use rt::{self, unwind};
+use sync::{Mutex, Condvar, Arc};
+use sys::thread as imp;
+use sys_common::{stack, thread_info};
+use thunk::Thunk;
+use time::Duration;
+
+#[allow(deprecated)] use old_io::Writer;
+
+////////////////////////////////////////////////////////////////////////////////
+// Thread-local storage
+////////////////////////////////////////////////////////////////////////////////
+
+#[macro_use]
+#[doc(hidden)]
+#[path = "local.rs"] pub mod __local;
+
+#[macro_use]
+#[doc(hidden)]
+#[path = "scoped.rs"] pub mod __scoped;
+
+////////////////////////////////////////////////////////////////////////////////
+// Builder
+////////////////////////////////////////////////////////////////////////////////
+
+/// Thread configuration. Provides detailed control over the properties
+/// and behavior of new threads.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Builder {
+ // A name for the thread-to-be, for identification in panic messages
+ name: Option<String>,
+ // The size of the stack for the spawned thread
+ stack_size: Option<usize>,
+}
+
+impl Builder {
+ /// Generate the base configuration for spawning a thread, from which
+ /// configuration methods can be chained.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn new() -> Builder {
+ Builder {
+ name: None,
+ stack_size: None,
+ }
+ }
+
+ /// Name the thread-to-be. Currently the name is used for identification
+ /// only in panic messages.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn name(mut self, name: String) -> Builder {
+ self.name = Some(name);
+ self
+ }
+
+ /// Set the size of the stack for the new thread.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn stack_size(mut self, size: usize) -> Builder {
+ self.stack_size = Some(size);
+ self
+ }
+
+ /// Redirect thread-local stdout.
+ #[unstable(feature = "std_misc",
+ reason = "Will likely go away after proc removal")]
+ #[deprecated(since = "1.0.0",
+ reason = "the old I/O module is deprecated and this function \
+ will be removed with no replacement")]
+ #[allow(deprecated)]
+ pub fn stdout(self, _stdout: Box<Writer + Send + 'static>) -> Builder {
+ self
+ }
+
+ /// Redirect thread-local stderr.
+ #[unstable(feature = "std_misc",
+ reason = "Will likely go away after proc removal")]
+ #[deprecated(since = "1.0.0",
+ reason = "the old I/O module is deprecated and this function \
+ will be removed with no replacement")]
+ #[allow(deprecated)]
+ pub fn stderr(self, _stderr: Box<Writer + Send + 'static>) -> Builder {
+ self
+ }
+
+ /// Spawn a new thread, and return a join handle for it.
+ ///
+ /// The child thread may outlive the parent (unless the parent thread
+ /// is the main thread; the whole process is terminated when the main
+ /// thread finishes.) The join handle can be used to block on
+ /// termination of the child thread, including recovering its panics.
+ ///
+ /// # Errors
+ ///
+ /// Unlike the `spawn` free function, this method yields an
+ /// `io::Result` to capture any failure to create the thread at
+ /// the OS level.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn spawn<F>(self, f: F) -> io::Result<JoinHandle> where
+ F: FnOnce(), F: Send + 'static
+ {
+ self.spawn_inner(Thunk::new(f)).map(|i| JoinHandle(i))
+ }
+
+ /// Spawn a new child thread that must be joined within a given
+ /// scope, and return a `JoinGuard`.
+ ///
+ /// The join guard can be used to explicitly join the child thread (via
+ /// `join`), returning `Result<T>`, or it will implicitly join the child
+ /// upon being dropped. Because the child thread may refer to data on the
+ /// current thread's stack (hence the "scoped" name), it cannot be detached;
+ /// it *must* be joined before the relevant stack frame is popped. See the
+ /// module documentation for additional details.
+ ///
+ /// # Errors
+ ///
+ /// Unlike the `scoped` free function, this method yields an
+ /// `io::Result` to capture any failure to create the thread at
+ /// the OS level.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn scoped<'a, T, F>(self, f: F) -> io::Result<JoinGuard<'a, T>> where
+ T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
+ {
+ self.spawn_inner(Thunk::new(f)).map(|inner| {
+ JoinGuard { inner: inner, _marker: PhantomData }
+ })
+ }
+
+ fn spawn_inner<T: Send>(self, f: Thunk<(), T>) -> io::Result<JoinInner<T>> {
+ let Builder { name, stack_size } = self;
+
+ let stack_size = stack_size.unwrap_or(rt::min_stack());
+
+ let my_thread = Thread::new(name);
+ let their_thread = my_thread.clone();
+
+ let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
+ let their_packet = Packet(my_packet.0.clone());
+
+ // Spawning a new OS thread guarantees that __morestack will never get
+ // triggered, but we must manually set up the actual stack bounds once
+ // this function starts executing. This raises the lower limit by a bit
+ // because by the time that this function is executing we've already
+ // consumed at least a little bit of stack (we don't know the exact byte
+ // address at which our stack started).
+ let main = move || {
+ let something_around_the_top_of_the_stack = 1;
+ let addr = &something_around_the_top_of_the_stack as *const i32;
+ let my_stack_top = addr as usize;
+ let my_stack_bottom = my_stack_top - stack_size + 1024;
+ unsafe {
+ if let Some(name) = their_thread.name() {
+ imp::set_name(name);
+ }
+ stack::record_os_managed_stack_bounds(my_stack_bottom,
+ my_stack_top);
+ thread_info::set(imp::guard::current(), their_thread);
+ }
+
+ let mut output = None;
+ let try_result = {
+ let ptr = &mut output;
+
+ // There are two primary reasons that general try/catch is
+ // unsafe. The first is that we do not support nested
+ // try/catch. The fact that this is happening in a newly-spawned
+ // thread suffices. The second is that unwinding while unwinding
+ // is not defined. We take care of that by having an
+ // 'unwinding' flag in the thread itself. For these reasons,
+ // this unsafety should be ok.
+ unsafe {
+ unwind::try(move || *ptr = Some(f.invoke(())))
+ }
+ };
+ unsafe {
+ *their_packet.0.get() = Some(match (output, try_result) {
+ (Some(data), Ok(_)) => Ok(data),
+ (None, Err(cause)) => Err(cause),
+ _ => unreachable!()
+ });
+ }
+ };
+
+ Ok(JoinInner {
+ native: try!(unsafe { imp::create(stack_size, Thunk::new(main)) }),
+ thread: my_thread,
+ packet: my_packet,
+ joined: false,
+ })
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// Free functions
+////////////////////////////////////////////////////////////////////////////////
+
+/// Spawn a new thread, returning a `JoinHandle` for it.
+///
+/// The join handle will implicitly *detach* the child thread upon being
+/// dropped. In this case, the child thread may outlive the parent (unless
+/// the parent thread is the main thread; the whole process is terminated when
+/// the main thread finishes.) Additionally, the join handle provides a `join`
+/// method that can be used to join the child thread. If the child thread
+/// panics, `join` will return an `Err` containing the argument given to
+/// `panic`.
+///
+/// # Panics
+///
+/// Panicks if the OS fails to create a thread; use `Builder::spawn`
+/// to recover from such errors.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub fn spawn<F>(f: F) -> JoinHandle where F: FnOnce(), F: Send + 'static {
+ Builder::new().spawn(f).unwrap()
+}
+
+/// Spawn a new *scoped* thread, returning a `JoinGuard` for it.
+///
+/// The join guard can be used to explicitly join the child thread (via
+/// `join`), returning `Result<T>`, or it will implicitly join the child
+/// upon being dropped. Because the child thread may refer to data on the
+/// current thread's stack (hence the "scoped" name), it cannot be detached;
+/// it *must* be joined before the relevant stack frame is popped. See the
+/// module documentation for additional details.
+///
+/// # Panics
+///
+/// Panicks if the OS fails to create a thread; use `Builder::scoped`
+/// to recover from such errors.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
+ T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
+{
+ Builder::new().scoped(f).unwrap()
+}
+
+/// Gets a handle to the thread that invokes it.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub fn current() -> Thread {
+ thread_info::current_thread()
+}
+
+/// Cooperatively give up a timeslice to the OS scheduler.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub fn yield_now() {
+ unsafe { imp::yield_now() }
+}
+
+/// Determines whether the current thread is unwinding because of panic.
+#[inline]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub fn panicking() -> bool {
+ unwind::panicking()
+}
+
+/// Put the current thread to sleep for the specified amount of time.
+///
+/// The thread may sleep longer than the duration specified due to scheduling
+/// specifics or platform-dependent functionality. Note that on unix platforms
+/// this function will not return early due to a signal being received or a
+/// spurious wakeup.
+#[unstable(feature = "thread_sleep",
+ reason = "recently added, needs an RFC, and `Duration` itself is \
+ unstable")]
+pub fn sleep(dur: Duration) {
+ imp::sleep(dur)
+}
+
+/// Block unless or until the current thread's token is made available (may wake spuriously).
+///
+/// See the module doc for more detail.
+//
+// The implementation currently uses the trivial strategy of a Mutex+Condvar
+// with wakeup flag, which does not actually allow spurious wakeups. In the
+// future, this will be implemented in a more efficient way, perhaps along the lines of
+// http://cr.openjdk.java.net/~stefank/6989984.1/raw_files/new/src/os/linux/vm/os_linux.cpp
+// or futuxes, and in either case may allow spurious wakeups.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub fn park() {
+ let thread = current();
+ let mut guard = thread.inner.lock.lock().unwrap();
+ while !*guard {
+ guard = thread.inner.cvar.wait(guard).unwrap();
+ }
+ *guard = false;
+}
+
+/// Block unless or until the current thread's token is made available or
+/// the specified duration has been reached (may wake spuriously).
+///
+/// The semantics of this function are equivalent to `park()` except that the
+/// thread will be blocked for roughly no longer than *duration*. This method
+/// should not be used for precise timing due to anomalies such as
+/// preemption or platform differences that may not cause the maximum
+/// amount of time waited to be precisely *duration* long.
+///
+/// See the module doc for more detail.
+#[unstable(feature = "std_misc", reason = "recently introduced, depends on Duration")]
+pub fn park_timeout(duration: Duration) {
+ let thread = current();
+ let mut guard = thread.inner.lock.lock().unwrap();
+ if !*guard {
+ let (g, _) = thread.inner.cvar.wait_timeout(guard, duration).unwrap();
+ guard = g;
+ }
+ *guard = false;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// Thread
+////////////////////////////////////////////////////////////////////////////////
+
+/// The internal representation of a `Thread` handle
+struct Inner {
+ name: Option<String>,
+ lock: Mutex<bool>, // true when there is a buffered unpark
+ cvar: Condvar,
+}
+
+unsafe impl Sync for Inner {}
+
+#[derive(Clone)]
+#[stable(feature = "rust1", since = "1.0.0")]
+/// A handle to a thread.
+pub struct Thread {
+ inner: Arc<Inner>,
+}
+
+impl Thread {
+ // Used only internally to construct a thread object without spawning
+ fn new(name: Option<String>) -> Thread {
+ Thread {
+ inner: Arc::new(Inner {
+ name: name,
+ lock: Mutex::new(false),
+ cvar: Condvar::new(),
+ })
+ }
+ }
+
+ /// Deprecated: use module-level free function.
+ #[deprecated(since = "1.0.0", reason = "use module-level free function")]
+ #[unstable(feature = "std_misc",
+ reason = "may change with specifics of new Send semantics")]
+ pub fn spawn<F>(f: F) -> Thread where F: FnOnce(), F: Send + 'static {
+ Builder::new().spawn(f).unwrap().thread().clone()
+ }
+
+ /// Deprecated: use module-level free function.
+ #[deprecated(since = "1.0.0", reason = "use module-level free function")]
+ #[unstable(feature = "std_misc",
+ reason = "may change with specifics of new Send semantics")]
+ pub fn scoped<'a, T, F>(f: F) -> JoinGuard<'a, T> where
+ T: Send + 'a, F: FnOnce() -> T, F: Send + 'a
+ {
+ Builder::new().scoped(f).unwrap()
+ }
+
+ /// Deprecated: use module-level free function.
+ #[deprecated(since = "1.0.0", reason = "use module-level free function")]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn current() -> Thread {
+ thread_info::current_thread()
+ }
+
+ /// Deprecated: use module-level free function.
+ #[deprecated(since = "1.0.0", reason = "use module-level free function")]
+ #[unstable(feature = "std_misc", reason = "name may change")]
+ pub fn yield_now() {
+ unsafe { imp::yield_now() }
+ }
+
+ /// Deprecated: use module-level free function.
+ #[deprecated(since = "1.0.0", reason = "use module-level free function")]
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn panicking() -> bool {
+ unwind::panicking()
+ }
+
+ /// Deprecated: use module-level free function.
+ #[deprecated(since = "1.0.0", reason = "use module-level free function")]
+ #[unstable(feature = "std_misc", reason = "recently introduced")]
+ pub fn park() {
+ let thread = current();
+ let mut guard = thread.inner.lock.lock().unwrap();
+ while !*guard {
+ guard = thread.inner.cvar.wait(guard).unwrap();
+ }
+ *guard = false;
+ }
+
+ /// Deprecated: use module-level free function.
+ #[deprecated(since = "1.0.0", reason = "use module-level free function")]
+ #[unstable(feature = "std_misc", reason = "recently introduced")]
+ pub fn park_timeout(duration: Duration) {
+ let thread = current();
+ let mut guard = thread.inner.lock.lock().unwrap();
+ if !*guard {
+ let (g, _) = thread.inner.cvar.wait_timeout(guard, duration).unwrap();
+ guard = g;
+ }
+ *guard = false;
+ }
+
+ /// Atomically makes the handle's token available if it is not already.
+ ///
+ /// See the module doc for more detail.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn unpark(&self) {
+ let mut guard = self.inner.lock.lock().unwrap();
+ if !*guard {
+ *guard = true;
+ self.inner.cvar.notify_one();
+ }
+ }
+
+ /// Get the thread's name.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn name(&self) -> Option<&str> {
+ self.inner.name.as_ref().map(|s| &**s)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl fmt::Debug for Thread {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fmt::Debug::fmt(&self.name(), f)
+ }
+}
+
+// a hack to get around privacy restrictions
+impl thread_info::NewThread for Thread {
+ fn new(name: Option<String>) -> Thread { Thread::new(name) }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// JoinHandle and JoinGuard
+////////////////////////////////////////////////////////////////////////////////
+
+/// Indicates the manner in which a thread exited.
+///
+/// A thread that completes without panicking is considered to exit successfully.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub type Result<T> = ::result::Result<T, Box<Any + Send + 'static>>;
+
+struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>);
+
+unsafe impl<T:Send> Send for Packet<T> {}
+unsafe impl<T> Sync for Packet<T> {}
+
+/// Inner representation for JoinHandle and JoinGuard
+struct JoinInner<T> {
+ native: imp::rust_thread,
+ thread: Thread,
+ packet: Packet<T>,
+ joined: bool,
+}
+
+impl<T> JoinInner<T> {
+ fn join(&mut self) -> Result<T> {
+ assert!(!self.joined);
+ unsafe { imp::join(self.native) };
+ self.joined = true;
+ unsafe {
+ (*self.packet.0.get()).take().unwrap()
+ }
+ }
+}
+
+/// An owned permission to join on a thread (block on its termination).
+///
+/// Unlike a `JoinGuard`, a `JoinHandle` *detaches* the child thread
+/// when it is dropped, rather than automatically joining on drop.
+///
+/// Due to platform restrictions, it is not possible to `Clone` this
+/// handle: the ability to join a child thread is a uniquely-owned
+/// permission.
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct JoinHandle(JoinInner<()>);
+
+impl JoinHandle {
+ /// Extract a handle to the underlying thread
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn thread(&self) -> &Thread {
+ &self.0.thread
+ }
+
+ /// Wait for the associated thread to finish.
+ ///
+ /// If the child thread panics, `Err` is returned with the parameter given
+ /// to `panic`.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn join(mut self) -> Result<()> {
+ self.0.join()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl Drop for JoinHandle {
+ fn drop(&mut self) {
+ if !self.0.joined {
+ unsafe { imp::detach(self.0.native) }
+ }
+ }
+}
+
+/// An RAII-style guard that will block until thread termination when dropped.
+///
+/// The type `T` is the return type for the thread's main function.
+///
+/// Joining on drop is necessary to ensure memory safety when stack
+/// data is shared between a parent and child thread.
+///
+/// Due to platform restrictions, it is not possible to `Clone` this
+/// handle: the ability to join a child thread is a uniquely-owned
+/// permission.
+#[must_use = "thread will be immediately joined if `JoinGuard` is not used"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct JoinGuard<'a, T: 'a> {
+ inner: JoinInner<T>,
+ _marker: PhantomData<&'a T>,
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+unsafe impl<'a, T: Send + 'a> Sync for JoinGuard<'a, T> {}
+
+impl<'a, T: Send + 'a> JoinGuard<'a, T> {
+ /// Extract a handle to the thread this guard will join on.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn thread(&self) -> &Thread {
+ &self.inner.thread
+ }
+
+ /// Wait for the associated thread to finish, returning the result of the thread's
+ /// calculation.
+ ///
+ /// # Panics
+ ///
+ /// Panics on the child thread are propagated by panicking the parent.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn join(mut self) -> T {
+ match self.inner.join() {
+ Ok(res) => res,
+ Err(_) => panic!("child thread {:?} panicked", self.thread()),
+ }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<T: Send> JoinGuard<'static, T> {
+ /// Detaches the child thread, allowing it to outlive its parent.
+ #[deprecated(since = "1.0.0", reason = "use spawn instead")]
+ #[unstable(feature = "std_misc")]
+ pub fn detach(mut self) {
+ unsafe { imp::detach(self.inner.native) };
+ self.inner.joined = true; // avoid joining in the destructor
+ }
+}
+
+#[unsafe_destructor]
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, T: Send + 'a> Drop for JoinGuard<'a, T> {
+ fn drop(&mut self) {
+ if !self.inner.joined {
+ if self.inner.join().is_err() {
+ panic!("child thread {:?} panicked", self.thread());
+ }
+ }
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+// Tests
+////////////////////////////////////////////////////////////////////////////////
+
+#[cfg(test)]
+mod test {
+ use prelude::v1::*;
+
+ use any::Any;
+ use sync::mpsc::{channel, Sender};
+ use boxed::BoxAny;
+ use result;
+ use std::old_io::{ChanReader, ChanWriter};
+ use super::{Builder};
+ use thread;
+ use thunk::Thunk;
+ use time::Duration;
+
+ // !!! These tests are dangerous. If something is buggy, they will hang, !!!
+ // !!! instead of exiting cleanly. This might wedge the buildbots. !!!
+
+ #[test]
+ fn test_unnamed_thread() {
+ thread::spawn(move|| {
+ assert!(thread::current().name().is_none());
+ }).join().ok().unwrap();
+ }
+
+ #[test]
+ fn test_named_thread() {
+ Builder::new().name("ada lovelace".to_string()).scoped(move|| {
+ assert!(thread::current().name().unwrap() == "ada lovelace".to_string());
+ }).unwrap().join();
+ }
+
+ #[test]
+ fn test_run_basic() {
+ let (tx, rx) = channel();
+ thread::spawn(move|| {
+ tx.send(()).unwrap();
+ });
+ rx.recv().unwrap();
+ }
+
+ #[test]
+ fn test_join_success() {
+ assert!(thread::scoped(move|| -> String {
+ "Success!".to_string()
+ }).join() == "Success!");
+ }
+
+ #[test]
+ fn test_join_panic() {
+ match thread::spawn(move|| {
+ panic!()
+ }).join() {
+ result::Result::Err(_) => (),
+ result::Result::Ok(()) => panic!()
+ }
+ }
+
+ #[test]
+ fn test_scoped_success() {
+ let res = thread::scoped(move|| -> String {
+ "Success!".to_string()
+ }).join();
+ assert!(res == "Success!");
+ }
+
+ #[test]
+ #[should_fail]
+ fn test_scoped_panic() {
+ thread::scoped(|| panic!()).join();
+ }
+
+ #[test]
+ #[should_fail]
+ fn test_scoped_implicit_panic() {
+ let _ = thread::scoped(|| panic!());
+ }
+
+ #[test]
+ fn test_spawn_sched() {
+ use clone::Clone;
+
+ let (tx, rx) = channel();
+
+ fn f(i: i32, tx: Sender<()>) {
+ let tx = tx.clone();
+ thread::spawn(move|| {
+ if i == 0 {
+ tx.send(()).unwrap();
+ } else {
+ f(i - 1, tx);
+ }
+ });
+
+ }
+ f(10, tx);
+ rx.recv().unwrap();
+ }
+
+ #[test]
+ fn test_spawn_sched_childs_on_default_sched() {
+ let (tx, rx) = channel();
+
+ thread::spawn(move|| {
+ thread::spawn(move|| {
+ tx.send(()).unwrap();
+ });
+ });
+
+ rx.recv().unwrap();
+ }
+
+ fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk<'static>) {
+ let (tx, rx) = channel();
+
+ let x: Box<_> = box 1;
+ let x_in_parent = (&*x) as *const i32 as usize;
+
+ spawnfn(Thunk::new(move|| {
+ let x_in_child = (&*x) as *const i32 as usize;
+ tx.send(x_in_child).unwrap();
+ }));
+
+ let x_in_child = rx.recv().unwrap();
+ assert_eq!(x_in_parent, x_in_child);
+ }
+
+ #[test]
+ fn test_avoid_copying_the_body_spawn() {
+ avoid_copying_the_body(|v| {
+ thread::spawn(move || v.invoke(()));
+ });
+ }
+
+ #[test]
+ fn test_avoid_copying_the_body_thread_spawn() {
+ avoid_copying_the_body(|f| {
+ thread::spawn(move|| {
+ f.invoke(());
+ });
+ })
+ }
+
+ #[test]
+ fn test_avoid_copying_the_body_join() {
+ avoid_copying_the_body(|f| {
+ let _ = thread::spawn(move|| {
+ f.invoke(())
+ }).join();
+ })
+ }
+
+ #[test]
+ fn test_child_doesnt_ref_parent() {
+ // If the child refcounts the parent task, this will stack overflow when
+ // climbing the task tree to dereference each ancestor. (See #1789)
+ // (well, it would if the constant were 8000+ - I lowered it to be more
+ // valgrind-friendly. try this at home, instead..!)
+ const GENERATIONS: u32 = 16;
+ fn child_no(x: u32) -> Thunk<'static> {
+ return Thunk::new(move|| {
+ if x < GENERATIONS {
+ thread::spawn(move|| child_no(x+1).invoke(()));
+ }
+ });
+ }
+ thread::spawn(|| child_no(0).invoke(()));
+ }
+
+ #[test]
+ fn test_simple_newsched_spawn() {
+ thread::spawn(move || {});
+ }
+
+ #[test]
+ fn test_try_panic_message_static_str() {
+ match thread::spawn(move|| {
+ panic!("static string");
+ }).join() {
+ Err(e) => {
+ type T = &'static str;
+ assert!(e.is::<T>());
+ assert_eq!(*e.downcast::<T>().unwrap(), "static string");
+ }
+ Ok(()) => panic!()
+ }
+ }
+
+ #[test]
+ fn test_try_panic_message_owned_str() {
+ match thread::spawn(move|| {
+ panic!("owned string".to_string());
+ }).join() {
+ Err(e) => {
+ type T = String;
+ assert!(e.is::<T>());
+ assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
+ }
+ Ok(()) => panic!()
+ }
+ }
+
+ #[test]
+ fn test_try_panic_message_any() {
+ match thread::spawn(move|| {
+ panic!(box 413u16 as Box<Any + Send>);
+ }).join() {
+ Err(e) => {
+ type T = Box<Any + Send>;
+ assert!(e.is::<T>());
+ let any = e.downcast::<T>().unwrap();
+ assert!(any.is::<u16>());
+ assert_eq!(*any.downcast::<u16>().unwrap(), 413);
+ }
+ Ok(()) => panic!()
+ }
+ }
+
+ #[test]
+ fn test_try_panic_message_unit_struct() {
+ struct Juju;
+
+ match thread::spawn(move|| {
+ panic!(Juju)
+ }).join() {
+ Err(ref e) if e.is::<Juju>() => {}
+ Err(_) | Ok(()) => panic!()
+ }
+ }
+
+ #[test]
+ fn test_park_timeout_unpark_before() {
+ for _ in 0..10 {
+ thread::current().unpark();
+ thread::park_timeout(Duration::seconds(10_000_000));
+ }
+ }
+
+ #[test]
+ fn test_park_timeout_unpark_not_called() {
+ for _ in 0..10 {
+ thread::park_timeout(Duration::milliseconds(10));
+ }
+ }
+
+ #[test]
+ fn test_park_timeout_unpark_called_other_thread() {
+ use std::old_io;
+
+ for _ in 0..10 {
+ let th = thread::current();
+
+ let _guard = thread::spawn(move || {
+ old_io::timer::sleep(Duration::milliseconds(50));
+ th.unpark();
+ });
+
+ thread::park_timeout(Duration::seconds(10_000_000));
+ }
+ }
+
+ #[test]
+ fn sleep_smoke() {
+ thread::sleep(Duration::milliseconds(2));
+ thread::sleep(Duration::milliseconds(-2));
+ }
+
+ // NOTE: the corresponding test for stderr is in run-pass/task-stderr, due
+ // to the test harness apparently interfering with stderr configuration.
+}
--- /dev/null
+// 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.
+//
+// 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.
+
+//! Scoped thread-local storage
+//!
+//! This module provides the ability to generate *scoped* thread-local
+//! variables. In this sense, scoped indicates that thread local storage
+//! actually stores a reference to a value, and this reference is only placed
+//! in storage for a scoped amount of time.
+//!
+//! There are no restrictions on what types can be placed into a scoped
+//! variable, but all scoped variables are initialized to the equivalent of
+//! null. Scoped thread local storage is useful when a value is present for a known
+//! period of time and it is not required to relinquish ownership of the
+//! contents.
+//!
+//! # Examples
+//!
+//! ```
+//! # #![feature(scoped_tls)]
+//! scoped_thread_local!(static FOO: u32);
+//!
+//! // Initially each scoped slot is empty.
+//! assert!(!FOO.is_set());
+//!
+//! // When inserting a value, the value is only in place for the duration
+//! // of the closure specified.
+//! FOO.set(&1, || {
+//! FOO.with(|slot| {
+//! assert_eq!(*slot, 1);
+//! });
+//! });
+//! ```
+
+#![unstable(feature = "thread_local_internals")]
+
+use prelude::v1::*;
+
+// macro hygiene sure would be nice, wouldn't it?
+#[doc(hidden)]
+pub mod __impl {
+ pub use super::imp::KeyInner;
+ pub use sys_common::thread_local::INIT as OS_INIT;
+}
+
+/// Type representing a thread local storage key corresponding to a reference
+/// to the type parameter `T`.
+///
+/// Keys are statically allocated and can contain a reference to an instance of
+/// type `T` scoped to a particular lifetime. Keys provides two methods, `set`
+/// and `with`, both of which currently use closures to control the scope of
+/// their contents.
+#[unstable(feature = "scoped_tls",
+ reason = "scoped TLS has yet to have wide enough use to fully consider \
+ stabilizing its interface")]
+pub struct ScopedKey<T> { #[doc(hidden)] pub inner: __impl::KeyInner<T> }
+
+/// Declare a new scoped thread local storage key.
+///
+/// This macro declares a `static` item on which methods are used to get and
+/// set the value stored within.
+#[macro_export]
+#[allow_internal_unstable]
+macro_rules! scoped_thread_local {
+ (static $name:ident: $t:ty) => (
+ __scoped_thread_local_inner!(static $name: $t);
+ );
+ (pub static $name:ident: $t:ty) => (
+ __scoped_thread_local_inner!(pub static $name: $t);
+ );
+}
+
+#[macro_export]
+#[doc(hidden)]
+#[allow_internal_unstable]
+macro_rules! __scoped_thread_local_inner {
+ (static $name:ident: $t:ty) => (
+ #[cfg_attr(not(any(windows,
+ target_os = "android",
+ target_os = "ios",
+ target_os = "openbsd",
+ target_arch = "aarch64")),
+ thread_local)]
+ static $name: ::std::thread::ScopedKey<$t> =
+ __scoped_thread_local_inner!($t);
+ );
+ (pub static $name:ident: $t:ty) => (
+ #[cfg_attr(not(any(windows,
+ target_os = "android",
+ target_os = "ios",
+ target_os = "openbsd",
+ target_arch = "aarch64")),
+ thread_local)]
+ pub static $name: ::std::thread::ScopedKey<$t> =
+ __scoped_thread_local_inner!($t);
+ );
+ ($t:ty) => ({
+ use std::thread::ScopedKey as __Key;
+
+ #[cfg(not(any(windows,
+ target_os = "android",
+ target_os = "ios",
+ target_os = "openbsd",
+ target_arch = "aarch64")))]
+ const _INIT: __Key<$t> = __Key {
+ inner: ::std::thread::__scoped::__impl::KeyInner {
+ inner: ::std::cell::UnsafeCell { value: 0 as *mut _ },
+ }
+ };
+
+ #[cfg(any(windows,
+ target_os = "android",
+ target_os = "ios",
+ target_os = "openbsd",
+ target_arch = "aarch64"))]
+ const _INIT: __Key<$t> = __Key {
+ inner: ::std::thread::__scoped::__impl::KeyInner {
+ inner: ::std::thread::__scoped::__impl::OS_INIT,
+ marker: ::std::marker::PhantomData::<::std::cell::Cell<$t>>,
+ }
+ };
+
+ _INIT
+ })
+}
+
+#[unstable(feature = "scoped_tls",
+ reason = "scoped TLS has yet to have wide enough use to fully consider \
+ stabilizing its interface")]
+impl<T> ScopedKey<T> {
+ /// Insert a value into this scoped thread local storage slot for a
+ /// duration of a closure.
+ ///
+ /// While `cb` is running, the value `t` will be returned by `get` unless
+ /// this function is called recursively inside of `cb`.
+ ///
+ /// Upon return, this function will restore the previous value, if any
+ /// was available.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # #![feature(scoped_tls)]
+ /// scoped_thread_local!(static FOO: u32);
+ ///
+ /// FOO.set(&100, || {
+ /// let val = FOO.with(|v| *v);
+ /// assert_eq!(val, 100);
+ ///
+ /// // set can be called recursively
+ /// FOO.set(&101, || {
+ /// // ...
+ /// });
+ ///
+ /// // Recursive calls restore the previous value.
+ /// let val = FOO.with(|v| *v);
+ /// assert_eq!(val, 100);
+ /// });
+ /// ```
+ pub fn set<R, F>(&'static self, t: &T, cb: F) -> R where
+ F: FnOnce() -> R,
+ {
+ struct Reset<'a, T: 'a> {
+ key: &'a __impl::KeyInner<T>,
+ val: *mut T,
+ }
+ #[unsafe_destructor]
+ impl<'a, T> Drop for Reset<'a, T> {
+ fn drop(&mut self) {
+ unsafe { self.key.set(self.val) }
+ }
+ }
+
+ let prev = unsafe {
+ let prev = self.inner.get();
+ self.inner.set(t as *const T as *mut T);
+ prev
+ };
+
+ let _reset = Reset { key: &self.inner, val: prev };
+ cb()
+ }
+
+ /// Get a value out of this scoped variable.
+ ///
+ /// This function takes a closure which receives the value of this
+ /// variable.
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if `set` has not previously been called.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # #![feature(scoped_tls)]
+ /// scoped_thread_local!(static FOO: u32);
+ ///
+ /// FOO.with(|slot| {
+ /// // work with `slot`
+ /// });
+ /// ```
+ pub fn with<R, F>(&'static self, cb: F) -> R where
+ F: FnOnce(&T) -> R
+ {
+ unsafe {
+ let ptr = self.inner.get();
+ assert!(!ptr.is_null(), "cannot access a scoped thread local \
+ variable without calling `set` first");
+ cb(&*ptr)
+ }
+ }
+
+ /// Test whether this TLS key has been `set` for the current thread.
+ pub fn is_set(&'static self) -> bool {
+ unsafe { !self.inner.get().is_null() }
+ }
+}
+
+#[cfg(not(any(windows,
+ target_os = "android",
+ target_os = "ios",
+ target_os = "openbsd",
+ target_arch = "aarch64")))]
+mod imp {
+ use std::cell::UnsafeCell;
+
+ #[doc(hidden)]
+ pub struct KeyInner<T> { pub inner: UnsafeCell<*mut T> }
+
+ unsafe impl<T> ::marker::Sync for KeyInner<T> { }
+
+ #[doc(hidden)]
+ impl<T> KeyInner<T> {
+ #[doc(hidden)]
+ pub unsafe fn set(&self, ptr: *mut T) { *self.inner.get() = ptr; }
+ #[doc(hidden)]
+ pub unsafe fn get(&self) -> *mut T { *self.inner.get() }
+ }
+}
+
+#[cfg(any(windows,
+ target_os = "android",
+ target_os = "ios",
+ target_os = "openbsd",
+ target_arch = "aarch64"))]
+mod imp {
+ use marker;
+ use std::cell::Cell;
+ use sys_common::thread_local::StaticKey as OsStaticKey;
+
+ #[doc(hidden)]
+ pub struct KeyInner<T> {
+ pub inner: OsStaticKey,
+ pub marker: marker::PhantomData<Cell<T>>,
+ }
+
+ unsafe impl<T> ::marker::Sync for KeyInner<T> { }
+
+ #[doc(hidden)]
+ impl<T> KeyInner<T> {
+ #[doc(hidden)]
+ pub unsafe fn set(&self, ptr: *mut T) { self.inner.set(ptr as *mut _) }
+ #[doc(hidden)]
+ pub unsafe fn get(&self) -> *mut T { self.inner.get() as *mut _ }
+ }
+}
+
+
+#[cfg(test)]
+mod tests {
+ use cell::Cell;
+ use prelude::v1::*;
+
+ scoped_thread_local!(static FOO: u32);
+
+ #[test]
+ fn smoke() {
+ scoped_thread_local!(static BAR: u32);
+
+ assert!(!BAR.is_set());
+ BAR.set(&1, || {
+ assert!(BAR.is_set());
+ BAR.with(|slot| {
+ assert_eq!(*slot, 1);
+ });
+ });
+ assert!(!BAR.is_set());
+ }
+
+ #[test]
+ fn cell_allowed() {
+ scoped_thread_local!(static BAR: Cell<u32>);
+
+ BAR.set(&Cell::new(1), || {
+ BAR.with(|slot| {
+ assert_eq!(slot.get(), 1);
+ });
+ });
+ }
+
+ #[test]
+ fn scope_item_allowed() {
+ assert!(!FOO.is_set());
+ FOO.set(&1, || {
+ assert!(FOO.is_set());
+ FOO.with(|slot| {
+ assert_eq!(*slot, 1);
+ });
+ });
+ assert!(!FOO.is_set());
+ }
+}
+++ /dev/null
-// 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.
-//
-// 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.
-
-//! Thread local storage
-//!
-//! This module provides an implementation of thread local storage for Rust
-//! programs. Thread local storage is a method of storing data into a global
-//! variable which each thread in the program will have its own copy of.
-//! Threads do not share this data, so accesses do not need to be synchronized.
-//!
-//! At a high level, this module provides two variants of storage:
-//!
-//! * Owning thread local storage. This is a type of thread local key which
-//! owns the value that it contains, and will destroy the value when the
-//! thread exits. This variant is created with the `thread_local!` macro and
-//! can contain any value which is `'static` (no borrowed pointers.
-//!
-//! * Scoped thread local storage. This type of key is used to store a reference
-//! to a value into local storage temporarily for the scope of a function
-//! call. There are no restrictions on what types of values can be placed
-//! into this key.
-//!
-//! Both forms of thread local storage provide an accessor function, `with`,
-//! which will yield a shared reference to the value to the specified
-//! closure. Thread local keys only allow shared access to values as there is no
-//! way to guarantee uniqueness if a mutable borrow was allowed. Most values
-//! will want to make use of some form of **interior mutability** through the
-//! `Cell` or `RefCell` types.
-
-#![stable(feature = "rust1", since = "1.0.0")]
-
-use prelude::v1::*;
-
-use cell::UnsafeCell;
-
-#[macro_use]
-pub mod scoped;
-
-// Sure wish we had macro hygiene, no?
-#[doc(hidden)]
-#[unstable(feature = "thread_local_internals")]
-pub mod __impl {
- pub use super::imp::Key as KeyInner;
- pub use super::imp::destroy_value;
- pub use sys_common::thread_local::INIT_INNER as OS_INIT_INNER;
- pub use sys_common::thread_local::StaticKey as OsStaticKey;
-}
-
-/// A thread local storage key which owns its contents.
-///
-/// This key uses the fastest possible implementation available to it for the
-/// target platform. It is instantiated with the `thread_local!` macro and the
-/// primary method is the `with` method.
-///
-/// The `with` method yields a reference to the contained value which cannot be
-/// sent across tasks or escape the given closure.
-///
-/// # Initialization and Destruction
-///
-/// Initialization is dynamically performed on the first call to `with()`
-/// within a thread, and values support destructors which will be run when a
-/// thread exits.
-///
-/// # Examples
-///
-/// ```
-/// use std::cell::RefCell;
-/// use std::thread;
-///
-/// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
-///
-/// FOO.with(|f| {
-/// assert_eq!(*f.borrow(), 1);
-/// *f.borrow_mut() = 2;
-/// });
-///
-/// // each thread starts out with the initial value of 1
-/// thread::spawn(move|| {
-/// FOO.with(|f| {
-/// assert_eq!(*f.borrow(), 1);
-/// *f.borrow_mut() = 3;
-/// });
-/// });
-///
-/// // we retain our original value of 2 despite the child thread
-/// FOO.with(|f| {
-/// assert_eq!(*f.borrow(), 2);
-/// });
-/// ```
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Key<T> {
- // The key itself may be tagged with #[thread_local], and this `Key` is
- // stored as a `static`, and it's not valid for a static to reference the
- // address of another thread_local static. For this reason we kinda wonkily
- // work around this by generating a shim function which will give us the
- // address of the inner TLS key at runtime.
- //
- // This is trivially devirtualizable by LLVM because we never store anything
- // to this field and rustc can declare the `static` as constant as well.
- #[doc(hidden)]
- #[unstable(feature = "thread_local_internals")]
- pub inner: fn() -> &'static __impl::KeyInner<UnsafeCell<Option<T>>>,
-
- // initialization routine to invoke to create a value
- #[doc(hidden)]
- #[unstable(feature = "thread_local_internals")]
- pub init: fn() -> T,
-}
-
-/// Declare a new thread local storage key of type `std::thread_local::Key`.
-#[macro_export]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[allow_internal_unstable]
-macro_rules! thread_local {
- (static $name:ident: $t:ty = $init:expr) => (
- static $name: ::std::thread_local::Key<$t> = {
- use std::cell::UnsafeCell as __UnsafeCell;
- use std::thread_local::__impl::KeyInner as __KeyInner;
- use std::option::Option as __Option;
- use std::option::Option::None as __None;
-
- __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = {
- __UnsafeCell { value: __None }
- });
- fn __init() -> $t { $init }
- fn __getit() -> &'static __KeyInner<__UnsafeCell<__Option<$t>>> {
- &__KEY
- }
- ::std::thread_local::Key { inner: __getit, init: __init }
- };
- );
- (pub static $name:ident: $t:ty = $init:expr) => (
- pub static $name: ::std::thread_local::Key<$t> = {
- use std::cell::UnsafeCell as __UnsafeCell;
- use std::thread_local::__impl::KeyInner as __KeyInner;
- use std::option::Option as __Option;
- use std::option::Option::None as __None;
-
- __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = {
- __UnsafeCell { value: __None }
- });
- fn __init() -> $t { $init }
- fn __getit() -> &'static __KeyInner<__UnsafeCell<__Option<$t>>> {
- &__KEY
- }
- ::std::thread_local::Key { inner: __getit, init: __init }
- };
- );
-}
-
-// Macro pain #4586:
-//
-// When cross compiling, rustc will load plugins and macros from the *host*
-// platform before search for macros from the target platform. This is primarily
-// done to detect, for example, plugins. Ideally the macro below would be
-// defined once per module below, but unfortunately this means we have the
-// following situation:
-//
-// 1. We compile libstd for x86_64-unknown-linux-gnu, this thread_local!() macro
-// will inject #[thread_local] statics.
-// 2. We then try to compile a program for arm-linux-androideabi
-// 3. The compiler has a host of linux and a target of android, so it loads
-// macros from the *linux* libstd.
-// 4. The macro generates a #[thread_local] field, but the android libstd does
-// not use #[thread_local]
-// 5. Compile error about structs with wrong fields.
-//
-// To get around this, we're forced to inject the #[cfg] logic into the macro
-// itself. Woohoo.
-
-#[macro_export]
-#[doc(hidden)]
-#[allow_internal_unstable]
-macro_rules! __thread_local_inner {
- (static $name:ident: $t:ty = $init:expr) => (
- #[cfg_attr(all(any(target_os = "macos", target_os = "linux"),
- not(target_arch = "aarch64")),
- thread_local)]
- static $name: ::std::thread_local::__impl::KeyInner<$t> =
- __thread_local_inner!($init, $t);
- );
- (pub static $name:ident: $t:ty = $init:expr) => (
- #[cfg_attr(all(any(target_os = "macos", target_os = "linux"),
- not(target_arch = "aarch64")),
- thread_local)]
- pub static $name: ::std::thread_local::__impl::KeyInner<$t> =
- __thread_local_inner!($init, $t);
- );
- ($init:expr, $t:ty) => ({
- #[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))]
- const _INIT: ::std::thread_local::__impl::KeyInner<$t> = {
- ::std::thread_local::__impl::KeyInner {
- inner: ::std::cell::UnsafeCell { value: $init },
- dtor_registered: ::std::cell::UnsafeCell { value: false },
- dtor_running: ::std::cell::UnsafeCell { value: false },
- }
- };
-
- #[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))]
- const _INIT: ::std::thread_local::__impl::KeyInner<$t> = {
- unsafe extern fn __destroy(ptr: *mut u8) {
- ::std::thread_local::__impl::destroy_value::<$t>(ptr);
- }
-
- ::std::thread_local::__impl::KeyInner {
- inner: ::std::cell::UnsafeCell { value: $init },
- os: ::std::thread_local::__impl::OsStaticKey {
- inner: ::std::thread_local::__impl::OS_INIT_INNER,
- dtor: ::std::option::Option::Some(__destroy as unsafe extern fn(*mut u8)),
- },
- }
- };
-
- _INIT
- });
-}
-
-/// Indicator of the state of a thread local storage key.
-#[unstable(feature = "std_misc",
- reason = "state querying was recently added")]
-#[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
- /// and the initialization expression succeeds.
- ///
- /// Keys in the `Uninitialized` state will yield a reference to the closure
- /// passed to `with` so long as the initialization routine does not panic.
- Uninitialized,
-
- /// Once a key has been accessed successfully, it will enter the `Valid`
- /// state. Keys in the `Valid` state will remain so until the thread exits,
- /// at which point the destructor will be run and the key will enter the
- /// `Destroyed` state.
- ///
- /// Keys in the `Valid` state will be guaranteed to yield a reference to the
- /// closure passed to `with`.
- Valid,
-
- /// When a thread exits, the destructors for keys will be run (if
- /// necessary). While a destructor is running, and possibly after a
- /// destructor has run, a key is in the `Destroyed` state.
- ///
- /// Keys in the `Destroyed` states will trigger a panic when accessed via
- /// `with`.
- Destroyed,
-}
-
-impl<T: 'static> Key<T> {
- /// Acquire a reference to the value in this TLS key.
- ///
- /// This will lazily initialize the value if this thread has not referenced
- /// this key yet.
- ///
- /// # Panics
- ///
- /// This function will `panic!()` if the key currently has its
- /// destructor running, and it **may** panic if the destructor has
- /// previously been run for this thread.
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn with<F, R>(&'static self, f: F) -> R
- where F: FnOnce(&T) -> R {
- let slot = (self.inner)();
- unsafe {
- let slot = slot.get().expect("cannot access a TLS value during or \
- after it is destroyed");
- f(match *slot.get() {
- Some(ref inner) => inner,
- None => self.init(slot),
- })
- }
- }
-
- unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
- // Execute the initialization up front, *then* move it into our slot,
- // just in case initialization fails.
- let value = (self.init)();
- let ptr = slot.get();
- *ptr = Some(value);
- (*ptr).as_ref().unwrap()
- }
-
- /// Query the current state of this key.
- ///
- /// A key is initially in the `Uninitialized` state whenever a thread
- /// starts. It will remain in this state up until the first call to `with`
- /// within a thread has run the initialization expression successfully.
- ///
- /// Once the initialization expression succeeds, the key transitions to the
- /// `Valid` state which will guarantee that future calls to `with` will
- /// succeed within the thread.
- ///
- /// When a thread exits, each key will be destroyed in turn, and as keys are
- /// destroyed they will enter the `Destroyed` state just before the
- /// destructor starts to run. Keys may remain in the `Destroyed` state after
- /// destruction has completed. Keys without destructors (e.g. with types
- /// that are `Copy`), may never enter the `Destroyed` state.
- ///
- /// Keys in the `Uninitialized` can be accessed so long as the
- /// initialization does not panic. Keys in the `Valid` state are guaranteed
- /// to be able to be accessed. Keys in the `Destroyed` state will panic on
- /// any call to `with`.
- #[unstable(feature = "std_misc",
- reason = "state querying was recently added")]
- pub fn state(&'static self) -> State {
- unsafe {
- match (self.inner)().get() {
- Some(cell) => {
- match *cell.get() {
- Some(..) => State::Valid,
- None => State::Uninitialized,
- }
- }
- None => State::Destroyed,
- }
- }
- }
-
- /// Deprecated
- #[unstable(feature = "std_misc")]
- #[deprecated(since = "1.0.0",
- reason = "function renamed to state() and returns more info")]
- pub fn destroyed(&'static self) -> bool { self.state() == State::Destroyed }
-}
-
-#[cfg(all(any(target_os = "macos", target_os = "linux"), not(target_arch = "aarch64")))]
-mod imp {
- use prelude::v1::*;
-
- use cell::UnsafeCell;
- use intrinsics;
- use ptr;
-
- #[doc(hidden)]
- #[unstable(feature = "thread_local_internals")]
- pub struct Key<T> {
- // Place the inner bits in an `UnsafeCell` to currently get around the
- // "only Sync statics" restriction. This allows any type to be placed in
- // the cell.
- //
- // Note that all access requires `T: 'static` so it can't be a type with
- // any borrowed pointers still.
- #[unstable(feature = "thread_local_internals")]
- pub inner: UnsafeCell<T>,
-
- // Metadata to keep track of the state of the destructor. Remember that
- // these variables are thread-local, not global.
- #[unstable(feature = "thread_local_internals")]
- pub dtor_registered: UnsafeCell<bool>, // should be Cell
- #[unstable(feature = "thread_local_internals")]
- pub dtor_running: UnsafeCell<bool>, // should be Cell
- }
-
- unsafe impl<T> ::marker::Sync for Key<T> { }
-
- #[doc(hidden)]
- impl<T> Key<T> {
- pub unsafe fn get(&'static self) -> Option<&'static T> {
- if intrinsics::needs_drop::<T>() && *self.dtor_running.get() {
- return None
- }
- self.register_dtor();
- Some(&*self.inner.get())
- }
-
- unsafe fn register_dtor(&self) {
- if !intrinsics::needs_drop::<T>() || *self.dtor_registered.get() {
- return
- }
-
- register_dtor(self as *const _ as *mut u8,
- destroy_value::<T>);
- *self.dtor_registered.get() = true;
- }
- }
-
- // Since what appears to be glibc 2.18 this symbol has been shipped which
- // GCC and clang both use to invoke destructors in thread_local globals, so
- // let's do the same!
- //
- // Note, however, that we run on lots older linuxes, as well as cross
- // compiling from a newer linux to an older linux, so we also have a
- // fallback implementation to use as well.
- //
- // Due to rust-lang/rust#18804, make sure this is not generic!
- #[cfg(target_os = "linux")]
- unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
- use boxed;
- use mem;
- use libc;
- use sys_common::thread_local as os;
-
- extern {
- static __dso_handle: *mut u8;
- #[linkage = "extern_weak"]
- static __cxa_thread_atexit_impl: *const ();
- }
- if !__cxa_thread_atexit_impl.is_null() {
- type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8),
- arg: *mut u8,
- dso_handle: *mut u8) -> libc::c_int;
- mem::transmute::<*const (), F>(__cxa_thread_atexit_impl)
- (dtor, t, __dso_handle);
- return
- }
-
- // The fallback implementation uses a vanilla OS-based TLS key to track
- // the list of destructors that need to be run for this thread. The key
- // then has its own destructor which runs all the other destructors.
- //
- // The destructor for DTORS is a little special in that it has a `while`
- // loop to continuously drain the list of registered destructors. It
- // *should* be the case that this loop always terminates because we
- // provide the guarantee that a TLS key cannot be set after it is
- // flagged for destruction.
- static DTORS: os::StaticKey = os::StaticKey {
- inner: os::INIT_INNER,
- dtor: Some(run_dtors as unsafe extern "C" fn(*mut u8)),
- };
- type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>;
- if DTORS.get().is_null() {
- let v: Box<List> = box Vec::new();
- DTORS.set(boxed::into_raw(v) as *mut u8);
- }
- let list: &mut List = &mut *(DTORS.get() as *mut List);
- list.push((t, dtor));
-
- unsafe extern fn run_dtors(mut ptr: *mut u8) {
- while !ptr.is_null() {
- let list: Box<List> = Box::from_raw(ptr as *mut List);
- for &(ptr, dtor) in &*list {
- dtor(ptr);
- }
- ptr = DTORS.get();
- DTORS.set(ptr::null_mut());
- }
- }
- }
-
- // OSX's analog of the above linux function is this _tlv_atexit function.
- // The disassembly of thread_local globals in C++ (at least produced by
- // clang) will have this show up in the output.
- #[cfg(target_os = "macos")]
- unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
- extern {
- fn _tlv_atexit(dtor: unsafe extern fn(*mut u8),
- arg: *mut u8);
- }
- _tlv_atexit(dtor, t);
- }
-
- #[doc(hidden)]
- #[unstable(feature = "thread_local_internals")]
- pub unsafe extern fn destroy_value<T>(ptr: *mut u8) {
- let ptr = ptr as *mut Key<T>;
- // Right before we run the user destructor be sure to flag the
- // destructor as running for this thread so calls to `get` will return
- // `None`.
- *(*ptr).dtor_running.get() = true;
- ptr::read((*ptr).inner.get());
- }
-}
-
-#[cfg(any(not(any(target_os = "macos", target_os = "linux")), target_arch = "aarch64"))]
-mod imp {
- use prelude::v1::*;
-
- use alloc::boxed;
- use cell::UnsafeCell;
- use mem;
- use ptr;
- use sys_common::thread_local::StaticKey as OsStaticKey;
-
- #[doc(hidden)]
- #[unstable(feature = "thread_local_internals")]
- pub struct Key<T> {
- // Statically allocated initialization expression, using an `UnsafeCell`
- // for the same reasons as above.
- #[unstable(feature = "thread_local_internals")]
- pub inner: UnsafeCell<T>,
-
- // OS-TLS key that we'll use to key off.
- #[unstable(feature = "thread_local_internals")]
- pub os: OsStaticKey,
- }
-
- unsafe impl<T> ::marker::Sync for Key<T> { }
-
- struct Value<T: 'static> {
- key: &'static Key<T>,
- value: T,
- }
-
- #[doc(hidden)]
- impl<T> Key<T> {
- pub unsafe fn get(&'static self) -> Option<&'static T> {
- self.ptr().map(|p| &*p)
- }
-
- unsafe fn ptr(&'static self) -> Option<*mut T> {
- let ptr = self.os.get() as *mut Value<T>;
- if !ptr.is_null() {
- if ptr as usize == 1 {
- return None
- }
- return Some(&mut (*ptr).value as *mut T);
- }
-
- // If the lookup returned null, we haven't initialized our own local
- // copy, so do that now.
- //
- // Also note that this transmute_copy should be ok because the value
- // `inner` is already validated to be a valid `static` value, so we
- // should be able to freely copy the bits.
- let ptr: Box<Value<T>> = box Value {
- key: self,
- value: mem::transmute_copy(&self.inner),
- };
- let ptr: *mut Value<T> = boxed::into_raw(ptr);
- self.os.set(ptr as *mut u8);
- Some(&mut (*ptr).value as *mut T)
- }
- }
-
- #[doc(hidden)]
- #[unstable(feature = "thread_local_internals")]
- pub unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
- // The OS TLS ensures that this key contains a NULL value when this
- // destructor starts to run. We set it back to a sentinel value of 1 to
- // ensure that any future calls to `get` for this thread will return
- // `None`.
- //
- // Note that to prevent an infinite loop we reset it back to null right
- // before we return from the destructor ourselves.
- let ptr: Box<Value<T>> = Box::from_raw(ptr as *mut Value<T>);
- let key = ptr.key;
- key.os.set(1 as *mut u8);
- drop(ptr);
- key.os.set(ptr::null_mut());
- }
-}
-
-#[cfg(test)]
-mod tests {
- use prelude::v1::*;
-
- use sync::mpsc::{channel, Sender};
- use cell::UnsafeCell;
- use super::State;
- use thread;
-
- struct Foo(Sender<()>);
-
- impl Drop for Foo {
- fn drop(&mut self) {
- let Foo(ref s) = *self;
- s.send(()).unwrap();
- }
- }
-
- #[test]
- fn smoke_no_dtor() {
- thread_local!(static FOO: UnsafeCell<i32> = UnsafeCell { value: 1 });
-
- FOO.with(|f| unsafe {
- assert_eq!(*f.get(), 1);
- *f.get() = 2;
- });
- let (tx, rx) = channel();
- let _t = thread::spawn(move|| {
- FOO.with(|f| unsafe {
- assert_eq!(*f.get(), 1);
- });
- tx.send(()).unwrap();
- });
- rx.recv().unwrap();
-
- FOO.with(|f| unsafe {
- assert_eq!(*f.get(), 2);
- });
- }
-
- #[test]
- fn states() {
- struct Foo;
- impl Drop for Foo {
- fn drop(&mut self) {
- assert!(FOO.state() == State::Destroyed);
- }
- }
- fn foo() -> Foo {
- assert!(FOO.state() == State::Uninitialized);
- Foo
- }
- thread_local!(static FOO: Foo = foo());
-
- thread::spawn(|| {
- assert!(FOO.state() == State::Uninitialized);
- FOO.with(|_| {
- assert!(FOO.state() == State::Valid);
- });
- assert!(FOO.state() == State::Valid);
- }).join().ok().unwrap();
- }
-
- #[test]
- fn smoke_dtor() {
- thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell {
- value: None
- });
-
- let (tx, rx) = channel();
- let _t = thread::spawn(move|| unsafe {
- let mut tx = Some(tx);
- FOO.with(|f| {
- *f.get() = Some(Foo(tx.take().unwrap()));
- });
- });
- rx.recv().unwrap();
- }
-
- #[test]
- fn circular() {
- struct S1;
- struct S2;
- thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell {
- value: None
- });
- thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell {
- value: None
- });
- static mut HITS: u32 = 0;
-
- impl Drop for S1 {
- fn drop(&mut self) {
- unsafe {
- HITS += 1;
- if K2.state() == State::Destroyed {
- assert_eq!(HITS, 3);
- } else {
- if HITS == 1 {
- K2.with(|s| *s.get() = Some(S2));
- } else {
- assert_eq!(HITS, 3);
- }
- }
- }
- }
- }
- impl Drop for S2 {
- fn drop(&mut self) {
- unsafe {
- HITS += 1;
- assert!(K1.state() != State::Destroyed);
- assert_eq!(HITS, 2);
- K1.with(|s| *s.get() = Some(S1));
- }
- }
- }
-
- thread::spawn(move|| {
- drop(S1);
- }).join().ok().unwrap();
- }
-
- #[test]
- fn self_referential() {
- struct S1;
- thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell {
- value: None
- });
-
- impl Drop for S1 {
- fn drop(&mut self) {
- assert!(K1.state() == State::Destroyed);
- }
- }
-
- thread::spawn(move|| unsafe {
- K1.with(|s| *s.get() = Some(S1));
- }).join().ok().unwrap();
- }
-
- #[test]
- fn dtors_in_dtors_in_dtors() {
- struct S1(Sender<()>);
- thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell {
- value: None
- });
- thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell {
- value: None
- });
-
- impl Drop for S1 {
- fn drop(&mut self) {
- let S1(ref tx) = *self;
- unsafe {
- if K2.state() != State::Destroyed {
- K2.with(|s| *s.get() = Some(Foo(tx.clone())));
- }
- }
- }
- }
-
- let (tx, rx) = channel();
- let _t = thread::spawn(move|| unsafe {
- let mut tx = Some(tx);
- K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
- });
- rx.recv().unwrap();
- }
-}
-
-#[cfg(test)]
-mod dynamic_tests {
- use prelude::v1::*;
-
- use cell::RefCell;
- use collections::HashMap;
-
- #[test]
- fn smoke() {
- fn square(i: i32) -> i32 { i * i }
- thread_local!(static FOO: i32 = square(3));
-
- FOO.with(|f| {
- assert_eq!(*f, 9);
- });
- }
-
- #[test]
- fn hashmap() {
- fn map() -> RefCell<HashMap<i32, i32>> {
- let mut m = HashMap::new();
- m.insert(1, 2);
- RefCell::new(m)
- }
- thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
-
- FOO.with(|map| {
- assert_eq!(map.borrow()[1], 2);
- });
- }
-
- #[test]
- fn refcell_vec() {
- thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
-
- FOO.with(|vec| {
- assert_eq!(vec.borrow().len(), 3);
- vec.borrow_mut().push(4);
- assert_eq!(vec.borrow()[3], 4);
- });
- }
-}
+++ /dev/null
-// 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.
-//
-// 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.
-
-//! Scoped thread-local storage
-//!
-//! This module provides the ability to generate *scoped* thread-local
-//! variables. In this sense, scoped indicates that thread local storage
-//! actually stores a reference to a value, and this reference is only placed
-//! in storage for a scoped amount of time.
-//!
-//! There are no restrictions on what types can be placed into a scoped
-//! variable, but all scoped variables are initialized to the equivalent of
-//! null. Scoped thread local storage is useful when a value is present for a known
-//! period of time and it is not required to relinquish ownership of the
-//! contents.
-//!
-//! # Examples
-//!
-//! ```
-//! scoped_thread_local!(static FOO: u32);
-//!
-//! // Initially each scoped slot is empty.
-//! assert!(!FOO.is_set());
-//!
-//! // When inserting a value, the value is only in place for the duration
-//! // of the closure specified.
-//! FOO.set(&1, || {
-//! FOO.with(|slot| {
-//! assert_eq!(*slot, 1);
-//! });
-//! });
-//! ```
-
-#![unstable(feature = "std_misc",
- reason = "scoped TLS has yet to have wide enough use to fully consider \
- stabilizing its interface")]
-
-use prelude::v1::*;
-
-// macro hygiene sure would be nice, wouldn't it?
-#[doc(hidden)]
-pub mod __impl {
- pub use super::imp::KeyInner;
- pub use sys_common::thread_local::INIT as OS_INIT;
-}
-
-/// Type representing a thread local storage key corresponding to a reference
-/// to the type parameter `T`.
-///
-/// Keys are statically allocated and can contain a reference to an instance of
-/// type `T` scoped to a particular lifetime. Keys provides two methods, `set`
-/// and `with`, both of which currently use closures to control the scope of
-/// their contents.
-pub struct Key<T> { #[doc(hidden)] pub inner: __impl::KeyInner<T> }
-
-/// Declare a new scoped thread local storage key.
-///
-/// This macro declares a `static` item on which methods are used to get and
-/// set the value stored within.
-#[macro_export]
-#[allow_internal_unstable]
-macro_rules! scoped_thread_local {
- (static $name:ident: $t:ty) => (
- __scoped_thread_local_inner!(static $name: $t);
- );
- (pub static $name:ident: $t:ty) => (
- __scoped_thread_local_inner!(pub static $name: $t);
- );
-}
-
-#[macro_export]
-#[doc(hidden)]
-#[allow_internal_unstable]
-macro_rules! __scoped_thread_local_inner {
- (static $name:ident: $t:ty) => (
- #[cfg_attr(not(any(windows,
- target_os = "android",
- target_os = "ios",
- target_os = "openbsd",
- target_arch = "aarch64")),
- thread_local)]
- static $name: ::std::thread_local::scoped::Key<$t> =
- __scoped_thread_local_inner!($t);
- );
- (pub static $name:ident: $t:ty) => (
- #[cfg_attr(not(any(windows,
- target_os = "android",
- target_os = "ios",
- target_os = "openbsd",
- target_arch = "aarch64")),
- thread_local)]
- pub static $name: ::std::thread_local::scoped::Key<$t> =
- __scoped_thread_local_inner!($t);
- );
- ($t:ty) => ({
- use std::thread_local::scoped::Key as __Key;
-
- #[cfg(not(any(windows,
- target_os = "android",
- target_os = "ios",
- target_os = "openbsd",
- target_arch = "aarch64")))]
- const _INIT: __Key<$t> = __Key {
- inner: ::std::thread_local::scoped::__impl::KeyInner {
- inner: ::std::cell::UnsafeCell { value: 0 as *mut _ },
- }
- };
-
- #[cfg(any(windows,
- target_os = "android",
- target_os = "ios",
- target_os = "openbsd",
- target_arch = "aarch64"))]
- const _INIT: __Key<$t> = __Key {
- inner: ::std::thread_local::scoped::__impl::KeyInner {
- inner: ::std::thread_local::scoped::__impl::OS_INIT,
- marker: ::std::marker::PhantomData::<::std::cell::Cell<$t>>,
- }
- };
-
- _INIT
- })
-}
-
-impl<T> Key<T> {
- /// Insert a value into this scoped thread local storage slot for a
- /// duration of a closure.
- ///
- /// While `cb` is running, the value `t` will be returned by `get` unless
- /// this function is called recursively inside of `cb`.
- ///
- /// Upon return, this function will restore the previous value, if any
- /// was available.
- ///
- /// # Examples
- ///
- /// ```
- /// scoped_thread_local!(static FOO: u32);
- ///
- /// FOO.set(&100, || {
- /// let val = FOO.with(|v| *v);
- /// assert_eq!(val, 100);
- ///
- /// // set can be called recursively
- /// FOO.set(&101, || {
- /// // ...
- /// });
- ///
- /// // Recursive calls restore the previous value.
- /// let val = FOO.with(|v| *v);
- /// assert_eq!(val, 100);
- /// });
- /// ```
- pub fn set<R, F>(&'static self, t: &T, cb: F) -> R where
- F: FnOnce() -> R,
- {
- struct Reset<'a, T: 'a> {
- key: &'a __impl::KeyInner<T>,
- val: *mut T,
- }
- #[unsafe_destructor]
- impl<'a, T> Drop for Reset<'a, T> {
- fn drop(&mut self) {
- unsafe { self.key.set(self.val) }
- }
- }
-
- let prev = unsafe {
- let prev = self.inner.get();
- self.inner.set(t as *const T as *mut T);
- prev
- };
-
- let _reset = Reset { key: &self.inner, val: prev };
- cb()
- }
-
- /// Get a value out of this scoped variable.
- ///
- /// This function takes a closure which receives the value of this
- /// variable.
- ///
- /// # Panics
- ///
- /// This function will panic if `set` has not previously been called.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// scoped_thread_local!(static FOO: u32);
- ///
- /// FOO.with(|slot| {
- /// // work with `slot`
- /// });
- /// ```
- pub fn with<R, F>(&'static self, cb: F) -> R where
- F: FnOnce(&T) -> R
- {
- unsafe {
- let ptr = self.inner.get();
- assert!(!ptr.is_null(), "cannot access a scoped thread local \
- variable without calling `set` first");
- cb(&*ptr)
- }
- }
-
- /// Test whether this TLS key has been `set` for the current thread.
- pub fn is_set(&'static self) -> bool {
- unsafe { !self.inner.get().is_null() }
- }
-}
-
-#[cfg(not(any(windows,
- target_os = "android",
- target_os = "ios",
- target_os = "openbsd",
- target_arch = "aarch64")))]
-mod imp {
- use std::cell::UnsafeCell;
-
- #[doc(hidden)]
- pub struct KeyInner<T> { pub inner: UnsafeCell<*mut T> }
-
- unsafe impl<T> ::marker::Sync for KeyInner<T> { }
-
- #[doc(hidden)]
- impl<T> KeyInner<T> {
- #[doc(hidden)]
- pub unsafe fn set(&self, ptr: *mut T) { *self.inner.get() = ptr; }
- #[doc(hidden)]
- pub unsafe fn get(&self) -> *mut T { *self.inner.get() }
- }
-}
-
-#[cfg(any(windows,
- target_os = "android",
- target_os = "ios",
- target_os = "openbsd",
- target_arch = "aarch64"))]
-mod imp {
- use marker;
- use std::cell::Cell;
- use sys_common::thread_local::StaticKey as OsStaticKey;
-
- #[doc(hidden)]
- pub struct KeyInner<T> {
- pub inner: OsStaticKey,
- pub marker: marker::PhantomData<Cell<T>>,
- }
-
- unsafe impl<T> ::marker::Sync for KeyInner<T> { }
-
- #[doc(hidden)]
- impl<T> KeyInner<T> {
- #[doc(hidden)]
- pub unsafe fn set(&self, ptr: *mut T) { self.inner.set(ptr as *mut _) }
- #[doc(hidden)]
- pub unsafe fn get(&self) -> *mut T { self.inner.get() as *mut _ }
- }
-}
-
-
-#[cfg(test)]
-mod tests {
- use cell::Cell;
- use prelude::v1::*;
-
- scoped_thread_local!(static FOO: u32);
-
- #[test]
- fn smoke() {
- scoped_thread_local!(static BAR: u32);
-
- assert!(!BAR.is_set());
- BAR.set(&1, || {
- assert!(BAR.is_set());
- BAR.with(|slot| {
- assert_eq!(*slot, 1);
- });
- });
- assert!(!BAR.is_set());
- }
-
- #[test]
- fn cell_allowed() {
- scoped_thread_local!(static BAR: Cell<u32>);
-
- BAR.set(&Cell::new(1), || {
- BAR.with(|slot| {
- assert_eq!(slot.get(), 1);
- });
- });
- }
-
- #[test]
- fn scope_item_allowed() {
- assert!(!FOO.is_set());
- FOO.set(&1, || {
- assert!(FOO.is_set());
- FOO.with(|slot| {
- assert_eq!(*slot, 1);
- });
- });
- assert!(!FOO.is_set());
- }
-}
impl ExpnId {
pub fn from_llvm_cookie(cookie: c_uint) -> ExpnId {
- ExpnId(cookie as u32)
+ ExpnId(cookie)
}
pub fn to_llvm_cookie(self) -> i32 {
let max_line_length = if lines.len() == 1 {
0
} else {
- lines.as_slice()
- .windows(2)
+ lines.windows(2)
.map(|w| w[1] - w[0])
.map(|bp| bp.to_usize())
.max()
match bytes_per_diff {
1 => for diff in diff_iter { try! { (diff.0 as u8).encode(s) } },
2 => for diff in diff_iter { try! { (diff.0 as u16).encode(s) } },
- 4 => for diff in diff_iter { try! { (diff.0 as u32).encode(s) } },
+ 4 => for diff in diff_iter { try! { diff.0.encode(s) } },
_ => unreachable!()
}
}
let lo = self.lookup_char_pos(sp.lo);
let hi = self.lookup_char_pos(sp.hi);
let mut lines = Vec::new();
- for i in lo.line - 1..hi.line as usize {
+ for i in lo.line - 1..hi.line {
lines.push(i);
};
FileLines {file: lo.file, lines: lines}
box MacEager {
$fld: Some(v),
..Default::default()
- } as Box<MacResult>
+ }
}
)*
}
/// Use this as a return value after hitting any errors and
/// calling `span_err`.
pub fn any(sp: Span) -> Box<MacResult+'static> {
- box DummyResult { expr_only: false, span: sp } as Box<MacResult+'static>
+ box DummyResult { expr_only: false, span: sp }
}
/// Create a default MacResult that can only be an expression.
/// if an error is encountered internally, the user will receive
/// an error that they also used it in the wrong place.
pub fn expr(sp: Span) -> Box<MacResult+'static> {
- box DummyResult { expr_only: true, span: sp } as Box<MacResult+'static>
+ box DummyResult { expr_only: true, span: sp }
}
/// A plain dummy expression.
pub mod generic;
-fn expand_deprecated_deriving(cx: &mut ExtCtxt,
- span: Span,
- _: &MetaItem,
- _: &Item,
- _: &mut FnMut(P<Item>)) {
- cx.span_err(span, "`deriving` has been renamed to `derive`");
-}
-
fn expand_derive(cx: &mut ExtCtxt,
_: Span,
mitem: &MetaItem,
env.insert(intern("derive"),
Modifier(Box::new(expand_derive)));
- env.insert(intern("deriving"),
- Decorator(Box::new(expand_deprecated_deriving)));
}
fn is_builtin_trait(name: &str) -> bool {
let lname = self.ecx.ident_of(&format!("__arg{}",
*name));
pats.push(self.ecx.pat_ident(e.span, lname));
- names[self.name_positions[*name]] =
+ names[*self.name_positions.get(name).unwrap()] =
Some(Context::format_arg(self.ecx, e.span, arg_ty,
self.ecx.expr_ident(e.span, lname)));
heads.push(self.ecx.expr_addr_of(e.span, e));
(unsigned, $t:ty, $tag:expr) => (
impl ToSource for $t {
fn to_source(&self) -> String {
+ #![allow(trivial_numeric_casts)]
let lit = ast::LitInt(*self as u64, ast::UnsignedIntLit($tag));
pprust::lit_to_string(&dummy_spanned(lit))
}
fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> PathBuf {
// NB: relative paths are resolved relative to the compilation unit
if !arg.is_absolute() {
- let mut cu = PathBuf::new(&cx.codemap().span_to_filename(sp));
+ let mut cu = PathBuf::from(&cx.codemap().span_to_filename(sp));
cu.pop();
cu.push(arg);
cu
// Weird, but useful for X-macros.
return box ParserAnyMacro {
parser: RefCell::new(p),
- } as Box<MacResult+'cx>
+ }
}
Failure(sp, ref msg) => if sp.lo >= best_fail_spot.lo {
best_fail_spot = sp;
argument_gram);
// Extract the arguments:
- let lhses = match *argument_map[lhs_nm] {
+ let lhses = match **argument_map.get(&lhs_nm).unwrap() {
MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(),
_ => cx.span_bug(def.span, "wrong-structured lhs")
};
check_lhs_nt_follows(cx, &**lhs, def.span);
}
- let rhses = match *argument_map[rhs_nm] {
+ let rhses = match **argument_map.get(&rhs_nm).unwrap() {
MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(),
_ => cx.span_bug(def.span, "wrong-structured rhs")
};
("no_mangle", Normal),
("no_link", Normal),
("derive", Normal),
- ("deriving", Normal), // deprecation err in expansion
("should_fail", Normal),
("should_panic", Normal),
("ignore", Normal),
("link_section", Whitelisted),
("no_builtins", Whitelisted),
("no_mangle", Whitelisted),
- ("no_split_stack", Whitelisted),
("no_stack_check", Whitelisted),
("packed", Whitelisted),
("static_assert", Gated("static_assert",
}
}
+ ast::ItemDefaultImpl(..) => {
+ self.gate_feature("optin_builtin_traits",
+ i.span,
+ "default trait implementations are experimental \
+ and possibly buggy");
+ }
+
ast::ItemImpl(_, polarity, _, _, _, _) => {
match polarity {
ast::ImplPolarity::Negative => {
#![feature(unicode)]
#![feature(path_ext)]
#![feature(str_char)]
+#![feature(convert)]
+#![feature(into_cow)]
extern crate arena;
extern crate fmt_macros;
self.err_span_char(self.last_pos, self.pos,
"illegal character in numeric character escape", c);
0
- }) as u32;
+ });
self.bump();
}
self.fatal_span_char(self.last_pos, self.pos,
"illegal character in unicode escape", c);
}
- }) as u32;
+ });
self.bump();
count += 1;
}
/// The specific types of unsupported syntax
#[derive(Copy, PartialEq, Eq, Hash)]
pub enum ObsoleteSyntax {
- Sized,
- ForSized,
- ClosureType,
ClosureKind,
EmptyIndex,
}
/// Reports an obsolete syntax non-fatal error.
fn obsolete(&mut self, sp: Span, kind: ObsoleteSyntax) {
let (kind_str, desc, error) = match kind {
- ObsoleteSyntax::ForSized => (
- "for Sized?",
- "no longer required. Traits (and their `Self` type) do not have the `Sized` bound \
- by default",
- true,
- ),
- ObsoleteSyntax::ClosureType => (
- "`|usize| -> bool` closure type",
- "use unboxed closures instead, no type annotation needed",
- true,
- ),
ObsoleteSyntax::ClosureKind => (
"`:`, `&mut:`, or `&:`",
"rely on inference instead",
true,
),
- ObsoleteSyntax::Sized => (
- "`Sized? T` for removing the `Sized` bound",
- "write `T: ?Sized` instead",
- true,
- ),
ObsoleteSyntax::EmptyIndex => (
"[]",
"write `[..]` instead",
pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
let lo = self.span.lo;
- let node = if self.eat_keyword_noexpect(keywords::Mod) {
- let span = self.last_span;
- self.span_warn(span, "deprecated syntax; use the `self` keyword now");
- ast::PathListMod { id: ast::DUMMY_NODE_ID }
- } else if self.eat_keyword(keywords::SelfValue) {
+ let node = if self.eat_keyword(keywords::SelfValue) {
ast::PathListMod { id: ast::DUMMY_NODE_ID }
} else {
let ident = self.parse_ident();
}
}
- /// Expect and consume a `|`. If `||` is seen, replace it with a single
- /// `|` and continue. If a `|` is not seen, signal an error.
- fn expect_or(&mut self) {
- self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
- match self.token {
- token::BinOp(token::Or) => self.bump(),
- token::OrOr => {
- let span = self.span;
- let lo = span.lo + BytePos(1);
- self.replace_token(token::BinOp(token::Or), lo, span.hi)
- }
- _ => {
- self.expect_one_of(&[], &[]);
- }
- }
- }
-
pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
match suffix {
None => {/* everything ok */}
}
}
- /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
- fn parse_seq_to_before_or<T, F>(&mut self,
- sep: &token::Token,
- mut f: F)
- -> Vec<T> where
- F: FnMut(&mut Parser) -> T,
- {
- let mut first = true;
- let mut vector = Vec::new();
- while self.token != token::BinOp(token::Or) &&
- self.token != token::OrOr {
- if first {
- first = false
- } else {
- self.expect(sep)
- }
-
- vector.push(f(self))
- }
- vector
- }
-
/// Expect and consume a GT. if a >> is seen, replace it
/// with a single > and continue. If a GT is not seen,
/// signal an error.
} else {
// Avoid token copies with `replace`.
let buffer_start = self.buffer_start as usize;
- let next_index = (buffer_start + 1) & 3 as usize;
+ let next_index = (buffer_start + 1) & 3;
self.buffer_start = next_index as isize;
let placeholder = TokenAndSpan {
self.check_keyword(keywords::Extern)
}
- /// Is the current token one of the keywords that signals a closure type?
- pub fn token_is_closure_keyword(&mut self) -> bool {
- self.check_keyword(keywords::Unsafe)
- }
-
pub fn get_lifetime(&mut self) -> ast::Ident {
match self.token {
token::Lifetime(ref ident) => *ident,
let lifetime_defs = self.parse_late_bound_lifetime_defs();
// examine next token to decide to do
- if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() {
- self.parse_ty_bare_fn_or_ty_closure(lifetime_defs)
- } else if self.check(&token::ModSep) ||
- self.token.is_ident() ||
- self.token.is_path()
- {
+ if self.token_is_bare_fn_keyword() {
+ self.parse_ty_bare_fn(lifetime_defs)
+ } else {
let hi = self.span.hi;
let trait_ref = self.parse_trait_ref();
let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
.chain(other_bounds.into_vec().into_iter())
.collect();
ast::TyPolyTraitRef(all_bounds)
- } else {
- self.parse_ty_closure(lifetime_defs)
}
}
};
self.expect_keyword(keywords::Fn);
- let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
let (inputs, variadic) = self.parse_fn_args(false, true);
let ret_ty = self.parse_ret_ty();
let decl = P(FnDecl {
self.obsolete(span, ObsoleteSyntax::ClosureKind);
}
- pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
- // Both bare fns and closures can begin with stuff like unsafe
- // and extern. So we just scan ahead a few tokens to see if we see
- // a `fn`.
- //
- // Closure: [unsafe] <'lt> |S| [:Bounds] -> T
- // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T
-
- if self.check_keyword(keywords::Fn) {
- self.parse_ty_bare_fn(lifetime_defs)
- } else if self.check_keyword(keywords::Extern) {
- self.parse_ty_bare_fn(lifetime_defs)
- } else if self.check_keyword(keywords::Unsafe) {
- if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) ||
- t.is_keyword(keywords::Extern)) {
- self.parse_ty_bare_fn(lifetime_defs)
- } else {
- self.parse_ty_closure(lifetime_defs)
- }
- } else {
- self.parse_ty_closure(lifetime_defs)
- }
- }
-
- /// Parse a TyClosure type
- pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
- /*
-
- [unsafe] <'lt> |S| [:Bounds] -> T
- ^~~~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
- | | | | |
- | | | | Return type
- | | | Closure bounds
- | | Argument types
- | Deprecated lifetime defs
- |
- Function Style
-
- */
-
- let ty_closure_span = self.last_span;
-
- // To be helpful, parse the closure type as ever
- let _ = self.parse_unsafety();
-
- let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
-
- if !self.eat(&token::OrOr) {
- self.expect_or();
-
- let _ = self.parse_seq_to_before_or(
- &token::Comma,
- |p| p.parse_arg_general(false));
- self.expect_or();
- }
-
- let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
-
- let _ = self.parse_ret_ty();
-
- self.obsolete(ty_closure_span, ObsoleteSyntax::ClosureType);
-
- TyInfer
- }
-
pub fn parse_unsafety(&mut self) -> Unsafety {
if self.eat_keyword(keywords::Unsafe) {
return Unsafety::Unsafe;
}
}
- /// Parses `[ 'for' '<' lifetime_defs '>' ]'
- fn parse_legacy_lifetime_defs(&mut self,
- lifetime_defs: Vec<ast::LifetimeDef>)
- -> Vec<ast::LifetimeDef>
- {
- if self.token == token::Lt {
- self.bump();
- if lifetime_defs.is_empty() {
- self.warn("deprecated syntax; use the `for` keyword now \
- (e.g. change `fn<'a>` to `for<'a> fn`)");
- let lifetime_defs = self.parse_lifetime_defs();
- self.expect_gt();
- lifetime_defs
- } else {
- self.fatal("cannot use new `for` keyword and older syntax together");
- }
- } else {
- lifetime_defs
- }
- }
-
/// Parse the items in a trait declaration
pub fn parse_trait_items(&mut self) -> Vec<P<TraitItem>> {
self.parse_unspanned_seq(
if self.eat(&token::Not) {
NoReturn(self.span)
} else {
- let t = self.parse_ty();
-
- // We used to allow `fn foo() -> &T + U`, but don't
- // anymore. If we see it, report a useful error. This
- // only makes sense because `parse_ret_ty` is only
- // used in fn *declarations*, not fn types or where
- // clauses (i.e., not when parsing something like
- // `FnMut() -> T + Send`, where the `+` is legal).
- if self.token == token::BinOp(token::Plus) {
- self.warn("deprecated syntax: `()` are required, see RFC 438 for details");
- }
-
- Return(t)
+ Return(self.parse_ty())
}
} else {
let pos = self.span.lo;
self.parse_borrowed_pointee()
} else if self.check_keyword(keywords::For) {
self.parse_for_in_type()
- } else if self.token_is_bare_fn_keyword() ||
- self.token_is_closure_keyword() {
- // BARE FUNCTION OR CLOSURE
- self.parse_ty_bare_fn_or_ty_closure(Vec::new())
- } else if self.check(&token::BinOp(token::Or)) ||
- self.token == token::OrOr ||
- (self.token == token::Lt &&
- self.look_ahead(1, |t| {
- *t == token::Gt || t.is_lifetime()
- })) {
- // CLOSURE
- self.parse_ty_closure(Vec::new())
+ } else if self.token_is_bare_fn_keyword() {
+ // BARE FUNCTION
+ self.parse_ty_bare_fn(Vec::new())
} else if self.eat_keyword_noexpect(keywords::Typeof) {
// TYPEOF
// In order to not be ambiguous, the type must be surrounded by parens.
return OwnedSlice::from_vec(result);
}
- fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
- let segment = ast::PathSegment {
- identifier: ident,
- parameters: ast::PathParameters::none()
- };
- let path = ast::Path {
- span: span,
- global: false,
- segments: vec![segment],
- };
- ast::TraitRef {
- path: path,
- ref_id: ast::DUMMY_NODE_ID,
- }
- }
-
- /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
+ /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
fn parse_ty_param(&mut self) -> TyParam {
- // This is a bit hacky. Currently we are only interested in a single
- // unbound, and it may only be `Sized`. To avoid backtracking and other
- // complications, we parse an ident, then check for `?`. If we find it,
- // we use the ident as the unbound, otherwise, we use it as the name of
- // type param. Even worse, we need to check for `?` before or after the
- // bound.
- let mut span = self.span;
- let mut ident = self.parse_ident();
- let mut unbound = None;
- if self.eat(&token::Question) {
- let tref = Parser::trait_ref_from_ident(ident, span);
- unbound = Some(tref);
- span = self.span;
- ident = self.parse_ident();
- self.obsolete(span, ObsoleteSyntax::Sized);
- }
+ let span = self.span;
+ let ident = self.parse_ident();
- let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
- if let Some(unbound) = unbound {
- let mut bounds_as_vec = bounds.into_vec();
- bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
- trait_ref: unbound,
- span: span },
- TraitBoundModifier::Maybe));
- bounds = OwnedSlice::from_vec(bounds_as_vec);
- };
+ let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
let default = if self.check(&token::Eq) {
self.bump();
Some(self.parse_ty_sum())
- }
- else { None };
+ } else {
+ None
+ };
TyParam {
ident: ident,
let ident = self.parse_ident();
let mut tps = self.parse_generics();
- // This is not very accurate, but since unbound only exists to catch
- // obsolete syntax, the span is unlikely to ever be used.
- let unbound_span = self.span;
- let unbound = self.parse_for_sized();
// Parse supertrait bounds.
- let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
-
- if let Some(unbound) = unbound {
- let mut bounds_as_vec = bounds.into_vec();
- bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
- trait_ref: unbound,
- span: unbound_span },
- TraitBoundModifier::Maybe));
- bounds = OwnedSlice::from_vec(bounds_as_vec);
- };
+ let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
self.parse_where_clause(&mut tps);
else { Inherited }
}
- fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
- // FIXME, this should really use TraitBoundModifier, but it will get
- // re-jigged shortly in any case, so leaving the hacky version for now.
- if self.eat_keyword(keywords::For) {
- let span = self.span;
-
- let mut ate_question = false;
- if self.eat(&token::Question) {
- ate_question = true;
- }
- let ident = self.parse_ident();
- if self.eat(&token::Question) {
- if ate_question {
- self.span_err(span,
- "unexpected `?`");
- }
- ate_question = true;
- }
- if !ate_question {
- self.span_err(span,
- "expected `?Sized` after `for` in trait item");
- return None;
- }
- let _tref = Parser::trait_ref_from_ident(ident, span);
-
- self.obsolete(span, ObsoleteSyntax::ForSized);
-
- None
- } else {
- None
- }
- }
-
/// Given a termination token, parse all of the items in a module
fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> Mod {
let mut items = vec![];
outer_attrs: &[ast::Attribute],
id_sp: Span)
-> (ast::Item_, Vec<ast::Attribute> ) {
- let mut prefix = PathBuf::new(&self.sess.span_diagnostic.cm
- .span_to_filename(self.span));
+ let mut prefix = PathBuf::from(&self.sess.span_diagnostic.cm
+ .span_to_filename(self.span));
prefix.pop();
let mut dir_path = prefix;
for part in &self.mod_path_stack {
opt_explicit_self: Option<&ast::ExplicitSelf_>)
-> io::Result<()> {
try!(self.ibox(indent_unit));
+ if generics.lifetimes.len() > 0 || generics.ty_params.len() > 0 {
+ try!(word(&mut self.s, "for"));
+ try!(self.print_generics(generics));
+ }
+ let generics = ast::Generics {
+ lifetimes: Vec::new(),
+ ty_params: OwnedSlice::empty(),
+ where_clause: ast::WhereClause {
+ id: ast::DUMMY_NODE_ID,
+ predicates: Vec::new(),
+ },
+ };
try!(self.print_fn(decl, unsafety, abi, name,
- generics, opt_explicit_self,
+ &generics, opt_explicit_self,
ast::Inherited));
self.end()
}
ast::LitBinary(ref v) => {
let mut escaped: String = String::new();
for &ch in &**v {
- escaped.extend(ascii::escape_default(ch as u8)
+ escaped.extend(ascii::escape_default(ch)
.map(|c| c as char));
}
word(&mut self.s, &format!("b\"{}\"", escaped))
//! # Examples
//!
//! ```no_run
+//! # #![feature(rustc_private)]
//! extern crate term;
//!
//! use std::io::prelude::*;
#![feature(std_misc)]
#![feature(str_char)]
#![feature(path_ext)]
+#![feature(convert)]
#![cfg_attr(windows, feature(libc))]
#[macro_use] extern crate log;
/// opened.
pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> {
TerminfoTerminal::new(WriterWrapper {
- wrapped: box std::io::stdout() as Box<Write + Send>,
+ wrapped: box std::io::stdout(),
})
}
/// opened.
pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> {
let ti = TerminfoTerminal::new(WriterWrapper {
- wrapped: box std::io::stdout() as Box<Write + Send>,
+ wrapped: box std::io::stdout(),
});
match ti {
Some(t) => Some(t),
None => {
WinConsole::new(WriterWrapper {
- wrapped: box std::io::stdout() as Box<Write + Send>,
+ wrapped: box std::io::stdout(),
})
}
}
/// opened.
pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> {
TerminfoTerminal::new(WriterWrapper {
- wrapped: box std::io::stderr() as Box<Write + Send>,
+ wrapped: box std::io::stderr(),
})
}
/// opened.
pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> {
let ti = TerminfoTerminal::new(WriterWrapper {
- wrapped: box std::io::stderr() as Box<Write + Send>,
+ wrapped: box std::io::stderr(),
});
match ti {
Some(t) => Some(t),
None => {
WinConsole::new(WriterWrapper {
- wrapped: box std::io::stderr() as Box<Write + Send>,
+ wrapped: box std::io::stderr(),
})
}
}
out: out,
ti: msys_terminfo(),
num_colors: 8,
- } as Box<Terminal<T>+Send>)
+ })
},
_ => {
debug!("error finding terminfo entry: {:?}", err);
return Some(box TerminfoTerminal {out: out,
ti: inf,
- num_colors: nc} as Box<Terminal<T>+Send>);
+ num_colors: nc});
}
fn dim_if_necessary(&self, color: color::Color) -> color::Color {
let magic = try!(read_le_u16(file));
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x}, found {:x}",
- 0x011A as usize, magic as usize));
+ 0x011A_usize, magic as usize));
}
let names_bytes = try!(read_le_u16(file)) as int;
// Find search directory
match env::var_os("TERMINFO") {
- Some(dir) => dirs_to_search.push(PathBuf::new(&dir)),
+ Some(dir) => dirs_to_search.push(PathBuf::from(dir)),
None => {
if homedir.is_some() {
// ncurses compatibility;
match env::var("TERMINFO_DIRS") {
Ok(dirs) => for i in dirs.split(':') {
if i == "" {
- dirs_to_search.push(PathBuf::new("/usr/share/terminfo"));
+ dirs_to_search.push(PathBuf::from("/usr/share/terminfo"));
} else {
- dirs_to_search.push(PathBuf::new(i));
+ dirs_to_search.push(PathBuf::from(i));
}
},
// Found nothing in TERMINFO_DIRS, use the default paths:
// ~/.terminfo, ncurses will search /etc/terminfo, then
// /lib/terminfo, and eventually /usr/share/terminfo.
Err(..) => {
- dirs_to_search.push(PathBuf::new("/etc/terminfo"));
- dirs_to_search.push(PathBuf::new("/lib/terminfo"));
- dirs_to_search.push(PathBuf::new("/usr/share/terminfo"));
+ dirs_to_search.push(PathBuf::from("/etc/terminfo"));
+ dirs_to_search.push(PathBuf::from("/lib/terminfo"));
+ dirs_to_search.push(PathBuf::from("/usr/share/terminfo"));
}
}
}
}
Some(box WinConsole { buf: out,
def_foreground: fg, def_background: bg,
- foreground: fg, background: bg } as Box<Terminal<T>+Send>)
+ foreground: fg, background: bg })
}
}
#![feature(libc)]
#![feature(set_stdio)]
#![feature(os)]
+#![feature(convert)]
+#![cfg_attr(test, feature(old_io))]
extern crate getopts;
extern crate serialize;
let run_ignored = matches.opt_present("ignored");
let logfile = matches.opt_str("logfile");
- let logfile = logfile.map(|s| PathBuf::new(&s));
+ let logfile = logfile.map(|s| PathBuf::from(&s));
let run_benchmarks = matches.opt_present("bench");
let run_tests = ! run_benchmarks ||
match tests.iter().max_by(|t|len_if_padded(*t)) {
Some(t) => {
let n = t.desc.name.as_slice();
- st.max_name_len = n.as_slice().len();
+ st.max_name_len = n.len();
},
None => {}
}
let MetricMap(ref mm) = *self;
let v : Vec<String> = mm.iter()
.map(|(k,v)| format!("{}: {} (+/- {})", *k,
- v.value as f64, v.noise as f64))
+ v.value, v.noise))
.collect();
v.connect(", ")
}
/// In both of these examples, 'ß' takes two bytes to encode.
///
/// ```
+ /// # #![feature(unicode)]
/// let mut b = [0; 2];
///
/// let result = 'ß'.encode_utf8(&mut b);
/// A buffer that's too small:
///
/// ```
+ /// # #![feature(unicode)]
/// let mut b = [0; 1];
///
/// let result = 'ß'.encode_utf8(&mut b);
/// In both of these examples, 'ß' takes one `u16` to encode.
///
/// ```
+ /// # #![feature(unicode)]
/// let mut b = [0; 1];
///
/// let result = 'ß'.encode_utf16(&mut b);
/// A buffer that's too small:
///
/// ```
+ /// # #![feature(unicode)]
/// let mut b = [0; 0];
///
/// let result = 'ß'.encode_utf8(&mut b);
/// In both of these examples, 'ß' takes two bytes to encode.
///
/// ```
+ /// # #![feature(unicode)]
/// let mut b = [0; 2];
///
/// let result = 'ß'.encode_utf8(&mut b);
/// A buffer that's too small:
///
/// ```
+ /// # #![feature(unicode)]
/// let mut b = [0; 1];
///
/// let result = 'ß'.encode_utf8(&mut b);
/// In both of these examples, 'ß' takes one `u16` to encode.
///
/// ```
+ /// # #![feature(unicode)]
/// let mut b = [0; 1];
///
/// let result = 'ß'.encode_utf16(&mut b);
/// A buffer that's too small:
///
/// ```
+ /// # #![feature(unicode)]
/// let mut b = [0; 0];
///
/// let result = 'ß'.encode_utf8(&mut b);
#![feature(no_std)]
#![no_std]
#![feature(core)]
+#![doc(test(no_crate_inject))]
extern crate core;
/// # Examples
///
/// ```
+/// # #![feature(unicode)]
+/// extern crate unicode;
+///
/// use unicode::str::Utf16Item::{ScalarValue, LoneSurrogate};
///
-/// // 𝄞mus<invalid>ic<invalid>
-/// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
-/// 0x0073, 0xDD1E, 0x0069, 0x0063,
-/// 0xD834];
+/// fn main() {
+/// // 𝄞mus<invalid>ic<invalid>
+/// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
+/// 0x0073, 0xDD1E, 0x0069, 0x0063,
+/// 0xD834];
///
-/// assert_eq!(unicode::str::utf16_items(&v).collect::<Vec<_>>(),
-/// vec![ScalarValue('𝄞'),
-/// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
-/// LoneSurrogate(0xDD1E),
-/// ScalarValue('i'), ScalarValue('c'),
-/// LoneSurrogate(0xD834)]);
+/// assert_eq!(unicode::str::utf16_items(&v).collect::<Vec<_>>(),
+/// vec![ScalarValue('𝄞'),
+/// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
+/// LoneSurrogate(0xDD1E),
+/// ScalarValue('i'), ScalarValue('c'),
+/// LoneSurrogate(0xD834)]);
+/// }
/// ```
pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> {
Utf16Items { iter : v.iter() }
// always include the introduction
top_items.push(BookItem {
title: "Introduction".to_string(),
- path: PathBuf::new("README.md"),
- path_to_root: PathBuf::new("."),
+ path: PathBuf::from("README.md"),
+ path_to_root: PathBuf::from("."),
children: vec!(),
});
errors.push(format!("paths in SUMMARY.md must be relative, \
but path '{}' for section '{}' is not.",
given_path, title));
- PathBuf::new("")
+ PathBuf::new()
}
};
- let path_to_root = PathBuf::new(&iter::repeat("../")
+ let path_to_root = PathBuf::from(&iter::repeat("../")
.take(path_from_root.components().count() - 1)
.collect::<String>());
let item = BookItem {
if env::args().len() < 3 {
src = env::current_dir().unwrap().clone();
} else {
- src = PathBuf::new(&env::args().nth(2).unwrap());
+ src = PathBuf::from(&env::args().nth(2).unwrap());
}
// preprocess the markdown, rerouting markdown references to html references
let mut markdown_data = String::new();
if env::args().len() < 3 {
src = cwd.clone();
} else {
- src = PathBuf::new(&env::args().nth(2).unwrap());
+ src = PathBuf::from(&env::args().nth(2).unwrap());
}
if env::args().len() < 4 {
tgt = cwd.join("_book");
} else {
- tgt = PathBuf::new(&env::args().nth(3).unwrap());
+ tgt = PathBuf::from(&env::args().nth(3).unwrap());
}
try!(fs::create_dir(&tgt));
pub type CommandResult<T> = Result<T, CommandError>;
pub fn err(s: &str) -> CliError {
+ #[derive(Debug)]
struct E(String);
impl Error for E {
#![feature(rustdoc)]
#![feature(rustc_private)]
#![feature(path_relative_from)]
+#![feature(convert)]
extern crate rustdoc;
extern crate rustc_back;
/// Create a Subcommand object based on its name.
pub fn parse_name(name: &str) -> Option<Box<Subcommand>> {
- for parser in [
- help::parse_cmd as fn(&str) -> Option<Box<Subcommand>>,
- build::parse_cmd as fn(&str) -> Option<Box<Subcommand>>,
- serve::parse_cmd as fn(&str) -> Option<Box<Subcommand>>,
- test::parse_cmd as fn(&str) -> Option<Box<Subcommand>>].iter() {
+ let cmds: [fn(&str) -> Option<Box<Subcommand>>; 4] = [help::parse_cmd,
+ build::parse_cmd,
+ serve::parse_cmd,
+ test::parse_cmd];
+ for parser in cmds.iter() {
let parsed = (*parser)(name);
if parsed.is_some() { return parsed }
}
S 2015-03-17 c64d671
- bitrig-x86_64 4b2f11a96b1b5b3782d74bda707aca33bc179880
+ bitrig-x86_64 41de2c7a69a1ac648d3fa3b65e96a29bdc122163
freebsd-x86_64 14ced24e1339a4dd8baa9db69995daa52a948d54
linux-i386 200450ad3cc56bc715ca105b9acae35204bf7351
linux-x86_64 a54f50fee722ba6bc7281dec3e4d5121af7c15e3
// except according to those terms.
#![crate_name="anonexternmod"]
+#![feature(libc)]
extern crate libc;
// Helper definition for test/run-pass/check-static-recursion-foreign.rs.
+#![feature(libc)]
+
#[crate_id = "check_static_recursion_foreign_helper"]
#[crate_type = "lib"]
#![crate_name="externcallback"]
#![crate_type = "lib"]
+#![feature(libc)]
extern crate libc;
// except according to those terms.
#![crate_name="foreign_lib"]
+#![feature(libc)]
pub mod rustrt {
extern crate libc;
}
pub fn foo() {
- let a = &1 as &inner::Trait;
+ let a = &1i as &inner::Trait;
a.f();
}
// the unused ty param is necessary so this gets monomorphized
pub fn request<T>(req: &header_map) {
- let data = req["METHOD".to_string()].clone();
+ let data = req[&"METHOD".to_string()].clone();
let _x = data.borrow().clone()[0].clone();
}
#![crate_name="socketlib"]
#![crate_type = "lib"]
+#![feature(libc)]
pub mod socket {
extern crate libc;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
pub mod testtypes {
use std::any::TypeId;
// ignore-stage1
// force-host
-#![feature(plugin_registrar, quote)]
+#![feature(plugin_registrar, quote, rustc_private)]
#![crate_type = "dylib"]
extern crate syntax;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
use std::marker::MarkerTrait;
pub trait Foo : MarkerTrait {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(libc)]
+
extern crate libc;
extern "C" {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc, old_path)]
+
use std::dynamic_lib::DynamicLibrary;
#[no_mangle]
// force-host
-#![feature(plugin_registrar)]
+#![feature(plugin_registrar, rustc_private)]
#![feature(box_syntax)]
extern crate syntax;
// force-host
#![feature(plugin_registrar)]
-#![feature(box_syntax)]
+#![feature(box_syntax, rustc_private)]
extern crate syntax;
// force-host
#![feature(plugin_registrar)]
-#![feature(box_syntax)]
+#![feature(box_syntax, rustc_private)]
extern crate syntax;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(rustc_private)]
+
#[macro_use] extern crate log;
pub fn foo<T>() {
// force-host
-#![feature(plugin_registrar)]
+#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
// force-host
#![feature(plugin_registrar, quote)]
-#![feature(box_syntax)]
+#![feature(box_syntax, rustc_private)]
extern crate syntax;
extern crate rustc;
// force-host
#![feature(plugin_registrar)]
-#![feature(box_syntax)]
+#![feature(box_syntax, rustc_private)]
extern crate syntax;
extern crate rustc;
// force-host
#![feature(plugin_registrar)]
-#![feature(box_syntax)]
+#![feature(box_syntax, rustc_private)]
extern crate rustc;
// force-host
-#![feature(plugin_registrar)]
+#![feature(plugin_registrar, rustc_private)]
#![deny(plugin_as_library)] // should have no effect in a plugin crate
extern crate macro_crate_test;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
trait Foo : ::std::marker::MarkerTrait {}
// force-host
#![crate_type="dylib"]
-#![feature(plugin_registrar, quote)]
+#![feature(plugin_registrar, quote, rustc_private)]
extern crate syntax;
extern crate rustc;
let mac_expr = match TokenTree::parse(cx, &mbe_matcher[..], args) {
Success(map) => {
- match (&*map[str_to_ident("matched")], &*map[str_to_ident("pat")]) {
+ match (&*map[&str_to_ident("matched")], &*map[&str_to_ident("pat")]) {
(&MatchedNonterminal(NtExpr(ref matched_expr)),
&MatchedSeq(ref pats, seq_sp)) => {
let pats: Vec<P<Pat>> = pats.iter().map(|pat_nt|
// no-prefer-dynamic
#![crate_type = "rlib"]
-#![feature(plugin_registrar)]
+#![feature(plugin_registrar, rustc_private)]
extern crate rustc;
// force-host
#![crate_type="dylib"]
-#![feature(plugin_registrar)]
+#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
//! (#14132).
#![crate_name = "a"]
+#![feature(core)]
use std::marker::MarkerTrait;
// force-host
#![crate_type = "dylib"]
-#![feature(plugin_registrar, quote)]
+#![feature(plugin_registrar, quote, rustc_private)]
extern crate "syntax_extension_with_dll_deps_1" as other;
extern crate syntax;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
pub trait Foo : ::std::marker::MarkerTrait {
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(optin_builtin_traits)]
+#![feature(optin_builtin_traits, core)]
#![crate_type = "rlib"]
use std::marker::MarkerTrait;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
use std::any::TypeId;
pub struct A;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
use std::any::TypeId;
pub struct A;
// This aux-file will require the eh_personality function to be codegen'd, but
// it hasn't been defined just yet. Make sure we don't explode.
-#![feature(no_std)]
+#![feature(no_std, core)]
#![no_std]
#![crate_type = "rlib"]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, std_misc, rand)]
use std::collections::{BTreeMap, HashMap, HashSet};
use std::env;
// ignore-pretty very bad with line comments
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, rand, std_misc, collections)]
extern crate collections;
extern crate rand;
// ignore-lexer-test FIXME #15679
// Microbenchmarks for various functions in std and extra
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, rand, old_io, old_path, std_misc, collections)]
use std::old_io::*;
use std::old_path::{Path, GenericPath};
// different scalability characteristics compared to the select
// version.
+#![feature(std_misc)]
+
use std::sync::mpsc::{channel, Sender, Receiver};
use std::env;
use std::thread;
//
// I *think* it's the same, more or less.
+#![feature(std_misc)]
+
use std::sync::mpsc::{channel, Sender, Receiver};
use std::env;
use std::thread;
// no-pretty-expanded FIXME #15189
// ignore-lexer-test FIXME #15679
+#![feature(std_misc)]
+
use std::env;
use std::sync::{Arc, Future, Mutex, Condvar};
use std::time::Duration;
// See https://github.com/nsf/pnoise for timings and alternative implementations.
// ignore-lexer-test FIXME #15679
+#![feature(rand, core)]
+
use std::f32::consts::PI;
use std::num::Float;
use std::rand::{Rng, StdRng};
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
+#![feature(rustc_private, core)]
+
extern crate arena;
use std::iter::range_step;
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
+#![feature(core)]
+
use std::{cmp, iter, mem};
use std::thread;
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
+#![feature(core, old_io, io, core)]
+
use std::cmp::min;
use std::old_io::*;
use std::iter::repeat;
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
+#![feature(old_io, old_path, io, core)]
+
use std::cmp::min;
use std::old_io::*;
use std::old_io;
// multi tasking k-nucleotide
-#![feature(box_syntax)]
+#![feature(box_syntax, std_misc, old_io, collections, os)]
use std::ascii::{AsciiExt, OwnedAsciiExt};
use std::cmp::Ordering::{self, Less, Greater, Equal};
// ignore-android see #10393 #13206
-#![feature(box_syntax)]
+#![feature(box_syntax, std_misc, collections)]
use std::ascii::OwnedAsciiExt;
use std::env;
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
-#![feature(simd)]
+#![feature(simd, old_io, core, io)]
// ignore-pretty very bad with line comments
// no-pretty-expanded FIXME #15189
+#![feature(core)]
+
use std::iter::repeat;
use std::sync::Arc;
use std::sync::mpsc::channel;
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
+#![feature(core)]
+
use std::num::Float;
const PI: f64 = 3.141592653589793;
*/
+#![feature(std_misc, rustc_private)]
+
extern crate getopts;
use std::sync::mpsc::{channel, Sender};
// ignore-android see #10393 #13206
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, libc, old_io, collections, io, core)]
extern crate libc;
use std::old_io::stdio::{stdin_raw, stdout_raw};
use std::old_io::*;
-use std::ptr::{copy_memory, Unique};
+use std::ptr::{copy, Unique};
use std::thread;
struct Tables {
let mut i = LINE_LEN;
while i < len {
unsafe {
- copy_memory(seq.as_mut_ptr().offset((i - off + 1) as int),
- seq.as_ptr().offset((i - off) as int), off);
+ copy(seq.as_mut_ptr().offset((i - off + 1) as int),
+ seq.as_ptr().offset((i - off) as int), off);
*seq.get_unchecked_mut(i - off) = b'\n';
}
i += LINE_LEN + 1;
// no-pretty-expanded FIXME #15189
#![allow(non_snake_case)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, core, os)]
use std::iter::{repeat, AdditiveIterator};
use std::thread;
// Microbenchmark for the smallintmap library
+#![feature(collections, std_misc)]
+
use std::collections::VecMap;
use std::env;
use std::time::Duration;
// ignore-pretty very bad with line comments
-#![feature(box_syntax)]
+#![feature(box_syntax, core)]
#![allow(non_snake_case)]
use std::io::prelude::*;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unsafe_destructor, box_syntax)]
+#![feature(unsafe_destructor, box_syntax, std_misc, collections)]
use std::env;
use std::thread;
}
impl Fn<(isize,)> for SFn {
- type Output = isize;
-
extern "rust-call" fn call(&self, (z,): (isize,)) -> isize {
self.x * self.y * z
}
}
+impl FnMut<(isize,)> for SFn {
+ extern "rust-call" fn call_mut(&mut self, args: (isize,)) -> isize { self.call(args) }
+}
+
+impl FnOnce<(isize,)> for SFn {
+ type Output = isize;
+ extern "rust-call" fn call_once(self, args: (isize,)) -> isize { self.call(args) }
+}
+
struct SFnMut {
x: isize,
y: isize,
}
impl FnMut<(isize,)> for SFnMut {
- type Output = isize;
-
extern "rust-call" fn call_mut(&mut self, (z,): (isize,)) -> isize {
self.x * self.y * z
}
}
+impl FnOnce<(isize,)> for SFnMut {
+ type Output = isize;
+ extern "rust-call" fn call_once(mut self, args: (isize,)) -> isize { self.call_mut(args) }
+}
+
struct SFnOnce {
x: String,
}
+++ /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(box_syntax)]
-
-use std::ops::Index;
-
-struct MyVec<T> {
- data: Vec<T>,
-}
-
-impl<T> Index<usize> for MyVec<T> {
- type Output = T;
-
- fn index(&self, &i: &usize) -> &T {
- &self.data[i]
- }
-}
-
-fn main() {
- let v = MyVec::<Box<_>> { data: vec!(box 1, box 2, box 3) };
- let good = &v[0]; // Shouldn't fail here
- let bad = v[0];
- //~^ ERROR cannot move out of indexed content
-}
impl<T> Index<usize> for MyVec<T> {
type Output = T;
- fn index(&self, _: &usize) -> &T {
+ fn index(&self, _: usize) -> &T {
&self.x
}
}
y: isize,
}
+#[cfg(stage0)]
impl Index<String> for Foo {
type Output = isize;
}
}
-impl IndexMut<String> for Foo {
- fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize {
+impl<'a> Index<&'a String> for Foo {
+ type Output = isize;
+
+ fn index(&self, z: &String) -> &isize {
+ if *z == "x" {
+ &self.x
+ } else {
+ &self.y
+ }
+ }
+}
+
+impl<'a> IndexMut<&'a String> for Foo {
+ fn index_mut(&mut self, z: &String) -> &mut isize {
if *z == "x" {
&mut self.x
} else {
}
fn test1(mut f: Box<Foo>, s: String) {
- let _p = &mut f[s];
- let _q = &f[s]; //~ ERROR cannot borrow
+ let _p = &mut f[&s];
+ let _q = &f[&s]; //~ ERROR cannot borrow
}
fn test2(mut f: Box<Foo>, s: String) {
- let _p = &mut f[s];
- let _q = &mut f[s]; //~ ERROR cannot borrow
+ let _p = &mut f[&s];
+ let _q = &mut f[&s]; //~ ERROR cannot borrow
}
struct Bar {
}
fn test3(mut f: Box<Bar>, s: String) {
- let _p = &mut f.foo[s];
- let _q = &mut f.foo[s]; //~ ERROR cannot borrow
+ let _p = &mut f.foo[&s];
+ let _q = &mut f.foo[&s]; //~ ERROR cannot borrow
}
fn test4(mut f: Box<Bar>, s: String) {
- let _p = &f.foo[s];
- let _q = &f.foo[s];
+ let _p = &f.foo[&s];
+ let _q = &f.foo[&s];
}
fn test5(mut f: Box<Bar>, s: String) {
- let _p = &f.foo[s];
- let _q = &mut f.foo[s]; //~ ERROR cannot borrow
+ let _p = &f.foo[&s];
+ let _q = &mut f.foo[&s]; //~ ERROR cannot borrow
}
fn test6(mut f: Box<Bar>, g: Foo, s: String) {
- let _p = &f.foo[s];
+ let _p = &f.foo[&s];
f.foo = g; //~ ERROR cannot assign
}
fn test7(mut f: Box<Bar>, g: Bar, s: String) {
- let _p = &f.foo[s];
+ let _p = &f.foo[&s];
*f = g; //~ ERROR cannot assign
}
fn test8(mut f: Box<Bar>, g: Foo, s: String) {
- let _p = &mut f.foo[s];
+ let _p = &mut f.foo[&s];
f.foo = g; //~ ERROR cannot assign
}
fn test9(mut f: Box<Bar>, g: Bar, s: String) {
- let _p = &mut f.foo[s];
+ let _p = &mut f.foo[&s];
*f = g; //~ ERROR cannot assign
}
--- /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(box_syntax)]
+
+use std::ops::Index;
+
+struct MyVec<T> {
+ data: Vec<T>,
+}
+
+impl<T> Index<usize> for MyVec<T> {
+ type Output = T;
+
+ fn index(&self, i: usize) -> &T {
+ &self.data[i]
+ }
+}
+
+fn main() {
+ let v = MyVec::<Box<_>> { data: vec!(box 1, box 2, box 3) };
+ let good = &v[0]; // Shouldn't fail here
+ let bad = v[0];
+ //~^ ERROR cannot move out of indexed content
+}
--- /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::ops::{Index, IndexMut};
+
+struct Foo {
+ x: isize,
+ y: isize,
+}
+
+impl Index<String> for Foo {
+ type Output = isize;
+
+ fn index(&self, z: String) -> &isize {
+ if z == "x" {
+ &self.x
+ } else {
+ &self.y
+ }
+ }
+}
+
+impl IndexMut<String> for Foo {
+ fn index_mut(&mut self, z: String) -> &mut isize {
+ if z == "x" {
+ &mut self.x
+ } else {
+ &mut self.y
+ }
+ }
+}
+
+struct Bar {
+ x: isize,
+}
+
+impl Index<isize> for Bar {
+ type Output = isize;
+
+ fn index<'a>(&'a self, z: isize) -> &'a isize {
+ &self.x
+ }
+}
+
+fn main() {
+ let mut f = Foo {
+ x: 1,
+ y: 2,
+ };
+ let mut s = "hello".to_string();
+ let rs = &mut s;
+
+ println!("{}", f[s]);
+ //~^ ERROR cannot move out of `s` because it is borrowed
+
+ f[s] = 10;
+ //~^ ERROR cannot move out of `s` because it is borrowed
+ //~| ERROR use of moved value: `s`
+
+ let s = Bar {
+ x: 1,
+ };
+ let i = 2;
+ let _j = &i;
+ println!("{}", s[i]); // no error, i is copy
+ println!("{}", s[i]);
+}
--- /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::ops::{Index, IndexMut};
+
+struct Foo {
+ x: isize,
+ y: isize,
+}
+
+impl<'a> Index<&'a String> for Foo {
+ type Output = isize;
+
+ fn index(&self, z: &String) -> &isize {
+ if *z == "x" {
+ &self.x
+ } else {
+ &self.y
+ }
+ }
+}
+
+impl<'a> IndexMut<&'a String> for Foo {
+ fn index_mut(&mut self, z: &String) -> &mut isize {
+ if *z == "x" {
+ &mut self.x
+ } else {
+ &mut self.y
+ }
+ }
+}
+
+struct Bar {
+ x: isize,
+}
+
+impl Index<isize> for Bar {
+ type Output = isize;
+
+ fn index<'a>(&'a self, z: isize) -> &'a isize {
+ &self.x
+ }
+}
+
+fn main() {
+ let mut f = Foo {
+ x: 1,
+ y: 2,
+ };
+ let mut s = "hello".to_string();
+ let rs = &mut s;
+ println!("{}", f[&s]);
+ //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable
+ f[&s] = 10;
+ //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable
+ let s = Bar {
+ x: 1,
+ };
+ s[2] = 20;
+ //~^ ERROR cannot assign to immutable indexed content
+}
+++ /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::ops::{Index, IndexMut};
-
-struct Foo {
- x: isize,
- y: isize,
-}
-
-impl Index<String> for Foo {
- type Output = isize;
-
- fn index<'a>(&'a self, z: &String) -> &'a isize {
- if *z == "x" {
- &self.x
- } else {
- &self.y
- }
- }
-}
-
-impl IndexMut<String> for Foo {
- fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize {
- if *z == "x" {
- &mut self.x
- } else {
- &mut self.y
- }
- }
-}
-
-struct Bar {
- x: isize,
-}
-
-impl Index<isize> for Bar {
- type Output = isize;
-
- fn index<'a>(&'a self, z: &isize) -> &'a isize {
- &self.x
- }
-}
-
-fn main() {
- let mut f = Foo {
- x: 1,
- y: 2,
- };
- let mut s = "hello".to_string();
- let rs = &mut s;
- println!("{}", f[s]);
- //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable
- f[s] = 10;
- //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable
- let s = Bar {
- x: 1,
- };
- s[2] = 20;
- //~^ ERROR cannot assign to immutable indexed content
-}
fn main() {
let x: Option<&[u8]> = Some("foo").map(std::mem::transmute);
- //~^ ERROR: is not implemented for the type
+ //~^ ERROR E0277
+ //~| ERROR E0277
}
impl MyTrait for .. {}
//~^ ERROR conflicting implementations for trait `MyTrait`
+trait MySafeTrait: MarkerTrait {}
+
+unsafe impl MySafeTrait for .. {}
+//~^ ERROR implementing the trait `MySafeTrait` is not unsafe
+
+unsafe trait MyUnsafeTrait: MarkerTrait {}
+
+impl MyUnsafeTrait for .. {}
+//~^ ERROR the trait `MyUnsafeTrait` requires an `unsafe impl` declaration
+
fn main() {}
+++ /dev/null
-// Copyright 2015 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.
-
-
-#[deriving(Clone)] //~ ERROR `deriving` has been renamed to `derive`
-struct Foo;
-
-fn main() {}
impl Index<usize> for S {
type Output = str;
- fn index<'a>(&'a self, _: &usize) -> &'a str {
+ fn index(&self, _: usize) -> &str {
"hello"
}
}
impl Index<usize> for T {
type Output = Debug + 'static;
- fn index<'a>(&'a self, idx: &usize) -> &'a (Debug + 'static) {
+ fn index<'a>(&'a self, idx: usize) -> &'a (Debug + 'static) {
static x: usize = 42;
&x
}
let _x: extern "C" fn() = f; // OK
is_fn(f);
//~^ ERROR the trait `core::ops::Fn<()>` is not implemented for the type `extern "C" fn()
- //~| ERROR the trait `core::ops::Fn<()>` is not implemented for the type `extern "C" fn()
+ //~| ERROR the trait `core::ops::FnOnce<()>` is not implemented for the type `extern "C" fn()
}
struct Foo;
impl Fn<()> for Foo {
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family of traits
- type Output = ();
-
- extern "rust-call" fn call(&self, args: ()) -> () {}
+ extern "rust-call" fn call(self, args: ()) -> () {}
}
struct Foo1;
-impl Fn() for Foo1 {
+impl FnOnce() for Foo1 {
//~^ ERROR associated type bindings are not allowed here
-
- extern "rust-call" fn call(&self, args: ()) -> () {}
+ extern "rust-call" fn call_once(self, args: ()) -> () {}
}
struct Bar;
impl FnMut<()> for Bar {
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family of traits
- type Output = ();
-
extern "rust-call" fn call_mut(&self, args: ()) -> () {}
}
struct Baz;
impl FnOnce<()> for Baz {
//~^ ERROR angle-bracket notation is not stable when used with the `Fn` family of traits
- type Output = ();
-
extern "rust-call" fn call_once(&self, args: ()) -> () {}
}
needs_fn(1);
//~^ ERROR `core::ops::Fn<(isize,)>`
- //~| ERROR `core::ops::Fn<(isize,)>`
+ //~| ERROR `core::ops::FnOnce<(isize,)>`
}
}
fn main() {
- apply(&3, takes_mut); //~ ERROR (values differ in mutability)
apply(&3, takes_imm);
+ apply(&3, takes_mut);
+ //~^ ERROR (values differ in mutability)
+ //~| ERROR (values differ in mutability)
apply(&mut 3, takes_mut);
- apply(&mut 3, takes_imm); //~ ERROR (values differ in mutability)
+ apply(&mut 3, takes_imm);
+ //~^ ERROR (values differ in mutability)
+ //~| ERROR (values differ in mutability)
}
+++ /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(unboxed_closures)]
-
-// Test that we suggest the correct parentheses
-
-trait Bar {
- fn dummy(&self) { }
-}
-
-struct Foo<'a> {
- a: &'a Bar+'a,
- //~^ ERROR E0178
- //~^^ HELP perhaps you meant `&'a (Bar + 'a)`?
-
- b: &'a mut Bar+'a,
- //~^ ERROR E0178
- //~^^ HELP perhaps you meant `&'a mut (Bar + 'a)`?
-
- c: Box<Bar+'a>, // OK, no paren needed in this context
-
- d: fn() -> Bar+'a,
- //~^ ERROR E0178
- //~^^ HELP perhaps you forgot parentheses
- //~^^^ WARN deprecated syntax
-}
-
-fn main() { }
// aux-build:internal_unstable.rs
// error-pattern:use of unstable library feature 'function'
// error-pattern:use of unstable library feature 'struct_field'
-// error-pattern:compilation successful
-#![feature(rustc_attrs)]
#[macro_use]
extern crate internal_unstable;
-#[rustc_error]
fn main() {
call_unstable_noallow!();
// aux-build:internal_unstable.rs
-#![feature(rustc_attrs)]
#![allow(dead_code)]
extern crate internal_unstable;
thread_local!(static FOO: () = ());
-thread_local!(static BAR: () = internal_unstable::unstable()); //~ WARN use of unstable
+thread_local!(static BAR: () = internal_unstable::unstable()); //~ ERROR use of unstable
-#[rustc_error]
-fn main() {} //~ ERROR
+fn main() {}
// aux-build:internal_unstable.rs
-#![feature(rustc_attrs, allow_internal_unstable)]
+#![feature(allow_internal_unstable)]
#[macro_use]
extern crate internal_unstable;
($e: expr, $f: expr) => {{
$e;
$f;
- internal_unstable::unstable(); //~ WARN use of unstable
+ internal_unstable::unstable(); //~ ERROR use of unstable
}}
}
}}
}
-#[rustc_error]
-fn main() { //~ ERROR
+fn main() {
// ok, the instability is contained.
call_unstable_allow!();
construct_unstable_allow!(0);
// bad.
- pass_through_allow!(internal_unstable::unstable()); //~ WARN use of unstable
+ pass_through_allow!(internal_unstable::unstable()); //~ ERROR use of unstable
- pass_through_noallow!(internal_unstable::unstable()); //~ WARN use of unstable
+ pass_through_noallow!(internal_unstable::unstable()); //~ ERROR use of unstable
- println!("{:?}", internal_unstable::unstable()); //~ WARN use of unstable
+ println!("{:?}", internal_unstable::unstable()); //~ ERROR use of unstable
- bar!(internal_unstable::unstable()); //~ WARN use of unstable
+ bar!(internal_unstable::unstable()); //~ ERROR use of unstable
}
//~| expected u8
//~| found array of 1 elements
- let local = [0];
+ let local: [u8; 1] = [0];
let _v = &local as *mut u8;
//~^ ERROR mismatched types
//~| expected `*mut u8`
- //~| found `&[_; 1]`
+ //~| found `&[u8; 1]`
//~| expected u8,
//~| found array of 1 elements
}
x: T
}
-impl<T: fmt::Debug> ops::Fn<(),> for Debuger<T> {
+impl<T: fmt::Debug> ops::FnOnce<(),> for Debuger<T> {
type Output = ();
-
- fn call(&self, _args: ()) {
-//~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn
+ fn call_once(self, _args: ()) {
+//~^ ERROR `call_once` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn
println!("{:?}", self.x);
}
}
}
static foo: *const Y::X = Y::foo(Y::x as *const Y::X);
-//~^ ERROR cannot refer to other statics by value
-//~| ERROR the trait `core::marker::Sync` is not implemented for the type
+//~^ ERROR the trait `core::marker::Sync` is not implemented for the type
//~| ERROR function calls in statics are limited to struct and enum constructors
fn main() {}
0.contains(bits);
//~^ ERROR overflow
- //~| ERROR overflow
- //~| ERROR overflow
- //~| ERROR mismatched types
}
struct Foo;
impl<'a, T> Fn<(&'a T,)> for Foo {
+ extern "rust-call" fn call(&self, (_,): (T,)) {}
+ //~^ ERROR: has an incompatible type for trait: expected &-ptr
+}
+
+impl<'a, T> FnMut<(&'a T,)> for Foo {
+ extern "rust-call" fn call_mut(&mut self, (_,): (T,)) {}
+ //~^ ERROR: has an incompatible type for trait: expected &-ptr
+}
+
+impl<'a, T> FnOnce<(&'a T,)> for Foo {
type Output = ();
- extern "rust-call" fn call(&self, (_,): (T,)) {}
+ extern "rust-call" fn call_once(self, (_,): (T,)) {}
//~^ ERROR: has an incompatible type for trait: expected &-ptr
}
+++ /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.
-
-trait Foo { fn foo(&self) {} }
-impl Foo for u8 {}
-
-fn main() {
- // FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
- let r: Box<Foo> = Box::new(5);
- let _m: Box<Foo> = r as Box<Foo>;
- //~^ ERROR `core::marker::Sized` is not implemented for the type `Foo`
-}
let a = &t as &Gettable<T>;
//~^ ERROR the trait `core::marker::Send` is not implemented
//~^^ ERROR the trait `core::marker::Copy` is not implemented
+ //~^^^ ERROR the parameter type `T` may not live long enough
}
fn g<T>(val: T) {
}
pub fn foo() {
- let a = &1 as &inner::Trait;
+ let a: &inner::Trait = &1_isize;
a.f();
}
#![feature(foo)] //~ ERROR unused or unknown feature
-extern crate lint_output_format; //~ WARNING: use of unstable library feature
+extern crate lint_output_format; //~ ERROR use of unstable library feature
use lint_output_format::{foo, bar};
fn main() {
let _x = foo(); //~ WARNING #[warn(deprecated)] on by default
- let _y = bar(); //~ WARNING: use of unstable library feature
+ let _y = bar(); //~ ERROR use of unstable library feature
}
pub fn foo() {
let x = Stable {
inherit: 1,
- override1: 2, //~ WARN use of unstable
+ override1: 2, //~ ERROR use of unstable
override2: 3,
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
};
let _ = x.inherit;
- let _ = x.override1; //~ WARN use of unstable
+ let _ = x.override1; //~ ERROR use of unstable
let _ = x.override2;
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
let Stable {
inherit: _,
- override1: _, //~ WARN use of unstable
+ override1: _, //~ ERROR use of unstable
override2: _
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
} = x;
// all fine
let Stable { .. } = x;
let x = Stable2(1, 2, 3);
let _ = x.0;
- let _ = x.1; //~ WARN use of unstable
+ let _ = x.1; //~ ERROR use of unstable
let _ = x.2;
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
let Stable2(_,
- _, //~ WARN use of unstable
+ _, //~ ERROR use of unstable
_)
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
= x;
// all fine
let Stable2(..) = x;
- let x = Unstable { //~ WARN use of unstable
- inherit: 1, //~ WARN use of unstable
+ let x = Unstable { //~ ERROR use of unstable
+ inherit: 1, //~ ERROR use of unstable
override1: 2,
override2: 3,
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
};
- let _ = x.inherit; //~ WARN use of unstable
+ let _ = x.inherit; //~ ERROR use of unstable
let _ = x.override1;
let _ = x.override2;
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
- let Unstable { //~ WARN use of unstable
- inherit: _, //~ WARN use of unstable
+ let Unstable { //~ ERROR use of unstable
+ inherit: _, //~ ERROR use of unstable
override1: _,
override2: _
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
} = x;
- let Unstable //~ WARN use of unstable
+ let Unstable //~ ERROR use of unstable
// the patterns are all fine:
{ .. } = x;
- let x = Unstable2(1, 2, 3); //~ WARN use of unstable
+ let x = Unstable2(1, 2, 3); //~ ERROR use of unstable
- let _ = x.0; //~ WARN use of unstable
+ let _ = x.0; //~ ERROR use of unstable
let _ = x.1;
let _ = x.2;
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
- let Unstable2 //~ WARN use of unstable
- (_, //~ WARN use of unstable
+ let Unstable2 //~ ERROR use of unstable
+ (_, //~ ERROR use of unstable
_,
_)
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
= x;
- let Unstable2 //~ WARN use of unstable
+ let Unstable2 //~ ERROR use of unstable
// the patterns are all fine:
(..) = x;
let x = Deprecated {
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
inherit: 1,
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
override1: 2,
- override2: 3, //~ WARN use of unstable
+ override2: 3, //~ ERROR use of unstable
};
let _ = x.inherit;
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
let _ = x.override1;
- let _ = x.override2; //~ WARN use of unstable
+ let _ = x.override2; //~ ERROR use of unstable
let Deprecated {
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
inherit: _,
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
override1: _,
- override2: _ //~ WARN use of unstable
+ override2: _ //~ ERROR use of unstable
} = x;
let Deprecated
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
// the patterns are all fine:
{ .. } = x;
let x = Deprecated2(1, 2, 3);
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
let _ = x.0;
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
let _ = x.1;
- let _ = x.2; //~ WARN use of unstable
+ let _ = x.2; //~ ERROR use of unstable
let Deprecated2
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
(_,
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
_,
- _) //~ WARN use of unstable
+ _) //~ ERROR use of unstable
= x;
let Deprecated2
//~^ ERROR use of deprecated item
- //~^^ WARN use of unstable
+ //~^^ ERROR use of unstable
// the patterns are all fine:
(..) = x;
}
mod cross_crate {
extern crate stability_cfg1;
- extern crate stability_cfg2; //~ WARNING: use of unstable library feature
+ extern crate stability_cfg2; //~ ERROR use of unstable library feature
use lint_stability::*;
<Foo as Trait>::trait_deprecated_text(&foo); //~ ERROR use of deprecated item: text
deprecated_unstable(); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
foo.method_deprecated_unstable(); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
Foo::method_deprecated_unstable(&foo); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo>::method_deprecated_unstable(&foo); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
foo.trait_deprecated_unstable(); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
Trait::trait_deprecated_unstable(&foo); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo>::trait_deprecated_unstable(&foo); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo as Trait>::trait_deprecated_unstable(&foo); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
deprecated_unstable_text(); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
foo.method_deprecated_unstable_text(); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
Foo::method_deprecated_unstable_text(&foo); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo>::method_deprecated_unstable_text(&foo); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
foo.trait_deprecated_unstable_text(); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
Trait::trait_deprecated_unstable_text(&foo); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo>::trait_deprecated_unstable_text(&foo); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo as Trait>::trait_deprecated_unstable_text(&foo); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
- unstable(); //~ WARNING use of unstable library feature
- foo.method_unstable(); //~ WARNING use of unstable library feature
- Foo::method_unstable(&foo); //~ WARNING use of unstable library feature
- <Foo>::method_unstable(&foo); //~ WARNING use of unstable library feature
- foo.trait_unstable(); //~ WARNING use of unstable library feature
- Trait::trait_unstable(&foo); //~ WARNING use of unstable library feature
- <Foo>::trait_unstable(&foo); //~ WARNING use of unstable library feature
- <Foo as Trait>::trait_unstable(&foo); //~ WARNING use of unstable library feature
+ unstable(); //~ ERROR use of unstable library feature
+ foo.method_unstable(); //~ ERROR use of unstable library feature
+ Foo::method_unstable(&foo); //~ ERROR use of unstable library feature
+ <Foo>::method_unstable(&foo); //~ ERROR use of unstable library feature
+ foo.trait_unstable(); //~ ERROR use of unstable library feature
+ Trait::trait_unstable(&foo); //~ ERROR use of unstable library feature
+ <Foo>::trait_unstable(&foo); //~ ERROR use of unstable library feature
+ <Foo as Trait>::trait_unstable(&foo); //~ ERROR use of unstable library feature
unstable_text();
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
foo.method_unstable_text();
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
Foo::method_unstable_text(&foo);
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
<Foo>::method_unstable_text(&foo);
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
foo.trait_unstable_text();
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
Trait::trait_unstable_text(&foo);
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
<Foo>::trait_unstable_text(&foo);
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
<Foo as Trait>::trait_unstable_text(&foo);
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
stable();
foo.method_stable();
let _ = DeprecatedStruct { i: 0 }; //~ ERROR use of deprecated item
let _ = DeprecatedUnstableStruct { i: 0 }; //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
- let _ = UnstableStruct { i: 0 }; //~ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
+ let _ = UnstableStruct { i: 0 }; //~ ERROR use of unstable library feature
let _ = StableStruct { i: 0 };
let _ = DeprecatedUnitStruct; //~ ERROR use of deprecated item
let _ = DeprecatedUnstableUnitStruct; //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
- let _ = UnstableUnitStruct; //~ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
+ let _ = UnstableUnitStruct; //~ ERROR use of unstable library feature
let _ = StableUnitStruct;
let _ = Enum::DeprecatedVariant; //~ ERROR use of deprecated item
let _ = Enum::DeprecatedUnstableVariant; //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
- let _ = Enum::UnstableVariant; //~ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
+ let _ = Enum::UnstableVariant; //~ ERROR use of unstable library feature
let _ = Enum::StableVariant;
let _ = DeprecatedTupleStruct (1); //~ ERROR use of deprecated item
let _ = DeprecatedUnstableTupleStruct (1); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
- let _ = UnstableTupleStruct (1); //~ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
+ let _ = UnstableTupleStruct (1); //~ ERROR use of unstable library feature
let _ = StableTupleStruct (1);
// At the moment, the lint checker only checks stability in
// on macros themselves are not yet linted.
macro_test_arg!(deprecated_text()); //~ ERROR use of deprecated item: text
macro_test_arg!(deprecated_unstable_text()); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
macro_test_arg!(macro_test_arg!(deprecated_text())); //~ ERROR use of deprecated item: text
}
<Foo>::trait_deprecated_text(&foo); //~ ERROR use of deprecated item: text
<Foo as Trait>::trait_deprecated_text(&foo); //~ ERROR use of deprecated item: text
foo.trait_deprecated_unstable(); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
Trait::trait_deprecated_unstable(&foo); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo>::trait_deprecated_unstable(&foo); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo as Trait>::trait_deprecated_unstable(&foo); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
foo.trait_deprecated_unstable_text(); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
Trait::trait_deprecated_unstable_text(&foo); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo>::trait_deprecated_unstable_text(&foo); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
<Foo as Trait>::trait_deprecated_unstable_text(&foo); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
- foo.trait_unstable(); //~ WARNING use of unstable library feature
- Trait::trait_unstable(&foo); //~ WARNING use of unstable library feature
- <Foo>::trait_unstable(&foo); //~ WARNING use of unstable library feature
- <Foo as Trait>::trait_unstable(&foo); //~ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
+ foo.trait_unstable(); //~ ERROR use of unstable library feature
+ Trait::trait_unstable(&foo); //~ ERROR use of unstable library feature
+ <Foo>::trait_unstable(&foo); //~ ERROR use of unstable library feature
+ <Foo as Trait>::trait_unstable(&foo); //~ ERROR use of unstable library feature
foo.trait_unstable_text();
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
Trait::trait_unstable_text(&foo);
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
<Foo>::trait_unstable_text(&foo);
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
<Foo as Trait>::trait_unstable_text(&foo);
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
foo.trait_stable();
Trait::trait_stable(&foo);
<Foo>::trait_stable(&foo);
foo.trait_deprecated(); //~ ERROR use of deprecated item
foo.trait_deprecated_text(); //~ ERROR use of deprecated item: text
foo.trait_deprecated_unstable(); //~ ERROR use of deprecated item
- //~^ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
foo.trait_deprecated_unstable_text(); //~ ERROR use of deprecated item: text
- //~^ WARNING use of unstable library feature
- foo.trait_unstable(); //~ WARNING use of unstable library feature
+ //~^ ERROR use of unstable library feature
+ foo.trait_unstable(); //~ ERROR use of unstable library feature
foo.trait_unstable_text();
- //~^ WARNING use of unstable library feature 'test_feature': text
+ //~^ ERROR use of unstable library feature 'test_feature': text
foo.trait_stable();
}
struct S;
- impl UnstableTrait for S { } //~ WARNING use of unstable library feature
+ impl UnstableTrait for S { } //~ ERROR use of unstable library feature
- trait LocalTrait : UnstableTrait { } //~ WARNING use of unstable library feature
+ trait LocalTrait : UnstableTrait { } //~ ERROR use of unstable library feature
impl Trait for S {
fn trait_stable(&self) {}
- fn trait_unstable(&self) {} //~ WARNING use of unstable library feature
+ fn trait_unstable(&self) {} //~ ERROR use of unstable library feature
}
}
mod inheritance {
- extern crate inherited_stability; //~ WARNING: use of unstable library feature
- use self::inherited_stability::*; //~ WARNING: use of unstable library feature
+ extern crate inherited_stability; //~ ERROR use of unstable library feature
+ use self::inherited_stability::*; //~ ERROR use of unstable library feature
fn test_inheritance() {
- unstable(); //~ WARNING use of unstable library feature
+ unstable(); //~ ERROR use of unstable library feature
stable();
- stable_mod::unstable(); //~ WARNING use of unstable library feature
+ stable_mod::unstable(); //~ ERROR use of unstable library feature
stable_mod::stable();
unstable_mod::deprecated(); //~ ERROR use of deprecated item
- unstable_mod::unstable(); //~ WARNING use of unstable library feature
+ unstable_mod::unstable(); //~ ERROR use of unstable library feature
- let _ = Unstable::UnstableVariant; //~ WARNING use of unstable library feature
+ let _ = Unstable::UnstableVariant; //~ ERROR use of unstable library feature
let _ = Unstable::StableVariant;
let x: usize = 0;
- x.unstable(); //~ WARNING use of unstable library feature
+ x.unstable(); //~ ERROR use of unstable library feature
x.stable();
}
}
+++ /dev/null
-// Copyright 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.
-
-#![forbid(unused_typecasts)]
-
-fn foo_i32(_: i32) {}
-
-fn foo_u64(a: u64) {
- let b: i32 = a as i32;
- foo_i32(b as i32); //~ ERROR: unnecessary type cast
-}
-
-fn main() {
- let x: u64 = 1;
- let y: u64 = x as u64; //~ ERROR: unnecessary type cast
- foo_u64(y as u64); //~ ERROR: unnecessary type cast
-}
#![deny(unused_variables)]
#![deny(unused_assignments)]
-#![allow(dead_code, non_camel_case_types)]
+#![allow(dead_code, non_camel_case_types, trivial_numeric_casts)]
fn f1(x: isize) {
//~^ ERROR unused variable: `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.
+
+// Check that when making a ref mut binding with type `&mut T`, the
+// type `T` must match precisely the type `U` of the value being
+// matched, and in particular cannot be some supertype of `U`. Issue
+// #23116. This test focuses on a `match`.
+
+#![allow(dead_code)]
+struct S<'b>(&'b i32);
+impl<'b> S<'b> {
+ fn bar<'a>(&'a mut self) -> &'a mut &'a i32 {
+ match self.0 { ref mut x => x } //~ ERROR mismatched types
+ }
+}
+
+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.
+
+// Check that when making a ref mut binding with type `&mut T`, the
+// type `T` must match precisely the type `U` of the value being
+// matched, and in particular cannot be some supertype of `U`. Issue
+// #23116. This test focuses on a `let`.
+
+#![allow(dead_code)]
+struct S<'b>(&'b i32);
+impl<'b> S<'b> {
+ fn bar<'a>(&'a mut self) -> &'a mut &'a i32 {
+ let ref mut x = self.0;
+ x //~ ERROR mismatched types
+ }
+}
+
+fn main() {}
#![feature(rustc_attrs)]
#![allow(dead_code)]
+#![allow(trivial_casts)]
trait Bar {
fn bar(self);
}
impl FnMut<(isize,)> for S {
- type Output = isize;
-
extern "rust-call" fn call_mut(&mut self, (z,): (isize,)) -> isize {
self.x * self.y * z
}
}
+impl FnOnce<(isize,)> for S {
+ type Output = isize;
+ extern "rust-call" fn call_once(mut self, (z,): (isize,)) -> isize {
+ self.call_mut((z,))
+ }
+}
+
fn main() {
let mut s = S {
x: 3,
}
impl FnMut<isize> for S {
- type Output = isize;
extern "rust-call" fn call_mut(&mut self, z: isize) -> isize {
self.x + self.y + z
}
}
+impl FnOnce<isize> for S {
+ type Output = isize;
+ extern "rust-call" fn call_once(mut self, z: isize) -> isize { self.call_mut(z) }
+}
+
fn main() {
let mut s = S {
x: 1,
fn main() {
is_send::<A>();
//~^ ERROR overflow evaluating
- //~^^ NOTE consider adding a `#![recursion_limit="20"]` attribute to your crate
- //~^^^ NOTE required by `is_send`
- //~^^^^ ERROR overflow evaluating
- //~^^^^^ NOTE consider adding a `#![recursion_limit="20"]` attribute to your crate
- //~^^^^^^ NOTE required by `is_send`
- //~^^^^^^^ ERROR overflow evaluating
- //~^^^^^^^^ NOTE consider adding a `#![recursion_limit="20"]` attribute to your crate
- //~^^^^^^^^^ NOTE required by `is_send`
+ //~| NOTE consider adding a `#![recursion_limit="20"]` attribute to your crate
}
fn f<'a, T, U>(v: Box<A<T>+'static>) -> Box<X+'static> {
box B(&*v) as Box<X> //~ ERROR the parameter type `T` may not live long enough
+ //~^ ERROR the parameter type `T` may not live long enough
}
fn main() {}
fn make_object1<A:SomeTrait>(v: A) -> Box<SomeTrait+'static> {
box v as Box<SomeTrait+'static>
//~^ ERROR the parameter type `A` may not live long enough
+ //~^^ ERROR the parameter type `A` may not live long enough
}
fn make_object2<'a,A:SomeTrait+'a>(v: A) -> Box<SomeTrait+'a> {
fn make_object3<'a,'b,A:SomeTrait+'a>(v: A) -> Box<SomeTrait+'b> {
box v as Box<SomeTrait+'b>
//~^ ERROR the parameter type `A` may not live long enough
+ //~^^ ERROR the parameter type `A` may not live long enough
}
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.
+
+trait Dummy { fn dummy(&self); }
+
+fn foo1<'a:'b,'b>(x: &'a mut (Dummy+'a)) -> &'b mut (Dummy+'b) {
+ // Here, we are able to coerce
+ x
+}
+
+fn foo2<'a:'b,'b>(x: &'b mut (Dummy+'a)) -> &'b mut (Dummy+'b) {
+ // Here, we are able to coerce
+ x
+}
+
+fn foo3<'a,'b>(x: &'a mut Dummy) -> &'b mut Dummy {
+ // Without knowing 'a:'b, we can't coerce
+ x //~ ERROR mismatched types
+ //~^ ERROR cannot infer
+}
+
+struct Wrapper<T>(T);
+fn foo4<'a:'b,'b>(x: Wrapper<&'a mut Dummy>) -> Wrapper<&'b mut Dummy> {
+ // We can't coerce because it is packed in `Wrapper`
+ x //~ ERROR mismatched types
+}
+
+fn main() {}
--- /dev/null
+// Copyright 2015 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 the trivial_casts and trivial_numeric_casts lints. For each error we also
+// check that the cast can be done using just coercion.
+
+#![deny(trivial_casts, trivial_numeric_casts)]
+
+trait Foo {
+ fn foo(&self) {}
+}
+
+pub struct Bar;
+
+impl Foo for Bar {}
+
+pub fn main() {
+ // Numeric
+ let _ = 42_i32 as i32; //~ ERROR trivial numeric cast: `i32` as `i32`
+ let _: i32 = 42_i32;
+
+ let _ = 42_u8 as u8; //~ ERROR trivial numeric cast: `u8` as `u8`
+ let _: u8 = 42_u8;
+
+ // & to * pointers
+ let x: &u32 = &42;
+ let _ = x as *const u32; //~ERROR trivial cast: `&u32` as `*const u32`
+ let _: *const u32 = x;
+
+ let x: &mut u32 = &mut 42;
+ let _ = x as *mut u32; //~ERROR trivial cast: `&mut u32` as `*mut u32`
+ let _: *mut u32 = x;
+
+ // unsize array
+ let x: &[u32; 3] = &[42, 43, 44];
+ let _ = x as &[u32]; //~ERROR trivial cast: `&[u32; 3]` as `&[u32]`
+ let _ = x as *const [u32]; //~ERROR trivial cast: `&[u32; 3]` as `*const [u32]`
+ let _: &[u32] = x;
+ let _: *const [u32] = x;
+
+ let x: &mut [u32; 3] = &mut [42, 43, 44];
+ let _ = x as &mut [u32]; //~ERROR trivial cast: `&mut [u32; 3]` as `&mut [u32]`
+ let _ = x as *mut [u32]; //~ERROR trivial cast: `&mut [u32; 3]` as `*mut [u32]`
+ let _: &mut [u32] = x;
+ let _: *mut [u32] = x;
+
+ let x: Box<[u32; 3]> = Box::new([42, 43, 44]);
+ let _ = x as Box<[u32]>; //~ERROR trivial cast: `Box<[u32; 3]>` as `Box<[u32]>`
+ let x: Box<[u32; 3]> = Box::new([42, 43, 44]);
+ let _: Box<[u32]> = x;
+
+ // unsize trait
+ let x: &Bar = &Bar;
+ let _ = x as &Foo; //~ERROR trivial cast: `&Bar` as `&Foo`
+ let _ = x as *const Foo; //~ERROR trivial cast: `&Bar` as `*const Foo`
+ let _: &Foo = x;
+ let _: *const Foo = x;
+
+ let x: &mut Bar = &mut Bar;
+ let _ = x as &mut Foo; //~ERROR trivial cast: `&mut Bar` as `&mut Foo`
+ let _ = x as *mut Foo; //~ERROR trivial cast: `&mut Bar` as `*mut Foo`
+ let _: &mut Foo = x;
+ let _: *mut Foo = x;
+
+ let x: Box<Bar> = Box::new(Bar);
+ let _ = x as Box<Foo>; //~ERROR trivial cast: `Box<Bar>` as `Box<Foo>`
+ let x: Box<Bar> = Box::new(Bar);
+ let _: Box<Foo> = x;
+
+ // functions
+ fn baz(_x: i32) {}
+ let _ = &baz as &Fn(i32); //~ERROR trivial cast: `&fn(i32) {main::baz}` as `&core::ops::Fn(i32)`
+ let _: &Fn(i32) = &baz;
+ let x = |_x: i32| {};
+ let _ = &x as &Fn(i32); //~ERROR trivial cast
+ let _: &Fn(i32) = &x;
+}
+
+// subtyping
+pub fn test_subtyping<'a, 'b: 'a>(a: &'a Bar, b: &'b Bar) {
+ let _ = a as &'a Bar; //~ERROR trivial cast
+ let _: &'a Bar = a;
+ let _ = b as &'a Bar; //~ERROR trivial cast
+ let _: &'a Bar = b;
+ let _ = b as &'b Bar; //~ERROR trivial cast
+ let _: &'b Bar = b;
+}
}
fn main() {
- let x = 5;
+ let x: i32 = 5;
let y = x as MyAdd<i32>;
//~^ ERROR as `MyAdd<i32>`
}
struct S;
impl FnMut<(isize,)> for S {
- type Output = isize;
-
extern "rust-call" fn call_mut(&mut self, (x,): (isize,)) -> isize {
x * x
}
}
+impl FnOnce<(isize,)> for S {
+ type Output = isize;
+
+ extern "rust-call" fn call_once(mut self, args: (isize,)) -> isize { self.call_mut(args) }
+}
+
fn call_it<F:Fn(isize)->isize>(f: &F, x: isize) -> isize {
f.call((x,))
}
fn main() {
let x = call_it(&S, 22);
//~^ ERROR not implemented
- //~| ERROR not implemented
}
}
impl<A,R,F : FnMut(&mut FnMut(A) -> R, A) -> R> FnMut<(A,)> for YCombinator<F,A,R> {
- type Output = R;
-
extern "rust-call" fn call_mut(&mut self, (arg,): (A,)) -> R {
(self.func)(self, arg)
//~^ ERROR cannot borrow `*self` as mutable more than once at a time
}
}
+impl<A,R,F : FnMut(&mut FnMut(A) -> R, A) -> R> FnOnce<(A,)> for YCombinator<F,A,R> {
+ type Output = R;
+ extern "rust-call" fn call_once(mut self, args: (A,)) -> R {
+ self.call_mut(args)
+ }
+}
+
fn main() {
let mut counter = 0;
let factorial = |recur: &mut FnMut(u32) -> u32, arg: u32| -> u32 {
}
fn b() {
- let y = call_it_mut(&mut square, 22); //~ ERROR not implemented
+ let y = call_it_mut(&mut square, 22);
+ //~^ ERROR not implemented
+ //~| ERROR not implemented
}
fn c() {
- let z = call_it_once(square, 22); //~ ERROR not implemented
+ let z = call_it_once(square, 22);
+ //~^ ERROR not implemented
+ //~| ERROR not implemented
}
fn main() { }
}
fn b() {
- let y = call_it_mut(&mut square, 22); //~ ERROR not implemented
+ let y = call_it_mut(&mut square, 22);
+ //~^ ERROR not implemented
+ //~| ERROR not implemented
}
fn c() {
- let z = call_it_once(square, 22); //~ ERROR not implemented
+ let z = call_it_once(square, 22);
+ //~^ ERROR not implemented
+ //~| ERROR not implemented
}
fn main() { }
}
fn b() {
- let y = call_it_mut(&mut square, 22); //~ ERROR not implemented
+ let y = call_it_mut(&mut square, 22);
+ //~^ ERROR not implemented
+ //~| ERROR not implemented
}
fn c() {
- let z = call_it_once(square, 22); //~ ERROR not implemented
+ let z = call_it_once(square, 22);
+ //~^ ERROR not implemented
+ //~| ERROR not implemented
}
fn main() { }
// Issue #14893. Tests that casts from vectors don't behave strangely in the
// presence of the `_` type shorthand notation.
+// Update: after a change to the way casts are done, we have more type information
+// around and so the errors here are no longer exactly the same.
struct X {
y: [u8; 2],
fn main() {
let x1 = X { y: [0, 0] };
- let p1: *const u8 = &x1.y as *const _; //~ ERROR mismatched types
+ // No longer a type mismatch - the `_` can be fully resolved by type inference.
+ let p1: *const u8 = &x1.y as *const _;
let t1: *const [u8; 2] = &x1.y as *const _;
let h1: *const [u8; 2] = &x1.y as *const [u8; 2];
let mut x1 = X { y: [0, 0] };
+ // This is still an error since we don't allow casts from &mut [T; n] to *mut T.
let p1: *mut u8 = &mut x1.y as *mut _; //~ ERROR mismatched types
let t1: *mut [u8; 2] = &mut x1.y as *mut _;
let h1: *mut [u8; 2] = &mut x1.y as *mut [u8; 2];
#![allow(unused_variables)]
#![allow(dead_code)]
#![omit_gdb_pretty_printer_section]
+#![feature(std_misc, core)]
// This test makes sure that the compiler doesn't crash when trying to assign
// debug locations to const-expressions.
// compile-flags:-g
+#![feature(old_io)]
+
// === GDB TESTS ===================================================================================
// gdb-command:run
// compile-flags:-g
+#![feature(old_io)]
+
// === GDB TESTS ===================================================================================
// gdb-command:rbreak immediate_args
// lldb-command:continue
#![allow(unused_variables)]
+#![feature(old_io)]
#![omit_gdb_pretty_printer_section]
fn immediate_args(a: int, b: bool, c: f64) {
// min-lldb-version: 310
// aux-build:issue13213aux.rs
+
+#![feature(old_io)]
+
extern crate issue13213aux;
// compile-flags:-g
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
+#![feature(core)]
use std::simd::{i8x16, i16x8,i32x4,i64x2,u8x16,u16x8,u32x4,u64x2,f32x4,f64x2};
let slice2 = &*vec2;
// Trait Objects
- let box_trait = (box 0) as Box<Trait1>;
- let ref_trait = &0 as &Trait1;
- let mut mut_int1 = 0;
+ let box_trait = (box 0_isize) as Box<Trait1>;
+ let ref_trait = &0_isize as &Trait1;
+ let mut mut_int1 = 0_isize;
let mut_ref_trait = (&mut mut_int1) as &mut Trait1;
- let generic_box_trait = (box 0) as Box<Trait2<i32, Mod1::Struct2>>;
- let generic_ref_trait = (&0) as &Trait2<Struct1, Struct1>;
+ let generic_box_trait = (box 0_isize) as Box<Trait2<i32, Mod1::Struct2>>;
+ let generic_ref_trait = (&0_isize) as &Trait2<Struct1, Struct1>;
- let mut generic_mut_ref_trait_impl = 0;
+ let mut generic_mut_ref_trait_impl = 0_isize;
let generic_mut_ref_trait = (&mut generic_mut_ref_trait_impl) as
&mut Trait2<Mod1::Mod2::Struct3, GenericStruct<usize, isize>>;
+++ /dev/null
-// Copyright 2015 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 we generate obsolete syntax errors around usages of `for Sized?`
-
-trait Foo for Sized? {} //~ ERROR obsolete syntax: for Sized?
-
-trait Bar for ?Sized {} //~ ERROR obsolete syntax: for Sized?
-
-fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(optin_builtin_traits)]
+#![feature(optin_builtin_traits, core)]
// pp-exact
fn main() {
let x: Box<Tr+ Sync>;
- Box::new(1) as Box<Tr+ Sync>;
+ Box::new(1isize) as Box<Tr+ Sync>;
}
// error-pattern:explicit failure
// Testing that runtime failure doesn't cause callbacks to abort abnormally.
// Instead the failure will be delivered after the callbacks return.
+#![feature(std_misc, libc)]
extern crate libc;
use std::task;
// error-pattern:whatever
+#![feature(os, rustc_private)]
+
#[macro_use] extern crate log;
use std::os;
// error-pattern:whatever
+#![feature(os, rustc_private)]
+
#[macro_use] extern crate log;
use std::os;
use std::thread;
// error-pattern:whatever
+#![feature(rustc_private, os)]
+
#[macro_use] extern crate log;
use std::os;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(test_feature)]
+
extern crate bar;
pub fn main() { bar::baz() }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(old_io, old_path)]
+
use std::env;
use std::fs::File;
use std::process::Command;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc, old_path, os)]
+
use std::dynamic_lib::DynamicLibrary;
use std::os;
use std::old_path::Path;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(asm)]
+#![feature(asm, core)]
#![crate_type="lib"]
use std::intrinsics;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(rustc_private, path, convert)]
+
extern crate rustc;
extern crate rustc_driver;
extern crate rustc_lint;
panic!("expected rustc path");
}
- let tmpdir = PathBuf::new(&args[1]);
+ let tmpdir = PathBuf::from(&args[1]);
- let mut sysroot = PathBuf::new(&args[3]);
+ let mut sysroot = PathBuf::from(&args[3]);
sysroot.pop();
sysroot.pop();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(libc, os)]
+
extern crate libc;
#[link(name="foo")]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(rustc_private)]
+
extern crate lib;
#[macro_use] extern crate log;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(lang_items, no_std)]
+#![feature(lang_items, no_std, libc)]
#![no_std]
#![crate_type = "dylib"]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(lang_items, no_std)]
+#![feature(lang_items, no_std, libc)]
#![no_std]
#![crate_type = "dylib"]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(optin_builtin_traits)]
+#![feature(core)]
+
pub mod bar {
use std::marker;
#![ crate_name = "test" ]
#![allow(unstable)]
-#![feature(box_syntax)]
+#![feature(box_syntax, old_io, rustc_private, core)]
extern crate graphviz;
// A simple rust project
pub fn dummy() {
// force the vtable to be created
- let _x = &1 as &Foo;
+ let _x = &1u as &Foo;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(rand)]
+
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(rand, core)]
+
use std::fs::File;
use std::io::prelude::*;
use std::iter::repeat;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
use std::intrinsics::{volatile_load, volatile_store};
pub fn main() {
// ignore-android
-#![feature(rustc_private)]
+#![feature(rustc_private, path)]
#![feature(core)]
extern crate getopts;
// ignore-pretty
// ignore-android
-#![feature(quote)]
+#![feature(quote, rustc_private)]
extern crate syntax;
// ignore-android
// ignore-pretty: does not work well with `--test`
-#![feature(quote)]
+#![feature(quote, rustc_private)]
extern crate syntax;
// ignore-android
// ignore-pretty: does not work well with `--test`
-#![feature(quote)]
+#![feature(quote, rustc_private)]
extern crate syntax;
// ignore-android
// ignore-pretty: does not work well with `--test`
-#![feature(quote)]
+#![feature(quote, rustc_private)]
#![deny(unused_variable)]
extern crate syntax;
// aux-build:syntax_extension_with_dll_deps_2.rs
// ignore-stage1
-#![feature(plugin)]
+#![feature(plugin, rustc_private)]
#![plugin(syntax_extension_with_dll_deps_2)]
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(old_io, io)]
+
fn main() {
let _ = std::old_io::stdin();
let _ = std::io::stdin();
// Regression test for issue #374
+// pretty-expanded FIXME #23616
+
enum sty { ty_nil, }
struct RawT {struct_: sty, cname: Option<String>, hash: uint}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum option<T> { some(T), none, }
struct R<T> {v: Vec<option<T>> }
// except according to those terms.
// aux-build:anon-extern-mod-cross-crate-1.rs
+// pretty-expanded FIXME #23616
+
extern crate anonexternmod;
use anonexternmod::rust_get_test_int;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
#[link(name = "rust_test_helpers")]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct X {
x: int
}
+// pretty-expanded FIXME #23616
+
pub fn main() {
let i32_c: int = 0x10101010;
assert!(i32_c + i32_c * 2 / 3 * 2 + (i32_c - 7 % 3) ==
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(type_limits)]
// Unsigned integer operations
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f() -> int { { return 3; } }
pub fn main() { assert!((f() == 3)); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
assert_eq!(3 as uint * 3, 9);
assert_eq!(3 as (uint) * 3, 9);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(asm)]
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(asm)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(asm)]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
// except according to those terms.
// Issue 483 - Assignment expressions result in nil
+// pretty-expanded FIXME #23616
+
fn test_assign() {
let mut x: int;
let y: () = x = 10;
// making method calls, but only if there aren't any matches without
// it.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
trait iterable<A> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::marker::MarkerTrait;
trait Foo : MarkerTrait {
// Test a case where the associated type binding (to `bool`, in this
// case) is derived from the trait definition. Issue #21636.
+// pretty-expanded FIXME #23616
+
use std::vec;
pub trait BitIter {
// Test equality constraints on associated types in a where clause.
+// pretty-expanded FIXME #23616
+
pub trait Foo {
type A;
fn boo(&self) -> <Self as Foo>::A;
// Test equality constrai32s on associated types in a where clause.
+// pretty-expanded FIXME #23616
+
pub trait ToI32 {
fn to_i32(&self) -> i32;
}
// `Target=[A]`, then the impl marked with `(*)` is seen to conflict
// with all the others.
+// pretty-expanded FIXME #23616
+
use std::marker::PhantomData;
use std::ops::Deref;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait SignedUnsigned {
type Opposite;
fn convert(self) -> Self::Opposite;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// (modulo bound lifetime names) appears in the environment
// twice. Issue #21965.
+// pretty-expanded FIXME #23616
+
fn foo<T>(t: T) -> i32
where T : for<'a> Fn(&'a u8) -> i32,
T : for<'b> Fn(&'b u8) -> i32,
// Check that we do not report ambiguities when the same predicate
// appears in the environment twice. Issue #21965.
+// pretty-expanded FIXME #23616
+
trait Foo {
type B;
// Test associated types appearing in struct-like enum variants.
+// pretty-expanded FIXME #23616
+
use self::VarValue::*;
pub trait UnifyKey {
// Test associated types appearing in tuple-like enum variants.
+// pretty-expanded FIXME #23616
+
use self::VarValue::*;
pub trait UnifyKey {
// Test equality constraints on associated types inside of an object type
+// pretty-expanded FIXME #23616
+
pub trait Foo {
type A;
fn boo(&self) -> <Self as Foo>::A;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value;
// Test references to `Self::Item` in the trait. Issue #20220.
+// pretty-expanded FIXME #23616
+
use std::vec;
trait IntoIteratorX {
// Test that we are able to have an impl that defines an associated type
// before the actual trait.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::marker::MarkerTrait;
impl X for f64 { type Y = int; }
// where clauses in the environment which in turn required normalizing
// `Self::Input`.
+// pretty-expanded FIXME #23616
+
pub trait Parser {
type Input;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn pairwise_sub<T:DoubleEndedIterator<Item=int>>(mut t: T) -> int {
let mut result = 0;
loop {
// Test that we can resolve nested projection types. Issue #20666.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::marker::MarkerTrait;
use std::slice;
// Test that we normalize associated types that appear in a bound that
// contains a binding. Issue #21664.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
#![allow(dead_code)]
use std::marker::MarkerTrait;
// Test that we normalize associated types that appear in bounds; if
// we didn't, the call to `self.split2()` fails to type check.
+// pretty-expanded FIXME #23616
+
use std::marker::PhantomData;
struct Splits<'a, T:'a, P>(PhantomData<(&'a T, P)>);
// Test that we normalize associated types that appear in bounds; if
// we didn't, the call to `self.split2()` fails to type check.
+// pretty-expanded FIXME #23616
+
use std::marker::PhantomData;
struct Splits<'a, T, P>(PhantomData<(&'a(),T,P)>);
// various special paths in the `type_is_immediate` function.
+// pretty-expanded FIXME #23616
+
pub trait OffsetState: Sized {}
pub trait Offset {
type State: OffsetState;
// `Item` originates in a where-clause, not the declaration of
// `T`. Issue #20300.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::marker::{MarkerTrait, PhantomData};
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
use std::sync::atomic::Ordering::SeqCst;
// Test where the impl self type uses a projection from a constant type.
+// pretty-expanded FIXME #23616
+
trait Int
{
type T;
// appear in associated type bindings in object types, which were not
// being properly flagged.
+// pretty-expanded FIXME #23616
+
use std::ops::{Shl, Shr};
use std::cell::RefCell;
// Test that we are handle to correctly handle a projection type
// that appears in a supertrait bound. Issue #20559.
+// pretty-expanded FIXME #23616
+
trait A
{
type TA;
// Test a where clause that uses a non-normalized projection type.
+// pretty-expanded FIXME #23616
+
trait Int
{
type T;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo<T> {
type Bar;
fn get_bar() -> <Self as Foo<T>>::Bar;
// Test associated type references in structure fields.
+// pretty-expanded FIXME #23616
+
trait Test {
type V;
// Test associated type references in a struct literal. Issue #20535.
+// pretty-expanded FIXME #23616
+
pub trait Foo {
type Bar;
// Regression test for #20582. This test caused an ICE related to
// inconsistent region erasure in trans.
+// pretty-expanded FIXME #23616
+
struct Foo<'a> {
buf: &'a[u8]
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Get<T> {
fn get(&self) -> T;
}
// Test equality constraints on associated types in a where clause.
+// pretty-expanded FIXME #23616
+
pub trait Foo {
type A;
fn boo(&self) -> <Self as Foo>::A;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value;
// Test references to the trait `Stream` in the bounds for associated
// types defined on `Stream`. Issue #20551.
+// pretty-expanded FIXME #23616
+
trait Stream {
type Car;
type Cdr: Stream;
// Test that we correctly normalize the type of a struct field
// which has an associated type.
+// pretty-expanded FIXME #23616
+
pub trait UnifyKey {
type Value;
// Test that we correctly normalize the type of a struct field
// which has an associated type.
+// pretty-expanded FIXME #23616
+
pub trait UnifyKey {
type Value;
// Test paths to associated types using the type-parameter-only sugar.
+// pretty-expanded FIXME #23616
+
pub trait Foo {
type A;
fn boo(&self) -> Self::A;
// carries a predicate that references the trait (`u32 : Trait1`,
// substituted).
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Trait1 : Trait2<SomeType<u32>> {
// error-pattern:expected item
-#![feature(custom_attribute)]
+// pretty-expanded FIXME #23616
+
+#![feature(custom_attribute, test)]
#[foo = "bar"]
extern crate test;
// error-pattern:expected item
-#![feature(custom_attribute)]
+// pretty-expanded FIXME #23616
+
+#![feature(custom_attribute, test)]
mod m {
#[foo = "bar"]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(main)]
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(main)]
#[main]
// <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.
+// pretty-expanded FIXME #23616
+
#![allow(unused_attribute)]
#![feature(custom_attribute)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
#![feature(unsafe_no_drop_flag)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(start)]
#[start]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(main)]
#[main]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut sum = 0;
let xs = vec!(1, 2, 3, 4, 5);
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Pushable<T> {
fn push_val(&mut self, t: T);
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f<T>(x: Vec<T>) -> T { return x.into_iter().next().unwrap(); }
fn g<F>(act: F) -> int where F: FnOnce(Vec<int>) -> int { return act(vec!(1, 2, 3)); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo {
x: int,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
}
pub fn main() {
- let x: Box<_> = box() (box 3 as Box<double>);
+ let x: Box<_> = box() (box 3u as Box<double>);
assert_eq!(x.double(), 6);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// ignore-windows FIXME #13259
#![feature(unboxed_closures)]
-#![feature(unsafe_destructor)]
+#![feature(unsafe_destructor, old_io, collections)]
use std::env;
use std::old_io::process::Command;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert_eq!(0xffffffff, (-1 as u32));
assert_eq!(4294967295, (-1 as u32));
// Check that issue #954 stays fixed
+// pretty-expanded FIXME #23616
+
pub fn main() {
match -1 { -1 => {}, _ => panic!("wat") }
assert_eq!(1-1, 0);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::sync::Arc;
fn dispose(_x: Arc<bool>) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
struct Foo { x: int, y: int }
let mut f = Foo { x: 10, y: 0 };
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, collections)]
extern crate collections;
use std::collections::BitVec;
// aux-build:blind-item-mixed-crate-use-item-foo.rs
// aux-build:blind-item-mixed-crate-use-item-foo2.rs
+// pretty-expanded FIXME #23616
+
mod m {
pub fn f<T>(_: T, _: (), _: ()) { }
pub fn g<T>(_: T, _: (), _: ()) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod m {
pub fn f<T>(_: T, _: ()) { }
pub fn g<T>(_: T, _: ()) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn asBlock<F>(f: F) -> uint where F: FnOnce() -> uint {
return f();
}
// no-reformat
+// pretty-expanded FIXME #23616
+
/*
*
* When you write a block-expression thing followed by
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn force<F>(f: F) -> int where F: FnOnce() -> int { return f(); }
pub fn main() {
+// pretty-expanded FIXME #23616
+
pub fn main() {
if !false { assert!((true)); } else { assert!((false)); }
if !true { assert!((false)); } else { assert!((true)); }
// Basic boolean tests
+// pretty-expanded FIXME #23616
+
use std::cmp::Ordering::{Equal, Greater, Less};
use std::ops::{BitAnd, BitOr, BitXor};
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn foo(self);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo(int, int);
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
struct A {
a: int,
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct F { f: Vec<int> }
fn impure(_v: &[int]) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
//
// Example from src/librustc_borrowck/borrowck/README.md
+// pretty-expanded FIXME #23616
+
fn foo<'a>(mut t0: &'a mut int,
mut t1: &'a mut int) {
let p: &int = &*t0; // Freezes `*t0`
// that the main function can read the variable too while
// the closures are in scope. Issue #6801.
+// pretty-expanded FIXME #23616
+
fn a() -> i32 {
let mut x = 3;
x += 1;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = [22];
let y = &x[0];
// Test that a `&mut` inside of an `&` is freezable.
+// pretty-expanded FIXME #23616
+
struct MutSlice<'a, T:'a> {
data: &'a mut [T]
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn borrow(_v: &int) {}
fn borrow_from_arg_imm_ref(v: Box<int>) {
// Check that we do not ICE when compiling this
// macro, which reuses the expression `$id`
+// pretty-expanded FIXME #23616
+
#![feature(box_patterns)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
#![feature(unboxed_closures)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn want_slice(v: &[int]) -> int {
let mut sum = 0;
for i in v { sum += *i; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut x = None;
match x {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Counter {
value: uint
}
// limited to the deref operation itself, and does not infect the
// block as a whole.
+// pretty-expanded FIXME #23616
+
struct Box {
x: uint
}
// Regression test for issue #7740
+// pretty-expanded FIXME #23616
+
pub fn main() {
static A: &'static char = &'A';
}
// This test verifies that casting from the same lifetime on a value
// to the same lifetime on a trait succeeds. See issue #10766.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
use std::marker;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Rec {
f: Box<int>,
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::cell::Cell;
#[derive(Copy)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo(s: &String) -> bool {
match &**s {
"kitty" => true,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo<'r>(s: &'r uint) -> bool {
match s {
&3 => true,
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let (&x, &y) = (&3, &'a');
assert_eq!(x, 3);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn select<'r>(x: &'r Option<int>, y: &'r Option<int>) -> &'r Option<int> {
match (x, y) {
(&None, &None) => x,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo<T:Clone>(x: &T) -> T{
match x {
&ref a => (*a).clone()
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let _a = Box::new(1);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn int_id(x: int) -> int { return x; }
pub fn main() { loop { int_id(break); } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut i = 0;
while i < 20 { i += 1; if i == 10 { break; } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Speak : Sized {
fn say(&self, s:&str) -> String;
fn hi(&self) -> String { hello(self) }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub trait Foo<T> {
fn func1<U>(&self, t: U, w: T);
// a Send. Basically this just makes sure rustc is using
// each_bound_trait_and_supertraits in type_contents correctly.
+// pretty-expanded FIXME #23616
+
use std::sync::mpsc::{channel, Sender};
trait Bar : Send { }
// Tests "capabilities" granted by traits with super-builtin-kinds,
// even when using them cross-crate.
+// pretty-expanded FIXME #23616
+
extern crate trait_superkinds_in_metadata;
use std::sync::mpsc::{channel, Sender, Receiver};
// builtin-kinds, e.g., if a trait requires Send to implement, then
// at usage site of that trait, we know we have the Send capability.
+// pretty-expanded FIXME #23616
+
use std::sync::mpsc::{channel, Sender, Receiver};
trait Foo : Send { }
// Tests (correct) usage of trait super-builtin-kinds cross-crate.
+// pretty-expanded FIXME #23616
+
extern crate trait_superkinds_in_metadata;
use trait_superkinds_in_metadata::{RequiresRequiresShareAndSend, RequiresShare};
use trait_superkinds_in_metadata::{RequiresCopy};
// super-builtin-kind of a trait, if the type parameter is never used,
// the type can implement the trait anyway.
+// pretty-expanded FIXME #23616
+
use std::marker;
trait Foo : Send { }
// Tests the ability for the Self type in default methods to use
// capabilities granted by builtin kinds as supertraits.
+// pretty-expanded FIXME #23616
+
use std::sync::mpsc::{Sender, channel};
trait Foo : Send + Sized + 'static {
// Simple test case of implementing a trait with super-builtin-kinds.
+// pretty-expanded FIXME #23616
+
trait Foo : Send { }
impl Foo for int { }
// Tests correct implementation of traits with super-builtin-kinds
// using a bounded type parameter.
+// pretty-expanded FIXME #23616
+
trait Foo : Send { }
impl <T: Send> Foo for T { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct X {
a: int
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
mod rustrt {
extern crate libc;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc, std_misc)]
+
extern crate libc;
use std::ffi::CString;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo() -> int { 22 }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn each<T, F>(x: &[T], mut f: F) where F: FnMut(&T) {
for val in x {
f(val)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
fn each<'a,T,F:FnMut(&'a T)>(x: &'a [T], mut f: F) {
// exec-env:RUST_LOG=info
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, old_io, rustc_private, std_misc)]
#[macro_use]
extern crate log;
// issues #10618 and #16382
+// pretty-expanded FIXME #23616
+
const SIZE: int = 25;
fn main() {
// except according to those terms.
pub fn main() {
- let x = 3;
+ let x: int = 3;
println!("&x={:x}", (&x as *const int as uint));
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let i: int = 'Q' as int;
assert_eq!(i, 0x51);
// This test makes sure we can do cross-crate inlining on functions
// that use capture clauses.
+// pretty-expanded FIXME #23616
+
extern crate cci_capture_clause;
pub fn main() {
// aux-build:cci_nested_lib.rs
+// pretty-expanded FIXME #23616
+
#![feature(globs)]
extern crate cci_nested_lib;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::cell::Cell;
#[derive(Copy)]
// main is conditionally compiled, but the conditional compilation
// is conditional too!
+// pretty-expanded FIXME #23616
+
#[cfg_attr(foo, cfg(bar))]
fn main() { }
// https://github.com/rust-lang/rust/issues/21833#issuecomment-72353044
+// pretty-expanded FIXME #23616
+
#![cfg_attr(not_used, no_std)]
fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[cfg(windows)]
pub fn main() {
}
// check that cfg correctly chooses between the macro impls (see also
// cfg-macros-notfoo.rs)
+// pretty-expanded FIXME #23616
+
#[cfg(foo)]
#[macro_use]
mod foo {
// check that cfg correctly chooses between the macro impls (see also
// cfg-macros-foo.rs)
+// pretty-expanded FIXME #23616
+
#[cfg(foo)]
#[macro_use]
mod foo {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
Bar,
Baz,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[cfg(target_family = "windows")]
pub fn main() {
}
// aux-build:cfg_inner_static.rs
+// pretty-expanded FIXME #23616
+
extern crate cfg_inner_static;
pub fn main() {
// compile-flags: --cfg fooA --cfg fooB
// fooA AND !bar
+// pretty-expanded FIXME #23616
+
#[cfg(all(fooA, not(bar)))]
fn foo1() -> int { 1 }
+// pretty-expanded FIXME #23616
+
pub fn main() {
let c: char = 'x';
let d: char = 'x';
// Checks that mutable static items can have mutable slices
+// pretty-expanded FIXME #23616
+
static mut TEST: &'static mut [int] = &mut [1];
pub fn main() {
// aux-build:check_static_recursion_foreign_helper.rs
-#![feature(custom_attribute)]
+// pretty-expanded FIXME #23616
+
+#![feature(custom_attribute, libc)]
extern crate check_static_recursion_foreign_helper;
extern crate libc;
// Check that the various ways of getting to a reference to a vec (both sized
// and unsized) work properly.
+// pretty-expanded FIXME #23616
+
const aa: [int; 3] = [1, 2, 3];
const ab: &'static [int; 3] = &aa;
const ac: &'static [int] = ab;
// Reported as issue #126, child leaks the string.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::thread::Thread;
fn child2(_s: String) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct cat {
done : extern fn(uint),
meows : uint,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/* Test that exporting a class also exports its
public fields and methods */
// except according to those terms.
// aux-build:cci_class_2.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_class_2;
use cci_class_2::kitties::cat;
// except according to those terms.
// aux-build:cci_class_3.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_class_3;
use cci_class_3::kitties::cat;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct cat {
meows : uint,
// except according to those terms.
// aux-build:cci_class_6.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_class_6;
use cci_class_6::kitties::cat;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct cat<U> {
info : Vec<U> ,
meows : uint,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct cat {
name : String,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::marker::PhantomData;
struct cat<U> {
// except according to those terms.
// aux-build:cci_class_4.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_class_4;
use cci_class_4::kitties::cat;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct kitten {
cat: Option<cat>,
}
// except according to those terms.
// aux-build:cci_class.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_class;
use cci_class::kitties::cat;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct cat {
meows : uint,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct cat {
meows : uint,
// Test that cleanup scope for temporaries created in a match
// arm is confined to the match arm itself.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, os)]
use std::os;
// This test verifies that temporaries created for `while`'s and `if`
// conditions are dropped after the condition is evaluated.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// It's unclear how likely such a bug is to recur, but it seems like a
// scenario worth testing.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Test that cleanups for the RHS of shortcircuiting operators work.
+// pretty-expanded FIXME #23616
+
use std::env;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, std_misc)]
use std::thread::Thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
use std::sync::mpsc::channel;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo(i: isize) -> isize { i + 1 }
fn apply<A, F>(f: F, v: A) -> A where F: FnOnce(A) -> A { f(v) }
// Test a rather underspecified example:
+// pretty-expanded FIXME #23616
+
pub fn main() {
let f = {|i| i};
assert_eq!(f(2), 2);
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, old_io)]
use std::mem;
use std::old_io::stdio::println;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::cmp::Ordering;
// Test default methods in PartialOrd and PartialEq
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Check that coercions are propagated through match and if expressions.
+// pretty-expanded FIXME #23616
+
use std::boxed::Box;
pub fn main() {
// Check that coercions are propagated through match and if expressions.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::rc::Rc;
// Examples from the "deref coercions" RFC, at rust-lang/rfcs#241.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn negate(x: &int) -> int {
-*x
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct SpeechMaker {
speeches: uint
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn sum(x: &[int]) -> int {
let mut sum = 0;
for y in x { sum += *y; }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn bar(v: &mut [uint]) -> Vec<uint> {
v.to_vec()
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct SpeechMaker {
speeches: uint
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct SpeechMaker {
speeches: uint
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn reverse(v: &mut [uint]) {
v.reverse();
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn bar(v: &mut [uint]) {
v.reverse();
v.reverse();
// Check that coercions unify the expected return type of a polymorphic
// function call, instead of leaving the type variables as they were.
+// pretty-expanded FIXME #23616
+
struct Foo;
impl Foo {
fn foo<T>(self, x: T) -> Option<T> { Some(x) }
// aux-build:coherence-lib.rs
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::Remote1;
// aux-build:coherence-lib.rs
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::Remote1;
// aux-build:coherence-lib.rs
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::Remote1;
// aux-build:coherence-lib.rs
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::Remote;
// Test that it's ok for T to appear first in the self-type, as long
// as it's covered somewhere.
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::{Remote,Pair};
// Test that it's ok for T to appear second in the self-type, as long
// as it's covered somewhere.
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::{Remote,Pair};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
#[derive(Copy)]
enum x { foo }
// aux-build:coherence-lib.rs
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::Remote1;
// aux-build:coherence-lib.rs
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::Remote1;
// aux-build:coherence-lib.rs
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::Remote;
// aux-build:coherence-lib.rs
+// pretty-expanded FIXME #23616
+
extern crate "coherence-lib" as lib;
use lib::Remote;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::fmt::Debug;
use std::default::Default;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(optin_builtin_traits)]
use std::marker::Send;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// no-pretty-expanded
-
use std::io::Write;
use std::fmt;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
type an_int = int;
fn cmp(x: Option<an_int>, y: Option<int>) -> bool {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert_eq!(format!(concat!("foo", "bar", "{}"), "baz"), "foobarbaz".to_string());
assert_eq!(format!(concat!()), "".to_string());
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[cfg(target_arch = "x86")]
pub fn main() { }
// except according to those terms.
// Crate use statements
+// pretty-expanded FIXME #23616
+
#[cfg(bogus)]
use flippity;
// compile-flags: -C debug-assertions=no
// exec-env:RUST_LOG=conditional-debug-macro-off=4
+// pretty-expanded FIXME #23616
+
+#![feature(rustc_private)]
+
#[macro_use]
extern crate log;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static A: [u8; 1] = ['h' as u8];
static B: u8 = (&A)[0];
static C: &'static &'static &'static &'static [u8; 1] = & & & &A;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
Bar(u32),
Baz,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => ({
use std::num::Float;
// aux-build:cci_const_block.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_const_block;
pub fn main() {
// General test that function items in static blocks
// can be generated with a macro.
+// pretty-expanded FIXME #23616
+
struct MyType {
desc: &'static str,
data: uint,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod foo {
pub trait Value {
fn value(&self) -> uint;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
#![allow(unused_unsafe)]
// Make sure const bounds work on things, and test that a few types
// are const.
+// pretty-expanded FIXME #23616
+
fn foo<T: Sync>(x: T) -> T { x }
struct F { field: int }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ptr;
struct TestStruct {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
struct TestStruct {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const a: int = 1;
const b: int = a + 2;
// Issue #570
+// pretty-expanded FIXME #23616
+
static lsl : int = 1 << 2;
static add : int = 1 + 2;
static addf : f64 = 1.0 + 2.0;
// aux-build:cci_const.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_const;
static foo: &'static str = cci_const::foopy;
static a: uint = cci_const::uint_val;
// aux-build:cci_const.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_const;
use cci_const::bar;
static foo: extern "C" fn() = bar;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const C: &'static int = &1000;
static D: int = *C;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V, VV(int) }
static C: E = E::V;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V, VV(int) }
static C: E = E::V;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum A { A1, A2 }
enum B { B1=0, B2=2 }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V0, V1(int) }
static C: &'static E = &E::V0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V16(u16), V32(u32) }
struct S { a: E, b: u16, c: u16 }
static C: S = S { a: E::V16(0xDEAD), b: 0x600D, c: 0xBAD };
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V0, V16(u16) }
struct S { a: E, b: u16, c: u16 }
static C: S = S { a: E::V0, b: 0x600D, c: 0xBAD };
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E {
S0 { s: String },
S1 { u: uint }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V16(u16), V32(u32) }
static C: (E, u16, u16) = (E::V16(0xDEAD), 0x600D, 0xBAD);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V0, V16(u16) }
static C: (E, u16, u16) = (E::V0, 0x600D, 0xBAD);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V16(u16), V32(u32) }
struct S(E, u16, u16);
static C: S = S(E::V16(0xDEAD), 0x600D, 0xBAD);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V0, V16(u16) }
struct S(E, u16, u16);
static C: S = S(E::V0, 0x600D, 0xBAD);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V1(int), V0 }
const C: &'static [E] = &[E::V0, E::V1(0xDEADBEE)];
static C0: E = C[0];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V1(int), V0 }
static C: &'static [E] = &[E::V0, E::V1(0xDEADBEE), E::V0];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E { V1(int), V0 }
static C: [E; 3] = [E::V0, E::V1(0xDEADBEE), E::V0];
// Check that constant expressions can be used for declaring the
// type of a fixed length vector.
+// pretty-expanded FIXME #23616
+
pub fn main() {
const FOO: uint = 2;
// Check that constant expressions can be used in vec repeat syntax.
+// pretty-expanded FIXME #23616
+
pub fn main() {
const FOO: uint = 2;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
extern fn foopy() {}
static f: extern "C" fn() = foopy;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo() -> int {
return 0xca7f000d;
}
// Issue #358
+// pretty-expanded FIXME #23616
+
static toplevel_mod: int = -1;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
Bar,
Baz,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
enum Foo {
Bar = 0xDEADBEE
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
type Big = [u64; 8];
struct Pair<'a> { a: int, b: &'a Big }
const x: &'static Big = &([13, 14, 10, 13, 11, 14, 14, 15]);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::{str, string};
const A: [u8; 2] = ['h' as u8, 'i' as u8];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
IntVal(i32),
Int64Val(i64)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Bar(int, int);
static X: Bar = Bar(1, 2);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo;
static X: Foo = Foo;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*!
* Try to double-check that static fns have the right size (with or
* without dummy env ptr, as appropriate) by iterating a size-2 array.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f(_: &[int]) {}
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const FOO: int = 10;
const BAR: int = 3;
//
// (Compare with compile-fail/move-out-of-array-1.rs)
+// pretty-expanded FIXME #23616
+
struct C { _x: u8 }
impl Copy for C { }
// instead of in std.
#![reexport_test_harness_main = "test_main"]
+#![feature(old_io, libc, std_misc)]
extern crate libc;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
use ::std::mem;
mem::drop(2_usize);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// compile-flags:--crate-name crate-name-attr-used -F unused-attributes
+// pretty-expanded FIXME #23616
+
#![crate_name = "crate-name-attr-used"]
fn main() {}
--- /dev/null
+// Copyright 2015 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(tempdir)]
+
+use std::env;
+use std::fs::{self, TempDir};
+
+fn main() {
+ let td = TempDir::new("create-dir-all-bare").unwrap();
+ env::set_current_dir(td.path()).unwrap();
+ fs::create_dir_all("create-dir-all-bare").unwrap();
+}
// aux-build:cci_const.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_const;
pub fn main() {
// aux-build:newtype_struct_xc.rs
+// pretty-expanded FIXME #23616
+
extern crate newtype_struct_xc;
pub fn main() {
// Regression test for #15477. This test just needs to compile.
+// pretty-expanded FIXME #23616
+
use std::marker::PhantomFn;
trait Chromosome<X: Chromosome<i32>> : PhantomFn<(Self,X)> {
// Test a case where a supertrait references a type that references
// the original trait. This poses no problem at the moment.
+// pretty-expanded FIXME #23616
+
trait Chromosome: Get<Struct<i32>> {
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![deny(dead_code)]
static _X: uint = 0;
+// pretty-expanded FIXME #23616
+
fn f(x: int) -> int {
if x == 1 { return 1; } else { let y: int = 1 + f(x - 1); return y; }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn m(&self, _:int) { }
}
+++ /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.
-
-//~ WARNING no_split_stack is a deprecated synonym for no_stack_check
-#[no_split_stack]
-fn main() {
-}
// Test that `&mut T` implements `DerefMut<T>`
+// pretty-expanded FIXME #23616
+
use std::ops::{Deref, DerefMut};
fn inc<T: Deref<Target=int> + DerefMut>(mut t: T) {
// Test that `&T` and `&mut T` implement `Deref<T>`
+// pretty-expanded FIXME #23616
+
use std::ops::Deref;
fn deref<U:Copy,T:Deref<Target=U>>(t: T) -> U {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::rc::Rc;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(no_std)]
+#![feature(no_std, core, rand, collections, rustc_private)]
#![no_std]
extern crate core;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
struct Test;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Clone)]
enum E {
A,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Clone)]
enum E<T,U> {
A(T),
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Clone)]
struct S<T> {
foo: (),
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Clone)]
struct S<T>(T, ());
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Clone)]
struct S {
_int: int,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Clone)]
struct S((), ());
// no-pretty-expanded FIXME #15189
+// pretty-expanded FIXME #23616
+
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum E<T> {
E0,
// no-pretty-expanded FIXME #15189
+// pretty-expanded FIXME #23616
+
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum ES<T> {
ES1 { x: T },
// no-pretty-expanded FIXME #15189
+// pretty-expanded FIXME #23616
+
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct S<T> {
x: T,
// no-pretty-expanded FIXME #15189
+// pretty-expanded FIXME #23616
+
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct TS<T>(T,T);
// where possible, by having a type that panics when compared as the
// second element, so this passes iff the instances shortcircuit.
+// pretty-expanded FIXME #23616
+
use std::cmp::Ordering;
pub struct FailCmp;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
-#![feature(old_orphan_check)]
+#![feature(old_orphan_check, rustc_private)]
extern crate serialize;
// This briefly tests the capability of `Cell` and `RefCell` to implement the
// `Encodable` and `Decodable` traits via `#[derive(Encodable, Decodable)]`
-#![feature(old_orphan_check)]
+// pretty-expanded FIXME #23616
+
+#![feature(old_orphan_check, rustc_private)]
extern crate serialize;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub type task_id = int;
#[derive(PartialEq)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(old_orphan_check)]
+#![feature(old_orphan_check, rand, rustc_private)]
extern crate serialize;
extern crate rand;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(hash)]
+
use std::hash::{Hash, SipHasher};
#[derive(Hash)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! define_vec {
() => (
mod foo {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::hash::{Hash, SipHasher};
// testing multiple separate deriving attributes
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::hash::{Hash, SipHasher};
#[derive(PartialEq, Clone, Hash)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
use std::num::FromPrimitive;
use std::isize;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(rand)]
+
use std::rand;
#[derive(Rand)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Hash)]
enum Foo {
Bar(int, char),
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Hash)]
struct Foo {
x: int,
// Ensure that we can do a destructuring bind of a fixed-size array,
// even when the element type has a destructor.
+// pretty-expanded FIXME #23616
+
struct D { x: u8 }
impl Drop for D { fn drop(&mut self) { } }
// Just testing that panic!() type checks in statement or expr
+// pretty-expanded FIXME #23616
+
#![allow(unreachable_code)]
fn f() {
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x: int = 15;
let y: int = 5;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn check_expr() {
let _: & uint = &1;
let _: & & uint = &&1;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
+// pretty-expanded FIXME #23616
+
fn f() -> int {
if true {
let _s: String = "should not leak".to_string();
// Test that destructor on a struct runs successfully after the struct
// is boxed and converted to an object.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo { }
impl Drop for Foo {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(str_words)]
+
fn main() {
let foo = "hello".to_string();
let foo: Vec<&str> = foo.words().collect();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
fn main() {
let args = vec!("foobie", "asdf::asdf");
let arr: Vec<&str> = args[1].split_str("::").collect();
// shows a similar setup, but restricts `f` so that the struct `C<'a>`
// is force-fed a lifetime equal to that of the borrowed arena.
+// pretty-expanded FIXME #23616
+
#![allow(unstable)]
-#![feature(unsafe_destructor)]
+#![feature(unsafe_destructor, rustc_private)]
extern crate arena;
// Test coercions involving DST and/or raw pointers
+// pretty-expanded FIXME #23616
+
struct S;
trait T { fn dummy(&self) { } }
impl T for S {}
// Test that a custom deref with a fat pointer return type does not ICE
+// pretty-expanded FIXME #23616
+
use std::ops::{Deref, DerefMut};
pub struct Arr {
// Test that a custom deref with a fat pointer return type does not ICE
+// pretty-expanded FIXME #23616
+
use std::ops::Deref;
pub struct Arr {
// Test that overloaded index expressions with DST result types
// work and don't ICE.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::ops::Index;
use std::fmt::Debug;
impl Index<uint> for S {
type Output = str;
- fn index<'a>(&'a self, _: &uint) -> &'a str {
+ fn index<'a>(&'a self, _: uint) -> &'a str {
"hello"
}
}
impl Index<uint> for T {
type Output = Debug + 'static;
- fn index<'a>(&'a self, idx: &uint) -> &'a (Debug + 'static) {
+ fn index<'a>(&'a self, idx: uint) -> &'a (Debug + 'static) {
static X: uint = 42;
&X as &(Debug + 'static)
}
// Test DST raw pointers
+// pretty-expanded FIXME #23616
+
trait Trait {
fn foo(&self) -> int;
}
// As dst-struct.rs, but the unsized field is the only field in the struct.
+// pretty-expanded FIXME #23616
+
struct Fat<T: ?Sized> {
ptr: T
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Regression test for a problem with the first mod attribute
// being applied to every mod
+// pretty-expanded FIXME #23616
+
#[cfg(target_os = "linux")]
mod hello;
// aux-build:anon-extern-mod-cross-crate-1.rs
// aux-build:anon-extern-mod-cross-crate-1.rs
+// pretty-expanded FIXME #23616
+
extern crate anonexternmod;
pub fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn wsucc(n: int) -> int { 0 + { return n + 1 } }
pub fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait thing<A> {
fn foo(&self) -> Option<A>;
}
+// pretty-expanded FIXME #23616
+
pub fn main() {
if 1 == 2 {
assert!((false));
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert!(Some(Box::new(())).is_some());
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = *Box::new(());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_mut)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
fn addr_of<T>(ptr: &T) -> uint {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*!
* C-like enums have to be represented as LLVM ints, not wrapped in a
* struct, because it's important for the FFI that they interoperate
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Animal {
Cat = 0,
Dog = 1,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::size_of;
enum Ei8 {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::size_of;
#[repr(i8)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub enum E64 {
H64 = 0x7FFF_FFFF_FFFF_FFFF,
L64 = 0x8000_0000_0000_0000
// pp-exact
+// pretty-expanded FIXME #23616
+
enum color { red = 1, green, blue, imaginary = -1, }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod a {
pub enum Foo {
Bar,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
extern crate core;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::result::Result;
use std::result::Result::Ok;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unused_variable)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Flopsy {
Bunny = 2
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(path)]
+#![feature(convert)]
+
use std::env::*;
use std::path::PathBuf;
let oldhome = var("HOME");
set_var("HOME", "/home/MountainView");
- assert!(home_dir() == Some(PathBuf::new("/home/MountainView")));
+ assert!(home_dir() == Some(PathBuf::from("/home/MountainView")));
remove_var("HOME");
if cfg!(target_os = "android") {
assert!(home_dir().is_some());
set_var("HOME", "/home/MountainView");
- assert!(home_dir() == Some(PathBuf::new("/home/MountainView")));
+ assert!(home_dir() == Some(PathBuf::from("/home/MountainView")));
remove_var("HOME");
set_var("USERPROFILE", "/home/MountainView");
- assert!(home_dir() == Some(PathBuf::new("/home/MountainView")));
+ assert!(home_dir() == Some(PathBuf::from("/home/MountainView")));
set_var("HOME", "/home/MountainView");
set_var("USERPROFILE", "/home/PaloAlto");
- assert!(home_dir() == Some(PathBuf::new("/home/MountainView")));
+ assert!(home_dir() == Some(PathBuf::from("/home/MountainView")));
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::env::*;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(PartialEq)]
struct Bar;
struct Baz;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
pub fn main() {
// exec-env:TEST_EXEC_ENV=22
+// pretty-expanded FIXME #23616
+
use std::env;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x: int = 8;
let y = 9;
// Test to make sure that explicit self params work inside closures
+// pretty-expanded FIXME #23616
+
struct Box {
x: uint
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// aux-build:explicit_self_xcrate.rs
+// pretty-expanded FIXME #23616
+
extern crate explicit_self_xcrate;
use explicit_self_xcrate::{Foo, Bar};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::num::strconv::ExponentFormat::{ExpBin, ExpDec};
use std::num::strconv::SignificantDigits::DigMax;
use std::num::strconv::SignFormat::{SignAll, SignNeg};
// We can export tags without exporting the variants to create a simple
// sort of ADT.
+// pretty-expanded FIXME #23616
+
mod foo {
pub enum t { t1, }
// Modified to not use export since it's going away. --pcw
+// pretty-expanded FIXME #23616
+
mod foo {
use foo::bar::*;
pub mod bar {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use m::f;
use m::g;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod foo {
pub enum t { t1, }
}
+// pretty-expanded FIXME #23616
+
fn test_fn() {
fn ten() -> int { return 10; }
let rs = ten;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool {
let actual: T = { expected.clone() };
assert!(eq(expected, actual));
// Regression test for issue #377
+// pretty-expanded FIXME #23616
+
struct A { a: int }
struct V { v: int }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Tests for standalone blocks as expressions
+// pretty-expanded FIXME #23616
+
fn test_basic() { let rs: bool = { true }; assert!((rs)); }
struct RS { v1: int, v2: int }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f(arg: &mut A) {
arg.a = 100;
}
// Issue #521
+// pretty-expanded FIXME #23616
+
fn f() {
let _x = match true {
true => { 10 }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test_int() {
fn f() -> int { 10 }
assert_eq!(f(), 10);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test_generic<T, F>(expected: T, not_expected: T, eq: F) where
T: Clone,
F: FnOnce(T, T) -> bool,
// When all branches of an if expression result in panic, the entire if
// expression results in panic.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _x = if true {
10
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test_if_panic() {
let x = if false { panic!() } else { 10 };
assert!((x == 10));
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Tests for if as expressions
+// pretty-expanded FIXME #23616
+
fn test_if() { let rs: bool = if true { true } else { false }; assert!((rs)); }
fn test_else() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
type compare<T> = extern "Rust" fn(T, T) -> bool;
fn test_generic<T:Clone>(expected: T, eq: compare<T>) {
// When all branches of a match expression result in panic, the entire
// match expression results in panic.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _x =
match true {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test_simple() {
let r = match true { true => { true } false => { panic!() } };
assert_eq!(r, true);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Tests for using match as an expression
+// pretty-expanded FIXME #23616
+
fn test_basic() {
let mut rs: bool = match true { true => { true } false => { false } };
assert!((rs));
// Regression test for issue #762
+// pretty-expanded FIXME #23616
+
pub fn f() { }
pub fn main() { return ::f(); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static FOO : &'static str = concat!(concat!("hel", "lo"), "world");
pub fn main() {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::cell::Cell;
#[derive(Copy)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
extern fn f() {
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(libc)]
+
extern crate libc;
mod rustrt {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc, libc)]
+
extern crate libc;
use std::thread::Thread;
// Test direct calls to extern fns.
+// pretty-expanded FIXME #23616
+
extern fn f(x: uint) -> uint { x * 2 }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(libc)]
+
extern crate libc;
mod rustrt {
// make sure the stack pointers are maintained properly in both
// directions
+#![feature(libc, std_misc)]
+
extern crate libc;
use std::thread::Thread;
// aux-build:extern_calling_convention.rs
+// pretty-expanded FIXME #23616
+
extern crate extern_calling_convention;
use extern_calling_convention::foo;
// Tests that we can compare various kinds of extern fn signatures.
+// pretty-expanded FIXME #23616
+
extern fn voidret1() {}
extern fn voidret2() {}
//aux-build:extern-crosscrate-source.rs
+#![feature(libc)]
+
extern crate externcallback;
extern crate libc;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
extern crate "std" as mystd;
pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::marker::MarkerTrait;
trait A : MarkerTrait {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
extern "C" {
fn pow(x: f64, y: f64) -> f64;
}
// aux-build:extern_mod_ordering_lib.rs
+// pretty-expanded FIXME #23616
+
extern crate extern_mod_ordering_lib;
use extern_mod_ordering_lib::extern_mod_ordering_lib as the_lib;
// except according to those terms.
#![allow(unused_imports)]
+#![feature(rustc_private)]
extern crate serialize;
use serialize::json::Object;
// Test a function that takes/returns a u8.
+// pretty-expanded FIXME #23616
+
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_identity_u8(v: u8) -> u8;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_identity_double(v: f64) -> f64;
// Test a foreign function that accepts empty struct.
+// pretty-expanded FIXME #23616
+
struct TwoU8s {
one: u8,
two: u8,
// Test a function that takes/returns a u32.
+// pretty-expanded FIXME #23616
+
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_identity_u32(v: u32) -> u32;
// Test a call to a function that takes/returns a u64.
+// pretty-expanded FIXME #23616
+
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_extern_identity_u64(v: u64) -> u64;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
extern {
pub fn free(p: *const u8);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct TwoU16s {
one: u16, two: u16
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct TwoU32s {
one: u32, two: u32
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct TwoU64s {
one: u64, two: u64
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct TwoU8s {
one: u8, two: u8
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[repr(C)]
pub struct Foo(u32);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
extern fn f() {
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert!(option_env!("__HOPEFULLY_DOESNT_EXIST__").is_none());
}
// declarations, but we currently run them top-to-bottom. I don't think the
// order really matters that much as long as we define what it is.
+// pretty-expanded FIXME #23616
+
struct A;
struct B;
struct C {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
// Make sure that this view item is filtered out because otherwise it would
// trigger a compilation error
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let arr = [1,2,3];
let arr2 = arr;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ops::{Deref, DerefMut};
// Generic unique/owned smaht pointer.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::num::Float;
pub fn main() {
+// pretty-expanded FIXME #23616
+
pub fn main() {
let a = 1.5e6f64;
let b = 1.5E6f64;
+// pretty-expanded FIXME #23616
+
pub fn main() {
let f = 4.999999999999f64;
assert!((f > 4.90f64));
// Ensure that declarations and types which use `extern fn` both have the same
// ABI (#9309).
+// pretty-expanded FIXME #23616
+
extern {
fn printf();
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f(i: int, called: &mut bool) {
assert_eq!(i, 10);
*called = true;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn bare() {}
fn likes_block<F>(f: F) where F: FnOnce() { f() }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
pub fn main() {
// This is what the signature to spawn should look like with bare functions
+// pretty-expanded FIXME #23616
+
fn spawn<T:Send>(val: T, f: fn(T)) {
f(val);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct r<F> where F: FnOnce() {
field: F,
}
// Test explicit coercions from a fn item type to a fn pointer type.
+// pretty-expanded FIXME #23616
+
fn foo(x: int) -> int { x * 2 }
fn bar(x: int) -> int { x * 4 }
type IntMap = fn(int) -> int;
// Test implicit coercions from a fn item type to a fn pointer type.
+// pretty-expanded FIXME #23616
+
fn foo(x: int) -> int { x * 2 }
fn bar(x: int) -> int { x * 4 }
type IntMap = fn(int) -> int;
+// pretty-expanded FIXME #23616
+
fn foo(_f: fn(int) -> int) { }
fn id(x: int) -> int { return x; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let f = |(x, y): (int, int)| {
assert_eq!(x, 1);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_variable)]
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Pair { x: int, y: int }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum BogusOption<T> {
None,
Some(T),
// Test that for loops can do what RFC #235 claims
+// pretty-expanded FIXME #23616
+
fn main() {
let mut v = vec![1];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(lang_items, start, no_std)]
+// pretty-expanded FIXME #23616
+
+#![feature(lang_items, start, no_std, core, collections)]
#![no_std]
extern crate "std" as other;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() { let x: Vec<int> = Vec::new(); for _ in &x { panic!("moop"); } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = [1; 100];
let mut y = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
extern crate collections;
use std::collections::HashMap;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
extern crate collections;
use std::collections::HashMap;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = [1; 100];
let mut y = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = [1; 100];
let y = [2; 100];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = [1; 100];
let mut y = 0;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn two<F>(mut it: F) where F: FnMut(int) { it(0); it(1); }
pub fn main() {
// except according to those terms.
// ignore-aarch64
+#![feature(libc)]
extern crate libc;
// calling pin_task and that's having weird side-effects.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
mod rustrt1 {
extern crate libc;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc, libc)]
+
extern crate libc;
use std::ffi::CString;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
pub struct S {
x: u64,
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
mod foo {
// ABI is cdecl by default
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
mod rustrt {
extern crate libc;
// Passing enums by value
+// pretty-expanded FIXME #23616
+
pub enum void { }
mod bindgen {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
mod bar {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
use std::f64;
let x = "NaN".to_string();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(lang_items, start, no_std)]
+// pretty-expanded FIXME #23616
+
+#![feature(lang_items, start, no_std, core, collections)]
#![no_std]
extern crate "std" as other;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::cell::RefCell;
pub fn main() {
// Issue 4691: Ensure that functional-struct-updates operates
// correctly and moves rather than copy when appropriate.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, core)]
use std::marker::NoCopy as NP;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn ho<F>(f: F) -> int where F: FnOnce(int) -> int { let n: int = f(3); return n; }
fn direct(x: int) -> int { return x + 1; }
+// pretty-expanded FIXME #23616
+
fn f() -> int { return 42; }
pub fn main() {
// Test that we do not leak when the arg pattern must drop part of the
// argument (in this case, the `y` field).
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// boxes. Make sure that we don't free the box as we match the
// pattern.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_patterns)]
#![feature(box_syntax)]
// Test that we can compile code that uses a `_` in function argument
// patterns.
+// pretty-expanded FIXME #23616
+
fn foo((x, _): (int, int)) -> int {
x
}
// aux-build:default_type_params_xc.rs
+// pretty-expanded FIXME #23616
+
extern crate default_type_params_xc;
struct Vec<T, A = default_type_params_xc::Heap>(Option<(T,A)>);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::num::Int;
extern "C" fn foo<T: WrappingOps>(a: T, b: T) -> T { a.wrapping_add(b) }
// Issue #45: infer type parameters in function applications
+// pretty-expanded FIXME #23616
+
fn id<T>(x: T) -> T { return x; }
pub fn main() { let x: int = 42; let y: int = id(x); assert!((x == y)); }
+// pretty-expanded FIXME #23616
+
mod foomod {
pub fn foo<T>() { }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum wrapper<T> { wrapped(T), }
pub fn main() { let _w = wrapper::wrapped(vec!(1, 2, 3, 4, 5)); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct S<T>(T);
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait vec_utils<T> {
fn map_<U, F>(x: &Self, f: F) -> Vec<U> where F: FnMut(&T) -> U;
}
// This used to cause memory corruption in stage 0.
+// pretty-expanded FIXME #23616
+
enum thing<K> { some(K), }
pub fn main() { let _x = thing::some("hi".to_string()); }
+// pretty-expanded FIXME #23616
+
enum clam<T> { a(T), }
pub fn main() { let _c = clam::a(3); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unused_variable)]
#![allow(unknown_features)]
+// pretty-expanded FIXME #23616
+
struct Foo<T> {
a: T
}
+// pretty-expanded FIXME #23616
+
struct Pair<T> {x: T, y: T}
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(rustc_private)]
+
extern crate getopts;
use getopts::{optopt, getopts};
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn f() -> int { return 1; }
pub mod foo {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
enum Q { R(Option<uint>) }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
struct Pair { x: int, y: int }
// except according to those terms.
#![allow(unknown_features)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, std_misc)]
/**
A somewhat reduced test case to expose some Valgrind issues.
// `&Typer<'tcx>` was getting an incorrect binder level, yielding
// weird compilation ICEs and so forth.
+// pretty-expanded FIXME #23616
+
trait Typer<'tcx> {
fn method(&self, data: &'tcx int) -> &'tcx int { data }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Typer<'tcx> {
fn method(&self, data: &'tcx int) -> &'tcx int { data }
fn dummy(&self) { }
// A basic test of using a higher-ranked trait bound.
+// pretty-expanded FIXME #23616
+
trait FnLike<A,R> {
fn call(&self, arg: A) -> R;
}
// A basic test of using a higher-ranked trait bound.
+// pretty-expanded FIXME #23616
+
trait FnLike<A,R> {
fn call(&self, arg: A) -> R;
}
// did not consider that a match (something I would like to revise in
// a later PR).
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
use std::marker::PhantomData;
// Test that we can parse all the various places that a `for` keyword
// can appear representing universal quantification.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
#![allow(unused_variables)]
#![allow(dead_code)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
// Test that `F : Fn(int) -> int + Send` is interpreted as two
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(unboxed_closures)]
// A basic test of using a higher-ranked trait bound.
+// pretty-expanded FIXME #23616
+
trait FnLike<A,R> {
fn call(&self, arg: A) -> R;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
// A basic test of using a higher-ranked trait bound.
// PrinterSupport<'b>`, gets properly expanded when it appears in a
// closure type. This used to result in messed up De Bruijn indices.
+// pretty-expanded FIXME #23616
+
trait PrinterSupport<'ast> {
fn ast_map(&self) -> Option<&'ast uint> { None }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::size_of;
#[cfg(target_pointer_width = "32")]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod x {
pub fn g() -> uint {14}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! loop_x {
($e: expr) => {
// $e shouldn't be able to interact with this 'x
+// pretty-expanded FIXME #23616
+
pub fn main() { let mut x: i32 = -400; x = 0 - x; assert!((x == 400)); }
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut x: i8 = -12;
let y: i8 = -12;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = Some(3);
if let Some(y) = x {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo() { if (return) { } }
pub fn main() { foo(); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(advanced_slice_patterns)]
struct Foo(int, int, int, int);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum option_<T> {
none_,
some_(T),
// with the same name, which can be called on values that have a
// precise enough type to allow distinguishing between the methods.
+// pretty-expanded FIXME #23616
+
struct Foo<T>(T);
impl Foo<usize> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo;
trait Trait {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod foo {
pub struct Point {
pub x: i32,
// aux-build:impl_privacy_xc_1.rs
+// pretty-expanded FIXME #23616
+
extern crate impl_privacy_xc_1;
pub fn main() {
// aux-build:crate_with_invalid_spans.rs
+// pretty-expanded FIXME #23616
+
extern crate crate_with_invalid_spans;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use spam::{ham, eggs};
mod spam {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
use std::mem::*;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
use std::mem::replace;
let mut x = 5;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use foo::bar::{baz, quux,};
mod foo {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo(_: &[&str]) {}
fn bad(a: &str, b: &str) {
+++ /dev/null
-// Copyright 2015 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.
-
-// Given `<expr> as Box<Trait>`, we should be able to infer that a
-// `Box<_>` is the expected type.
-
-trait Foo { fn foo(&self) -> u32; }
-impl Foo for u32 { fn foo(&self) -> u32 { *self } }
-
-// (another impl to ensure trait-matching cannot just choose from a singleton set)
-impl Foo for () { fn foo(&self) -> u32 { -176 } }
-
-trait Boxed { fn make() -> Self; }
-impl Boxed for Box<u32> { fn make() -> Self { Box::new(7) } }
-
-// (another impl to ensure trait-matching cannot just choose from a singleton set)
-impl Boxed for () { fn make() -> Self { () } }
-
-fn boxed_foo() {
- let b7 = Boxed::make() as Box<Foo>;
- assert_eq!(b7.foo(), 7);
-}
-
-trait Refed<'a,T> { fn make(&'a T) -> Self; }
-impl<'a> Refed<'a, u32> for &'a u32 { fn make(x: &'a u32) -> Self { x } }
-
-// (another impl to ensure trait-matching cannot just choose from a singleton set)
-impl<'a,'b> Refed<'a, ()> for &'b () { fn make(_: &'a ()) -> Self { static U: () = (); &U } }
-
-fn refed_foo() {
- let a = 8;
- let b7 = Refed::make(&a) as &Foo;
- assert_eq!(b7.foo(), 8);
-}
-
-fn check_subtyping_works() {
- fn inner<'short, 'long:'short>(_s: &'short u32,
- l: &'long u32) -> &'short (Foo+'short) {
- Refed::make(l) as &Foo
- }
-
- let a = 9;
- let b = 10;
- let r = inner(&b, &a);
- assert_eq!(r.foo(), 9);
-}
-
-pub fn main() {
- boxed_foo();
- refed_foo();
- check_subtyping_works();
-}
// issue #680
+// pretty-expanded FIXME #23616
+
fn f() -> Vec<int> { Vec::new() }
pub fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = 2;
let x_message = match x {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo;
impl Foo {
// Doing it incorrectly causes massive slowdown in LLVM during
// optimisation.
-#![feature(intrinsics)]
+// pretty-expanded FIXME #23616
+
+#![feature(intrinsics, std_misc)]
use std::thread::Thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
#![feature(unsafe_destructor)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo;
impl Foo {
// aux-build:inner_static.rs
+// pretty-expanded FIXME #23616
+
extern crate inner_static;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ptr;
// check that we do not report a type like this as uninstantiable,
+// pretty-expanded FIXME #23616
+
pub fn main() { let _x: int = 10; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let a = 0xBEEF_isize;
let b = 0o755_isize;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo(_: *const ()) {}
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
fn id_i8(n: i8) -> i8 { n }
fn id_i16(n: i16) -> i16 { n }
// propagation yet, and so we just saw a type variable, yielding an
// error.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::u8;
trait IntoIterator {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(intrinsics, main)]
mod rusti {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::intrinsics::assume;
unsafe fn f(x: i32) -> i32 {
// aux-build:cci_intrinsic.rs
+// pretty-expanded FIXME #23616
+
extern crate cci_intrinsic;
use cci_intrinsic::atomic_xchg;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
#![feature(intrinsics)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
#![feature(intrinsics)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(intrinsics)]
use std::ptr;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(intrinsics)]
mod rusti {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::intrinsics;
// See also src/test/run-make/intrinsic-unreachable.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(intrinsics)]
mod rusti {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(intrinsics)]
+// pretty-expanded FIXME #23616
+
+#![feature(intrinsics, core)]
macro_rules! assert_approx_eq {
($a:expr, $b:expr) => ({
// successfully (and safely) invoke external, cdecl
// functions from outside the crate.
+// pretty-expanded FIXME #23616
+
extern crate foreign_lib;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let ((),()) = ((),());
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
unsafe extern fn foo() {}
unsafe extern "C" fn bar() {}
// aux-build:issue-10028.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-10028" as issue10028;
use issue10028::ZeroLengthThingWithDestructor;
// except according to those terms.
// aux-build:issue_10031_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_10031_aux;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum StdioContainer {
CreatePipe(bool)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct A { foo: int }
struct B { a: int, b: int, c: int }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct Foo;
pub trait Bar {
// Make sure that if a process doesn't have its stdio/stderr descriptors set up
// that we don't die in a large ball of fire
+#![feature(old_io)]
+
use std::env;
use std::old_io::process;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
//// I am not a doc comment!
////////////////// still not a doc comment
// Regression test for issue #10682
// Nested `proc` usage can't use outer owned data
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ascii::AsciiExt;
static NAME: &'static str = "hello world";
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum v {}
pub fn main() {
let y: v = unsafe { ::std::mem::uninitialized() };
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
fn f<F:FnOnce()>(p: F) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_no_drop_flag)]
static mut drop_count: uint = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
extern "Rust" fn foo() {}
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
extern "Rust" fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn foo() -> int {
3
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![deny(missing_docs)]
#![doc="module"]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub mod two_tuple {
pub trait T { fn dummy(&self) { } }
pub struct P<'a>(&'a (T + 'a), &'a (T + 'a));
// compile-flags: --cfg foo
+// pretty-expanded FIXME #23616
+
struct Foo {
#[cfg(fail)]
bar: baz,
// Issue #1112
// Alignment of interior pointers to dynamic-size types
+// pretty-expanded FIXME #23616
+
struct X<T> {
a: T,
b: u8,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
// aux-build:issue-11224.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-11224" as unused;
pub fn main() {}
// aux-build:issue-11225-1.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-11225-1" as foo;
pub fn main() {
// aux-build:issue-11225-2.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-11225-2" as foo;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Common { fn dummy(&self) { } }
impl<'t, T> Common for (T, &'t T) {}
// aux-build:issue-11529.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-11529" as a;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_patterns)]
#![feature(box_syntax)]
+// pretty-expanded FIXME #23616
+
// 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.
// We weren't updating the auto adjustments with all the resolved
// type information after type check.
+// pretty-expanded FIXME #23616
+
trait A { fn dummy(&self) { } }
struct B<'a, T:'a> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
// this code used to cause an ICE
// when this bug was opened. The cases where the compiler
// panics before the fix have a comment.
+#![feature(std_misc)]
+
use std::thunk::Thunk;
struct S {x:()}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
extern crate collections;
use std::collections::BitVec;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct NoClone;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct A {
a: String
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(old_orphan_check)]
+// pretty-expanded FIXME #23616
+
+#![feature(old_orphan_check, rustc_private, old_io)]
extern crate rbml;
extern crate serialize;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const TEST_STR: &'static str = "abcd";
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![forbid(warnings)]
+#![feature(std_misc)]
// Pretty printing tests complain about `use std::predule::*`
#![allow(unused_imports)]
// aux-build:issue-12133-rlib.rs
// aux-build:issue-12133-dylib.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-12133-rlib" as a;
extern crate "issue-12133-dylib" as b;
// aux-build:issue-12133-dylib.rs
// no-prefer-dynamic
+// pretty-expanded FIXME #23616
+
extern crate "issue-12133-rlib" as a;
extern crate "issue-12133-dylib" as b;
// aux-build:issue-12133-dylib.rs
// aux-build:issue-12133-dylib2.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-12133-dylib2" as other;
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct S;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
#![crate_id="rust_get_test_int"]
mod rustrt {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main () {
let mut line = "".to_string();
let mut i = 0;
// aux-build:issue-12612-1.rs
// aux-build:issue-12612-2.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-12612-1" as foo;
extern crate "issue-12612-2" as bar;
// aux-build:issue-12660-aux.rs
+// pretty-expanded FIXME #23616
+
extern crate issue12660aux;
use issue12660aux::{my_fn, MyStruct};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let s = "Hello";
let first = s.bytes();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io, std_misc)]
+
use std::time::Duration;
use std::thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io, std_misc)]
+
use std::old_io::timer;
use std::time::Duration;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct Foo;
mod bar {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
extern crate collections;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::collections::HashMap;
fn copy<T: Copy>(&x: &T) -> T {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::marker::MarkerTrait;
trait Foo : MarkerTrait {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::slice;
pub struct PhfMapEntries<'a, T: 'a> {
// Test that when instantiating trait default methods, typeck handles
// lifetime parameters defined on the method bound correctly.
+// pretty-expanded FIXME #23616
+
pub trait Foo {
fn bar<'a, I: Iterator<Item=&'a ()>>(&self, it: I) -> uint {
let mut xs = it.filter(|_| true);
// defining static with struct that contains enum
// with &'static str variant used to cause ICE
+// pretty-expanded FIXME #23616
+
pub enum Foo {
Bar,
Baz(&'static str),
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
#[cfg(windows)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ops::Deref;
struct Root {
// except according to those terms.
// ignore-aarch64
+#![feature(io, process_capture)]
use std::env;
use std::io::prelude::*;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc, libc)]
+
extern crate libc;
use std::thunk::Thunk;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo<'a> {
i: &'a bool,
j: Option<&'a int>,
// This test may not always fail, but it can be flaky if the race it used to
// expose is still present.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread::Thread;
// except according to those terms.
// aux-build:issue13507.rs
+
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
extern crate issue13507;
use issue13507::testtypes;
// aux-build:issue-13620-1.rs
// aux-build:issue-13620-2.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-13620-2" as crate2;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, core)]
use std::ops::Fn;
struct Foo<T>(T);
impl<T: Copy> Fn<()> for Foo<T> {
- type Output = T;
extern "rust-call" fn call(&self, _: ()) -> T {
match *self {
Foo(t) => t
}
}
+impl<T: Copy> FnMut<()> for Foo<T> {
+ extern "rust-call" fn call_mut(&mut self, _: ()) -> T {
+ self.call(())
+ }
+}
+
+impl<T: Copy> FnOnce<()> for Foo<T> {
+ type Output = T;
+
+ extern "rust-call" fn call_once(self, _: ()) -> T {
+ self.call(())
+ }
+}
+
fn main() {
let t: u8 = 1;
println!("{}", Foo(t)());
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo<'r>() {
let maybe_value_ref: Option<&'r u8> = None;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct Foo<'a, 'b: 'a> { foo: &'a &'b int }
pub fn foo<'a, 'b>(x: Foo<'a, 'b>, _o: Option<& & ()>) { let _y = x.foo; }
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::u8;
const NUM: uint = u8::BITS as uint;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn bar(&self, int) {}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo<'a> {
listener: Box<FnMut() + 'a>,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct TestStruct {
x: *const [int; 2]
}
// Test that codegen works correctly when there are multiple refutable
// patterns in match expression.
+// pretty-expanded FIXME #23616
+
enum Foo {
FooUint(uint),
FooNullary,
// aux-build:issue-13872-2.rs
// aux-build:issue-13872-3.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-13872-3" as other;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(old_orphan_check)]
+#![feature(old_orphan_check, rustc_private)]
extern crate serialize;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_imports, dead_code)]
use foo::Foo;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn bar(&self);
fn baz(&self) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct A(int);
struct B;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[macro_use] extern crate "std" as std2;
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
match ("", 1_usize) {
(_, 42_usize) => (),
// value was coerced to a trait object. (v.clone() returns Box<B1>
// which is coerced to Box<A>).
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// aux-build:issue-14421.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-14421" as bug_lib;
use bug_lib::B;
// aux-build:issue-14422.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-14422" as bug_lib;
use bug_lib::B;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(io, process_capture)]
+
use std::env;
use std::io::prelude::*;
use std::io;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_variable)]
struct T { f: extern "Rust" fn() }
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+// pretty-expanded FIXME #23616
+
fn main() {
send::<Box<Foo>>(Box::new(Output(0)));
Test::<Box<Foo>>::foo(Box::new(Output(0)));
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
{|i| if 1 == i { }};
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[deny(dead_code)]
pub enum Foo {
Bar {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum X {
Foo(uint),
Bar(bool)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io)]
+
use std::old_io::Reader;
enum Wrapper<'a> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Matcher {
fn next_match(&mut self) -> Option<(uint, uint)>;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub type BigRat<T = int> = T;
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(asm)]
type History = Vec<&'static str>;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io, io)]
+
use std::env;
use std::process::Command;
use std::io::{self, Write};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
trait Foo { fn dummy(&self) { }}
struct Bar;
impl<'a> std::ops::Fn<(&'a (Foo+'a),)> for Bar {
- type Output = ();
extern "rust-call" fn call(&self, _: (&'a Foo,)) {}
}
+impl<'a> std::ops::FnMut<(&'a (Foo+'a),)> for Bar {
+ extern "rust-call" fn call_mut(&mut self, a: (&'a Foo,)) { self.call(a) }
+}
+
+impl<'a> std::ops::FnOnce<(&'a (Foo+'a),)> for Bar {
+ type Output = ();
+ extern "rust-call" fn call_once(self, a: (&'a Foo,)) { self.call(a) }
+}
+
struct Baz;
impl Foo for Baz {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::ops::Fn;
}
impl<'b> Fn<(&'b mut (Response+'b),)> for SendFile {
+ extern "rust-call" fn call(&self, (_res,): (&'b mut (Response+'b),)) {}
+}
+
+impl<'b> FnMut<(&'b mut (Response+'b),)> for SendFile {
+ extern "rust-call" fn call_mut(&mut self, (_res,): (&'b mut (Response+'b),)) {
+ self.call((_res,))
+ }
+}
+
+impl<'b> FnOnce<(&'b mut (Response+'b),)> for SendFile {
type Output = ();
- extern "rust-call" fn call(&self, (_res,): (&'b mut (Response+'b),)) {}
+ extern "rust-call" fn call_once(self, (_res,): (&'b mut (Response+'b),)) {
+ self.call((_res,))
+ }
}
impl<Rq: Request, Rs: Response> Ingot<Rq, Rs> for HelloWorld {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(warnings)]
struct S<T>(T);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let mut x: &[_] = &[1, 2, 3, 4];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
assert_eq!(count_members(&[1, 2, 3, 4]), 4);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub enum T {
T1(()),
T2(())
// no-prefer-dynamic
+// pretty-expanded FIXME #23616
+
#![feature(fs, process, env, path, rand)]
use std::env;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! inner {
($e:pat ) => ($e)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static mut n_mut: uint = 0;
static n: &'static uint = unsafe{ &n_mut };
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait MyTrait {
fn foo(&self);
}
// aux-build:issue-15562.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-15562" as i;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::iter::AdditiveIterator;
fn main() {
let x: [u64; 3] = [1, 2, 3];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(PartialEq)]
enum Test<'a> {
Slice(&'a int)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Clone)]
enum Test<'a> {
Slice(&'a int)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let mut array = [1, 2, 3];
let pie_slice = &array[1..2];
// If `Index` used an associated type for its output, this test would
// work more smoothly.
-#![feature(old_orphan_check)]
+// pretty-expanded FIXME #23616
+
+#![feature(old_orphan_check, core)]
use std::ops::Index;
impl<T> Index<(uint, uint)> for Mat<T> {
type Output = T;
- fn index<'a>(&'a self, &(row, col): &(uint, uint)) -> &'a T {
+ fn index<'a>(&'a self, (row, col): (uint, uint)) -> &'a T {
&self.data[row * self.cols + col]
}
}
impl<'a, T> Index<(uint, uint)> for &'a Mat<T> {
type Output = T;
- fn index<'b>(&'b self, index: &(uint, uint)) -> &'b T {
+ fn index<'b>(&'b self, index: (uint, uint)) -> &'b T {
(*self).index(index)
}
}
impl<T, M: Index<(uint, uint), Output=T>> Index<uint> for Row<M> {
type Output = T;
- fn index<'a>(&'a self, col: &uint) -> &'a T {
- &self.mat[(self.row, *col)]
+ fn index<'a>(&'a self, col: uint) -> &'a T {
+ &self.mat[(self.row, col)]
}
}
let m = Mat::new(vec!(1, 2, 3, 4, 5, 6), 3);
let r = m.row(1);
- assert!(r.index(&2) == &6);
+ assert!(r.index(2) == &6);
assert!(r[2] == 6);
assert!(r[2] == 6);
assert!(6 == r[2]);
assert_eq!(cc().unwrap(), 3);
assert_eq!(dd().unwrap(), 3);
- let i = box 32 as Box<A>;
+ let i = box 32i as Box<A>;
assert_eq!(i.aaa(), 3);
- let i = box 32 as Box<A>;
+ let i = box 32i as Box<A>;
assert_eq!(i.bbb(), 3);
- let i = box 32 as Box<A>;
+ let i = box 32i as Box<A>;
assert_eq!(i.ccc().unwrap(), 3);
- let i = box 32 as Box<A>;
+ let i = box 32i as Box<A>;
assert_eq!(i.ddd().unwrap(), 3);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![deny(warnings)]
#![allow(unused_imports)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum NestedEnum {
First,
Second,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
static mut DROP_RAN: bool = false;
//
// regression test for the model lexer handling the DOTDOTDOT syntax (#15877)
+// pretty-expanded FIXME #23616
+
pub fn main() {
match 5_usize {
1_usize...5_usize => {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unsafe_destructor)]
+// pretty-expanded FIXME #23616
+
+#![feature(unsafe_destructor, rustc_private)]
extern crate serialize;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
static mut DROP_COUNT: uint = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let mut buf = Vec::new();
|c: u8| buf.push(c);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Empty;
// This used to cause an ICE
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
if true { return }
match () {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(hash)]
+
use std::hash::{SipHasher, hash};
#[derive(Hash)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
use std::thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait MatrixRow { fn dummy(&self) { }}
struct Mat;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
static _x: int = 1<<2;
}
// aux-build:issue-16643.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-16643" as i;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let x: (int, &[int]) = (2, &[1, 2]);
assert_eq!(match x {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, core)]
// Test that unboxing shim for calling rust-call ABI methods through a
// trait box works and does not cause an ICE.
struct Foo { foo: u32 }
impl FnMut<()> for Foo {
- type Output = u32;
extern "rust-call" fn call_mut(&mut self, _: ()) -> u32 { self.foo }
}
-impl FnMut<(u32,)> for Foo {
+impl FnOnce<()> for Foo {
type Output = u32;
+ extern "rust-call" fn call_once(mut self, _: ()) -> u32 { self.call_mut(()) }
+}
+
+/////////////////////////////////////////////////////////////////////////
+
+impl FnMut<(u32,)> for Foo {
extern "rust-call" fn call_mut(&mut self, (x,): (u32,)) -> u32 { self.foo + x }
}
-impl FnMut<(u32,u32)> for Foo {
+impl FnOnce<(u32,)> for Foo {
type Output = u32;
+ extern "rust-call" fn call_once(mut self, args: (u32,)) -> u32 { self.call_mut(args) }
+}
+
+/////////////////////////////////////////////////////////////////////////
+
+impl FnMut<(u32,u32)> for Foo {
extern "rust-call" fn call_mut(&mut self, (x, y): (u32, u32)) -> u32 { self.foo + x + y }
}
+impl FnOnce<(u32,u32)> for Foo {
+ type Output = u32;
+ extern "rust-call" fn call_once(mut self, args: (u32,u32)) -> u32 { self.call_mut(args) }
+}
+
fn main() {
let mut f = box Foo { foo: 42 } as Box<FnMut() -> u32>;
assert_eq!(f.call_mut(()), 42);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
#![feature(box_patterns)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = [1, 2, 3];
let y = x;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::any::Any;
fn foo(_: &u8) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(collections)]
+
extern crate collections;
use std::collections::HashMap;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum pattern { tabby, tortoiseshell, calico }
enum breed { beagle, rottweiler, pug }
type name = String;
// Test that regionck creates the right region links in the pattern
// binding of a for loop
+// pretty-expanded FIXME #23616
+
fn foo<'a>(v: &'a [uint]) -> &'a uint {
for &ref x in v { return x; }
unreachable!()
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static X2: u64 = -1 as u16 as u64;
static Y2: u64 = -1 as u32 as u64;
const X: u64 = -1 as u16 as u64;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::fs::File;
use std::io::{self, BufReader, Read};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
struct Leak<'a> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const X1: &'static [u8] = &[b'1'];
const X2: &'static [u8] = b"1";
const X3: &'static [u8; 1] = &[b'1'];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static mut DROPPED: [bool; 2] = [false, false];
struct A(uint);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, io)]
use std::io::{self, Write};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
fn main() {
let _: &Str = &"x";
}
// Test that astconv doesn't forget about mutability of &mut str
+// pretty-expanded FIXME #23616
+
fn main() {
fn foo<T: ?Sized>(_: &mut T) {}
let _f: fn(&mut str) = foo;
// aux-build:issue-17662.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-17662" as i;
use std::marker;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const FOO: uint = 3;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::marker;
use std::cell::UnsafeCell;
// aux-build:issue-17718.rs
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
extern crate "issue-17718" as other;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Person {
type string;
fn dummy(&self) { }
// Test that generating drop glue for Box<str> doesn't ICE
+// pretty-expanded FIXME #23616
+
fn f(s: Box<str>) -> Box<str> {
s
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Aaa { fn dummy(&self) { } }
impl<'a> Aaa for &'a mut (Aaa + 'a) {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
use std::marker::PhantomData;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
assert_eq!(match [0u8; 1024] {
_ => 42_usize,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, std_misc)]
use std::thunk::Thunk;
// Test that we can parse where clauses on various forms of tuple
// structs.
+// pretty-expanded FIXME #23616
+
struct Bar<T>(T) where T: Copy;
struct Bleh<T, U>(T, U) where T: Copy, U: Sized;
struct Baz<T> where T: Copy {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
({return},);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, std_misc)]
use std::thunk::Thunk;
// Issue #1821 - Don't recurse trying to typecheck this
+// pretty-expanded FIXME #23616
+
enum t {
foo(Vec<t>)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Cursor<'a>(::std::marker::PhantomData<&'a ()>);
trait CursorNavigator {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const X: &'static str = "12345";
fn test(s: String) -> bool {
// Test that wrapping an unsized struct in an enum which gets optimised does
// not ICE.
+// pretty-expanded FIXME #23616
+
struct Str {
f: [u8]
}
// Test that non-static methods can be assigned to local variables as
// function pointers.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn foo(&self) -> uint;
}
// Check that trans doesn't ICE when translating an array repeat
// expression with a count of 1 and a non-Copy element type.
+// pretty-expanded FIXME #23616
+
fn main() {
let _ = [Box::new(1_usize); 1];
}
// translating the def ID of the trait during AST decoding.
// aux-build:issue-18501.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-18501" as issue;
fn main() {
// impl.
// aux-build:issue-18514.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-18514" as ice;
use ice::{Tr, St};
// Test that coercing bare fn's that return a zero sized type to
// a closure doesn't cause an LLVM ERROR
+// pretty-expanded FIXME #23616
+
struct Foo;
fn uint_to_foo(_: uint) -> Foo {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io)]
+
use std::old_io::FileType;
pub fn main() {
// once closure as an optimization by trans. This used to hit an
// incorrect assert.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod a {
pub type rust_task = uint;
pub mod rustrt {
// Test that param substitutions from the correct environment are
// used when translating unboxed closure calls.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
pub fn inside<F: Fn()>(c: F) {
c.call(());
// Test that the self param space is not used in a conflicting
// manner by unboxed closures within a default method on a trait
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
trait Tr {
// Test that we don't panic on a RefCell borrow conflict in certain
// code paths involving unboxed closures.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
// aux-build:issue-18711.rs
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Eq, PartialEq, PartialOrd, Ord)]
enum Test<'a> {
Int(&'a int),
// Test that regionck uses the right memcat for patterns in for loops
// and doesn't ICE.
+// pretty-expanded FIXME #23616
+
fn main() {
for &&x in Some(&0_usize).iter() {
assert_eq!(x, 0)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod foo {
pub mod bar {
pub mod baz {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub trait Borrow<Borrowed: ?Sized> {
fn borrow(&self) -> &Borrowed;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Str([u8]);
#[derive(Clone)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
pub trait Handler {
fn handle(&self, &mut String);
// Test that a partially specified trait object with unspecified associated
// type does not ICE.
+// pretty-expanded FIXME #23616
+
trait Foo {
type A;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
fn foo<T, F: FnOnce(T) -> T>(f: F) {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Trait<Input> {
type Output;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Trait<Input> {
type Output;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct MyStruct { field: usize }
struct Nested { nested: MyStruct }
struct Mix2 { nested: ((usize,),) }
// except according to those terms.
// aux-build:issue_19293.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_19293;
use issue_19293::{Foo, MyEnum};
// aux-build:issue-19340-1.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-19340-1" as lib;
use lib::Homura;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Homura {
Madoka {
name: String,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait T {
unsafe extern "Rust" fn foo(&self);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Base {
fn dummy(&self) { }
}
// reasonable examples) let to ambiguity errors about not being able
// to infer sufficient type information.
+// pretty-expanded FIXME #23616
+
fn main() {
let n = 0;
let it = Some(1_usize).into_iter().inspect(|_| {n;});
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait PoolManager {
type C;
fn dummy(&self) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait PoolManager {
type C;
fn dummy(&self) { }
// Issue 1974
// Don't double free the condition allocation
+// pretty-expanded FIXME #23616
+
pub fn main() {
let s = "hej".to_string();
while s != "".to_string() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
fn main() {
let mut escaped = String::from_str("");
for c in '\u{10401}'.escape_unicode() {
// Test that `<Type as Trait>::Output` and `Self::Output` are accepted as type annotations in let
// bindings
+// pretty-expanded FIXME #23616
+
trait Int {
fn one() -> Self;
fn leading_zeros(self) -> uint;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(core,unboxed_closures)]
#[allow(dead_code)]
struct Foo;
impl<'a> Fn<(&'a (),)> for Foo {
+ extern "rust-call" fn call(&self, (_,): (&(),)) {}
+}
+
+impl<'a> FnMut<(&'a (),)> for Foo {
+ extern "rust-call" fn call_mut(&mut self, (_,): (&(),)) {}
+}
+
+impl<'a> FnOnce<(&'a (),)> for Foo {
type Output = ();
- extern "rust-call" fn call(&self, (_,): (&(),)) {}
+ extern "rust-call" fn call_once(self, (_,): (&(),)) {}
}
fn main() {}
// Check that associated types are `Sized`
+// pretty-expanded FIXME #23616
+
trait Trait {
type Output;
// except according to those terms.
// ignore-aarch64
+#![feature(std_misc, os)]
#[cfg(unix)]
fn main() {
// <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.
+// pretty-expanded FIXME #23616
+
#![feature(link_llvm_intrinsics)]
extern {
// Regression test for Issue #20343.
+// pretty-expanded FIXME #23616
+
#![deny(dead_code)]
struct B { b: u32 }
// aux-build:issue_20389.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_20389;
struct Foo;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Foo<T> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Trait {
fn method(self) -> int;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread;
fn main() {
// Test that overloaded calls work with zero arity closures
+// pretty-expanded FIXME #23616
+
fn main() {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let functions: [Box<Fn() -> Option<()>>; 1] = [Box::new(|| None)];
// A reduced version of the rustbook ice. The problem this encountered
// had to do with trans ignoring binders.
+// pretty-expanded FIXME #23616
+
+#![feature(os)]
+
use std::iter;
use std::os;
use std::fs::File;
// UFCS-style calls to a method in `Trait` where `Self` was bound to a
// trait object of type `Trait`. See also `ufcs-trait-object.rs`.
+// pretty-expanded FIXME #23616
+
use std::fmt;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(non_camel_case_types)]
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait T0 {
type O;
fn dummy(&self) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait T0 {
type O;
fn dummy(&self) { }
// Regression test for #20797.
+// pretty-expanded FIXME #23616
+
+#![feature(convert)]
+
use std::default::Default;
use std::io;
use std::fs;
-use std::path::{PathBuf, Path};
+use std::path::PathBuf;
pub trait PathExtensions {
fn is_dir(&self) -> bool { false }
}
}
-fn foo() {
- let mut walker: Subpaths<Recursive> = Subpaths::walk(&PathBuf::new("/home")).unwrap();
+fn _foo() {
+ let _walker: Subpaths<Recursive> = Subpaths::walk(&PathBuf::from("/home")).unwrap();
}
fn main() {}
// <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.
+// pretty-expanded FIXME #23616
+
#![feature(box_patterns)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
struct NT(str);
struct DST { a: u32, b: str }
// insufficient type propagation caused the type of the iterator to be
// incorrectly unified with the `*const` type to which it is coerced.
+// pretty-expanded FIXME #23616
+
use std::ptr;
trait IntoIterator {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[forbid(raw_pointer_derive)]
#[derive(Copy)]
struct Test(*const i32);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::sync::Arc;
fn main() {
// Make sure that "bare sequences" don't ICE in follow checking
+// pretty-expanded FIXME #23616
+
macro_rules! bare {
$($id:expr),+ => ( $($id)+ )
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let v = vec![1, 2, 3];
let boxed: Box<Iterator<Item=i32>> = Box::new(v.into_iter());
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![no_implicit_prelude]
trait Iterator {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use ::std::ops::RangeFull;
fn test<T : Clone>(arg: T) -> T {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Hash)]
struct Foo {
a: Vec<bool>,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use m::{START, END};
fn main() {
// Test that the requirement (in `Bar`) that `T::Bar : 'static` does
// not wind up propagating to `T`.
+// pretty-expanded FIXME #23616
+
pub trait Foo {
type Bar;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
if let Ok(x) = "3.1415".parse() {
assert_eq!(false, x <= 0.0);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test(it: &mut Iterator<Item=i32>) {
for x in it {
assert_eq!(x, 1)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
static NONE: Option<((), &'static u8)> = None;
let ptr = unsafe {
// subtyping of projection types that resulted in an unconstrained
// region, yielding region inference failures.
+// pretty-expanded FIXME #23616
+
fn main() { }
fn foo<'a>(s: &'a str) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static foo: [uint; 3] = [1, 2, 3];
static slice_1: &'static [uint] = &foo;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::thread::Builder;
use std::thunk::Thunk;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A<X> {
fn dummy(&self, arg: X);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait DigitCollection: Sized {
type Iter: Iterator<Item = u8>;
fn digit_iter(self) -> Self::Iter;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
use std::mem;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::marker::{PhantomData, PhantomFn};
pub struct Handle<T, I>(T, I);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
match 42 {
x if x < 7 => (),
// Regression test for Issue #22536: If a type implements Copy, then
// moving it must not zero the original memory.
+// pretty-expanded FIXME #23616
+
trait Resources {
type Buffer: Copy;
fn foo(&self) {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(fs, net, fs_walk)]
+
use std::{fs, net};
fn assert_both<T: Send + Sync>() {}
// Test transitive analysis for associated types. Collected types
// should be normalized and new obligations generated.
+// pretty-expanded FIXME #23616
+
use std::borrow::{ToOwned, Cow};
fn assert_send<T: Send>(_: T) {}
// can successfully deal with a "deep" structure, which the drop-check
// was hitting a recursion limit on at one point.
+// pretty-expanded FIXME #23616
+
#![allow(non_camel_case_types)]
pub fn noop_fold_impl_item() -> SmallVector<ImplItem> {
// Test transitive analysis for associated types. Collected types
// should be normalized and new obligations generated.
+// pretty-expanded FIXME #23616
+
trait Foo {
type A;
fn foo(&self) {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Send {
fn f(&self);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait clam<A> {
fn get(self) -> A;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait clam<A> { fn get(self) -> A; }
trait foo<A> {
fn bar<B,C:clam<A>>(&self, c: C) -> B;
// Testing that the B's are resolved
+// pretty-expanded FIXME #23616
+
trait clam<A> { fn get(self) -> A; }
struct foo(int);
// aux-build:issue_2316_a.rs
// aux-build:issue_2316_b.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_2316_b;
use issue_2316_b::cloth;
// instantiates all the methods, even those that could not otherwise
// be called.
+// pretty-expanded FIXME #23616
+
struct Foo {
x: i32
}
// aux-build:issue-2380.rs
+// pretty-expanded FIXME #23616
+
extern crate a;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
extern crate collections;
use std::collections::VecDeque;
// aux-build:issue-2414-a.rs
// aux-build:issue-2414-b.rs
+// pretty-expanded FIXME #23616
+
extern crate b;
pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _foo = 100;
const quux: int = 5;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct c1<T> {
x: T,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct c1<T> {
x: T,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Pair { f: int, g: int }
pub fn main() {
// aux-build:issue_2472_b.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_2472_b;
use issue_2472_b::{S, T};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct socket {
sock: int,
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct font<'a> {
fontbuf: &'a Vec<u8> ,
}
// aux-build:issue-2526.rs
+// pretty-expanded FIXME #23616
+
#![allow(unused_imports)]
extern crate issue_2526;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct C {
x: uint,
}
// Tests that impls are allowed to have looser, more permissive bounds
// than the traits require.
+// pretty-expanded FIXME #23616
+
trait A {
fn b<C:Sync,D>(&self, x: C) -> C;
}
// aux-build:issue-2631-a.rs
+// pretty-expanded FIXME #23616
+
extern crate req;
use req::request;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f() {
let _x: uint = loop { loop { break; } };
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
//
// ignore-lexer-test FIXME #15883
-#![feature(unsafe_destructor)]
+#![feature(unsafe_destructor, std_misc)]
pub type Task = int;
// aux-build:issue_2723_a.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_2723_a;
use issue_2723_a::f;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
use std::cell::Cell;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
use std::cell::Cell;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct CMap<'a> {
buf: &'a [u8],
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn thing<'r>(x: &'r [int]) -> &'r [int] { x }
pub fn main() {
// Minimized version of issue-2804.rs. Both check that callee IDs don't
// clobber the previous node ID in a macro expr
+#![feature(collections)]
+
extern crate collections;
use std::collections::HashMap;
fn add_interfaces(managed_ip: String, device: HashMap<String, int>) {
- println!("{}, {}", managed_ip, device["interfaces".to_string()]);
+ println!("{}, {}", managed_ip, device["interfaces"]);
}
pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(collections)]
+#![feature(rustc_private)]
+
extern crate collections;
extern crate serialize;
fn add_interfaces(store: int, managed_ip: String, device: HashMap<String, json::Json>)
-> Vec<(String, object)> {
- match device["interfaces".to_string()]
- {
+ match device["interfaces"] {
Json::Array(ref interfaces) =>
{
interfaces.iter().map(|interface| {
_ =>
{
println!("Expected list for {} interfaces, found {}", managed_ip,
- device["interfaces".to_string()]);
+ device["interfaces"]);
Vec::new()
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
struct Cat {
// except according to those terms.
-/// Map representation
+// Map representation
+
+#![feature(old_io)]
use std::old_io;
use std::fmt;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait bar<T> {
fn get_bar(&self) -> T;
}
// aux-build:issue-3012-1.rs
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, libc)]
extern crate socketlib;
extern crate libc;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, collections)]
extern crate collections;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum what { }
fn what_to_string(x: what) -> String
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
type Connection = Box<FnMut(Vec<u8>) + 'static>;
fn f() -> Option<Connection> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = 1;
let y = 1;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn Matrix4<T>(m11: T, m12: T, m13: T, m14: T,
m21: T, m22: T, m23: T, m24: T,
m31: T, m32: T, m33: T, m34: T,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct thing { x: int, }
impl Drop for thing {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn quux<T>(x: T) -> T { let f = id::<T>; return f(x); }
fn id<T>(x: T) -> T { return x; }
// rustc --test ignores2.rs && ./ignores2
#![allow(unknown_features)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, old_path, std_misc)]
use std::old_path::{Path};
use std::old_path;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = 1_usize;
let y = || x;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = &Some(1);
match x {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(collections)]
+
extern crate collections;
use std::collections::HashMap;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Canvas {
fn add_point(&self, point: &int);
fn add_points(&self, shapes: &[int]) {
// that are already linked in. Using WriterUtil allows us to use the write_line
// method.
+#![feature(core)]
+
use std::fmt;
use std::iter::repeat;
use std::slice;
// rustc --test match_borrowed_str.rs.rs && ./match_borrowed_str.rs
+// pretty-expanded FIXME #23616
+
fn compare(x: &str, y: &str) -> bool {
match x {
"foo" => y == "foo",
// except according to those terms.
#![allow(unknown_features)]
+#![feature(std_misc)]
use std::thread::Thread;
use std::sync::mpsc::Sender;
// Incorrect struct size computation in the FFI, because of not taking
// the alignment of elements into account.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
use libc::{c_uint, uint32_t, c_void};
// Issue Name: pub method preceded by attribute can't be parsed
// Abstract: Visibility parsing failed when compiler parsing
+#![feature(core)]
+
use std::f64;
#[derive(Copy)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum PureCounter { PureCounterVariant(uint) }
fn each<F>(thing: PureCounter, blk: F) where F: FnOnce(&uint) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(path_statement)]
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn vec_peek<'r, T>(v: &'r [T]) -> &'r [T] {
&v[1..5]
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
enum State { BadChar, BadSyntax }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(PartialEq)]
struct Bike {
name: String,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A {
fn a_method(&self);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ops::Add;
trait Positioned<S> {
// except according to those terms.
// aux-build:issue_3979_traits.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_3979_traits;
use issue_3979_traits::{Positioned, Movable};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Positioned {
fn SetX(&mut self, int);
fn X(&self) -> int;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct HasNested {
nest: Vec<Vec<int> > ,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(rustc_private)]
extern crate serialize;
// Issue #4036: Test for an issue that arose around fixing up type inference
// byproducts in vtable records.
+// pretty-expanded FIXME #23616
+
+#![feature(rustc_private)]
+
extern crate serialize;
use serialize::{json, Decodable};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _id: &Mat2<f64> = &Matrix::identity(1.0);
}
// aux-build:issue-4208-cc.rs
+// pretty-expanded FIXME #23616
+
extern crate numeric;
use numeric::{sin, Angle};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo;
impl Foo {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(io)]
+
use std::io;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _foo = [0; 2*4];
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io)]
+
use std::old_io::println;
use std::sync::mpsc::channel;
use std::thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::sync::mpsc::channel;
use std::thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { &v[i..j] }
pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::env;
pub fn main() {
// aux-build:issue-4545.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-4545" as somelib;
pub fn main() { somelib::mk::<int>(); }
// Ensures that destructors are run for expressions of the form "e;" where
// `e` is a type which requires a destructor.
+// pretty-expanded FIXME #23616
+
#![allow(path_statement)]
struct A { n: int }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, libc)]
extern crate libc;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait U { fn f(self); }
impl U for isize { fn f(self) {} }
pub fn main() { 4.f(); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct Scheduler {
/// The event loop used to drive the scheduler and perform I/O
event_loop: Box<int>
// regression test for issue 4875
+// pretty-expanded FIXME #23616
+
pub struct Foo<T> {
data: T,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Regression test for issue #5239
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _f = |ref x: int| { *x };
let foo = 10;
// enough for trans to consider this as non-monomorphic,
// which led to various assertions and failures in turn.
+// pretty-expanded FIXME #23616
+
struct S<'a> {
v: &'a int
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct A(bool);
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const INVALID_ENUM : u32 = 0;
const INVALID_VALUE : u32 = 1;
// aux-build:issue-5518.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-5518" as other;
fn main() {}
// aux-build:issue-5521.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-5521" as foo;
fn bar(a: foo::map) {
if false {
panic!();
} else {
- let _b = &(*a)[2];
+ let _b = &(*a)[&2];
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Enum {
Foo { foo: uint },
Bar { bar: uint }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::default::Default;
pub struct X<T> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo<T: ::std::cmp::PartialEq>(_t: T) { }
pub fn main() { }
}
pub fn main() {
- let inner = 5;
+ let inner: int = 5;
let outer = Outer::new(&inner as &Inner);
outer.inner.print();
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unreachable_code)]
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct TwoDoubles {
r: f64,
i: f64
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
extern {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub mod foo {
use super::Bar;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct T (&'static [int]);
static t : T = T (&[5, 4, 3]);
pub fn main () {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub use local as local_alias;
pub mod local { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io)]
+
use std::old_io;
trait B {
fn f(&self);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f<T>() -> bool {
enum E<T> { V(T) }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Either<T, U> { Left(T), Right(U) }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, collections)]
extern crate collections;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![deny(type_limits)]
pub fn main() {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn swap<F>(f: F) -> Vec<int> where F: FnOnce(Vec<int>) -> Vec<int> {
let x = vec!(1, 2, 3);
f(x)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub trait OpInt { fn call(&mut self, int, int) -> int; }
impl<F> OpInt for F where F: FnMut(int, int) -> int {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Tests that everything still compiles and runs fine even when
// we reorder the bounds.
+// pretty-expanded FIXME #23616
+
trait A {
fn a(&self) -> uint;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(PartialEq)]
struct A { x: uint }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
Bar(int),
Baz,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub mod Bar {
pub struct Foo {
v: int,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_patterns)]
#![feature(box_syntax)]
// Ensures that destructors are run for expressions of the form "let _ = e;"
// where `e` is a type which requires a destructor.
+// pretty-expanded FIXME #23616
+
struct Foo;
struct Bar { x: int }
struct Baz(int);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::intrinsics;
/// Returns the size of a type
// aux-build:iss.rs
+// pretty-expanded FIXME #23616
+
#![crate_id="issue-6919"]
extern crate issue6919_3;
// aux-build:issue-7178.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-7178" as cross_crate_self;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
const FOO: f64 = 10.0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo<T: 'static>(_: T) {}
fn bar<T>(x: &'static T) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unreachable_code)]
fn foo() -> bool { false }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*
#7519 ICE pattern matching unit in function argument
*/
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn new() -> bool { false }
fn dummy(&self) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub mod a {
pub struct Foo { a: usize }
}
// Regression test for issue 7660
// rvalue lifetime too short when equivalent `match` works
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
extern crate collections;
use std::collections::HashMap;
let mut m: HashMap<int, A> = HashMap::new();
m.insert(1, A(0, 0));
- let A(ref _a, ref _b) = m[1];
- let (a, b) = match m[1] { A(ref _a, ref _b) => (_a, _b) };
+ let A(ref _a, ref _b) = m[&1];
+ let (a, b) = match m[&1] { A(ref _a, ref _b) => (_a, _b) };
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_imports, dead_code)]
mod test1 {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*
#7673 Polymorphically creating traits barely works
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(advanced_slice_patterns)]
use std::ops::Add;
// aux-build:issue-7899.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-7899" as testcrate;
fn main() {
// aux-build:issue-8044.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-8044" as minimal;
use minimal::{BTree, leaf};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*
#8171 Self is not recognised as implementing kinds in default method implementations
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A {
fn dummy(&self) { }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A {
fn dummy(&self) { }
}
// aux-build:issue-8259.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-8259" as other;
static a: other::Foo<'static> = other::Foo::A;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E {
Foo{f: int},
Bar,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E {
Foo{f: int, b: bool},
Bar,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let x = match Some(1) {
ref _y @ Some(_) => 1,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io, io)]
+
use std::old_io;
fn foo(a: &mut old_io::Writer) {
// aux-build:issue_8401.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_8401;
pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::num::Int;
use std::thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
match &[(Box::new(5),Box::new(7))] {
ps => {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
enum Either {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub struct UninterpretedOption_NamePart {
name_part: Option<String>,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f<T, F>(g: F) -> T where F: FnOnce() -> T { g() }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! sty {
($t:ty) => (stringify!($t))
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::default::Default;
struct X { pub x: uint }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
use std::sync::mpsc::{channel, Receiver};
// doesn't cause capture. Making this macro hygienic (as I've done)
// could very well make this test case completely pointless....
+// pretty-expanded FIXME #23616
+
enum T {
A(int),
B(uint)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static mut DROP: int = 0;
static mut DROP_S: int = 0;
static mut DROP_T: int = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn assert_repr_eq<T: std::fmt::Debug>(obj : T, expected : String) {
assert_eq!(expected, format!("{:?}", obj));
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! silly_macro {
() => (
pub mod Qux {
// aux-build:issue_9123.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_9123;
pub fn main() {}
// aux-build:issue_9188.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_9188;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static DATA:&'static [&'static str] = &["my string"];
fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct A<'a> {
a: &'a [String],
b: Option<&'a [String]>,
+// pretty-expanded FIXME #23616
+
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Base: Base2 + Base3{
fn foo(&self) -> String;
fn foo1(&self) -> String;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io, std_misc)]
+
use std::sync::mpsc::{TryRecvError, channel};
use std::old_io::timer::Timer;
use std::thread::Thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod a {
pub enum Enum<T> {
A(T),
impl X for int {}
pub struct Z<'a>(Enum<&'a (X+'a)>);
- fn foo() { let x = 42; let z = Z(Enum::A(&x as &X)); let _ = z; }
+ fn foo() { let x: int = 42; let z = Z(Enum::A(&x as &X)); let _ = z; }
}
mod b {
}
fn bar() {
- let x = 42;
+ let x: int = 42;
let _y = Y { x: Some(&x as &X) };
}
}
pub trait X { fn f(&self); }
impl X for int { fn f(&self) {} }
pub struct Z<'a>(Option<&'a (X+'a)>);
- fn main() { let x = 42; let z = Z(Some(&x as &X)); let _ = z; }
+ fn main() { let x: int = 42; let z = Z(Some(&x as &X)); let _ = z; }
}
pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
use std::cell::Cell;
// aux-build:issue-9906.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-9906" as testmod;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert_eq!((0 + 0u8) as char, '\0');
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
const S: uint = 23 as uint; [0; S]; ()
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_variables)]
trait Bar {
// aux-build:issue-9968.rs
+// pretty-expanded FIXME #23616
+
extern crate "issue-9968" as lib;
use lib::{Trait, Struct};
// except according to those terms.
// aux-build:issue2170lib.rs
+// pretty-expanded FIXME #23616
+
extern crate issue2170lib;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
// This used to cause an ICE because the retslot for the "return" had the wrong type
fn testcase<'a>() -> Box<Iterator<Item=usize> + 'a> {
return Box::new((0..3).map(|i| { return i; }));
// aux-build:issue_3136_a.rc
+// pretty-expanded FIXME #23616
+
extern crate issue_3136_a;
pub fn main() {}
// aux-build:issue_9155.rs
+// pretty-expanded FIXME #23616
+
extern crate issue_9155;
struct Baz;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(collections)]
+
use std::string::String;
fn test_stack_assign() {
// for completeness since .rs files linked from .rc files support this
// notation to specify their module's attributes
-#![feature(custom_attribute)]
+// pretty-expanded FIXME #23616
+
+#![feature(custom_attribute, libc)]
#![allow(unused_attribute)]
#![attr1 = "val"]
#![attr2 = "val"]
+// pretty-expanded FIXME #23616
+
mod foo {
pub fn baz() { }
}
// Test to see that the element type of .cloned() can be inferred
// properly. Previously this would fail to deduce the type of `sum`.
+// pretty-expanded FIXME #23616
+
#![feature(core)]
use std::iter::AdditiveIterator;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f(_a: Vec<int> ) { }
pub fn main() { f(vec!(1, 2, 3, 4, 5)); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
// mod -> module
// match -> match
+// pretty-expanded FIXME #23616
+
pub fn main() {
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
fn user(_i: int) {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// aux-build:kinds_in_metadata.rs
+// pretty-expanded FIXME #23616
+
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
'foo: loop {
loop {
+// pretty-expanded FIXME #23616
+
struct Large {a: int,
b: int,
c: int,
// Issue #1818
+// pretty-expanded FIXME #23616
+
fn lp<T, F>(s: String, mut f: F) -> T where F: FnMut(String) -> T {
while false {
let r = f(s);
// Make sure #1399 stays fixed
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, core)]
struct A { a: Box<isize> }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = 3_usize;
let ref y = x;
// except according to those terms.
// shouldn't affect evaluation of $ex:
+// pretty-expanded FIXME #23616
+
macro_rules! bad_macro {
($ex:expr) => ({let _x = 9; $ex})
}
// ignore-android: FIXME(#10379)
// ignore-windows: std::dynamic_lib does not work on Windows well
+#![feature(std_misc, old_path)]
+
extern crate "linkage-visibility" as foo;
pub fn main() {
// This is ok because we often use the trailing underscore to mean 'prime'
+// pretty-expanded FIXME #23616
+
#[forbid(non_camel_case_types)]
type Foo_ = int;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![forbid(non_camel_case_types)]
#![forbid(non_upper_case_globals)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unreachable_code)]
#![allow(unused_variable)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unreachable_code)]
fn test() {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn take(x: int) -> int {x}
fn the_loop() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(trace_macros, log_syntax)]
// make sure these macros can be used as in the various places that
// compile-flags:-C debug-assertions=no
// exec-env:RUST_LOG=logging-enabled-debug=debug
+// pretty-expanded FIXME #23616
+
+#![feature(rustc_private)]
+
#[macro_use]
extern crate log;
// exec-env:RUST_LOG=logging-enabled=info
+// pretty-expanded FIXME #23616
+
+#![feature(rustc_private)]
+
#[macro_use]
extern crate log;
// longer happens by enabling logging for *this* crate and then invoking a
// function in an external crate which will panic when logging is enabled.
+// pretty-expanded FIXME #23616
+
extern crate logging_right_crate;
pub fn main() {
// exec-env:RUST_LOG=debug
// compile-flags:-C debug-assertions=y
+#![feature(old_io, rustc_private)]
+
#[macro_use]
extern crate log;
// this test will trigger "output during runtime initialization" to make sure
// that the bug isn't re-introduced.
+// pretty-expanded FIXME #23616
+
pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_variable)]
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _i = 0_usize;
loop {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/* Make sure a loop{} can be the tailexpr in the body
of a diverging function */
// Issue #12512.
+// pretty-expanded FIXME #23616
+
fn main() {
let mut foo = Vec::new();
'foo: for i in &[1, 2, 3] {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
'outer: loop {
let _: i32 = loop { break 'outer };
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct S;
// Ensure S is moved, not copied, on assignment.
impl Drop for S { fn drop(&mut self) { } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = vec!(10, 20, 30);
let mut sum = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! do_block{
($val:block) => {$val}
}
// aux-build:macro_crate_def_only.rs
+// pretty-expanded FIXME #23616
+
#[macro_use] #[no_link]
extern crate macro_crate_def_only;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn increment(x: uint) -> uint {
x + 1
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! foo2 {
() => {
"foo"
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
vec![1_usize, 2, 3].len();
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! overly_complicated {
($fnname:ident, $arg:ident, $ty:ty, $body:block, $val:expr, $pat:pat, $res:path) =>
({
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! four {
() => (4)
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct A;
macro_rules! make_thirteen_method {() => (fn thirteen(&self)->int {13})}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! list {
( ($($id:ident),*) ) => (());
( [$($id:ident),*] ) => (());
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! higher_order {
(subst $lhs:tt => $rhs:tt) => ({
macro_rules! anon { $lhs => $rhs }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! mypat {
() => (
Some('y')
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod m {
pub type t = int;
}
// compile-flags: --cfg foo
+// pretty-expanded FIXME #23616
+
#[cfg(foo)]
macro_rules! foo { () => (1) }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[cfg(foo)]
macro_rules! foo { () => (1) }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
macro_rules! expr { ($e: expr) => { $e } }
// aux-build:macro_with_super_1.rs
+// pretty-expanded FIXME #23616
+
#[macro_use]
extern crate macro_with_super_1;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct NewBool(bool);
enum Direction {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unnecessary_allocation)]
fn f1(ref_string: &str) -> String {
// except according to those terms.
// n.b. This was only ever failing with optimization disabled.
+// pretty-expanded FIXME #23616
+
fn a() -> int { match return 1 { 2 => 3, _ => panic!() } }
pub fn main() { a(); }
// regression test for issue #5625
+// pretty-expanded FIXME #23616
+
enum E {
Foo{f : int},
Bar
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum E {
Foo{f : int},
Bar
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
B { b1: int, bb1: int},
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct X { x: int }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct X { x: int }
pub fn main() {
+// pretty-expanded FIXME #23616
+
mod m1 {
pub enum foo { foo1, foo2, }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let value = Some(1);
assert_eq!(match value {
+// pretty-expanded FIXME #23616
+
fn altsimple(f: int) { match f { _x => () } }
pub fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unused_variable)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test1() {
// from issue 6338
match ((1, "a".to_string()), (2, "b".to_string())) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const s: int = 1;
const e: int = 42;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::sync::Mutex;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut v = Some(22);
match v {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Rec {
f: int
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn destructure(x: Option<int>) -> int {
match x {
None => 0,
// around this problem locally by renaming the constant in the `use`
// form to an uppercase identifier that placates the lint.
+// pretty-expanded FIXME #23616
+
#![deny(non_upper_case_globals)]
pub const A : int = 97;
// Issue #53
+// pretty-expanded FIXME #23616
+
pub fn main() {
match "test" { "not-test" => panic!(), "test" => (), _ => panic!() }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo{
f : int,
}
+// pretty-expanded FIXME #23616
+
enum color {
rgb(int, int, int),
rgba(int, int, int, int),
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(advanced_slice_patterns)]
fn match_vecs<'a, T>(l1: &'a [T], l2: &'a [T]) -> &'static str {
// Tests that matching rvalues with drops does not crash.
+// pretty-expanded FIXME #23616
+
pub fn main() {
match vec!(1, 2, 3) {
x => {
// except according to those terms.
// pp-exact - Make sure we print all the attributes
+// pretty-expanded FIXME #23616
+
#![allow(unused_attribute)]
#![feature(custom_attribute)]
// Check that we successfully handle methods where the `self` type has
// an early-bound lifetime. Issue #18208.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
use std::marker;
// type is `&mut [u8]`, passes in a pointer to the lvalue and not a
// temporary. Issue #19147.
+// pretty-expanded FIXME #23616
+
+#![feature(core, old_io)]
+
use std::mem;
use std::slice;
use std::old_io::IoResult;
// winnowing stage of method resolution failed to handle an associated
// type projection.
+// pretty-expanded FIXME #23616
+
#![feature(associated_types)]
trait Hasher {
///////////////////////////////////////////////////////////////////////////
+// pretty-expanded FIXME #23616
+
trait MakeString {
fn make_string(&self) -> String;
}
// know not to stop at the blanket, we have to recursively evaluate
// the `T:Foo` bound.
+// pretty-expanded FIXME #23616
+
use std::marker::Sized;
// Note: this must be generic for the problem to show up
// Test method calls with self as an argument (cross-crate)
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Test method calls with self as an argument (cross-crate)
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Test method calls with self as an argument
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Test method calls with self as an argument
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Test that we pick which version of `foo` to run based on the
// type that is (ultimately) inferred for `x`.
+// pretty-expanded FIXME #23616
+
trait foo {
fn foo(&self) -> i32;
}
// version will run (note that the `push` occurs after the call to
// `foo()`).
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Test that we select between traits A and B. To do that, we must
// consider the `Sized` bound.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
trait A {
fn foo(self);
}
fn main() {
let x: [int; 4] = [1,2,3,4];
- let xptr = x.as_slice() as *const _;
+ let xptr = x.as_slice() as *const [int];
xptr.foo();
}
// Test that we can use method notation to call methods based on a
// where clause type, and not only type parameters.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn foo(&self) -> i32;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct S<T> {
contents: T,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f() -> int {
mod m {
pub fn g() -> int { 720 }
// pretty-print such view items. If that happens again, this should
// begin failing.
+// pretty-expanded FIXME #23616
+
mod m {
pub fn f() -> Vec<int> { Vec::new() }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod m {
pub struct S {
pub x: int,
+// pretty-expanded FIXME #23616
+
trait vec_monad<A> {
fn bind<B, F>(&self, f: F ) -> Vec<B> where F: FnMut(&A) -> Vec<B> ;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::marker::MarkerTrait;
trait Serializer : MarkerTrait {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test(foo: int) { assert!((foo == 10)); }
pub fn main() { let x = 10; test(x); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(box_syntax)]
fn main() {
// except according to those terms.
// Issue #922
+// pretty-expanded FIXME #23616
+
fn f2<F>(_thing: F) where F: FnOnce() { }
fn f<F>(thing: F) where F: FnOnce() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::string::String;
struct StringBuffer {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let y: int = 42;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
pub fn main() {
// aux-build:moves_based_on_type_lib.rs
+// pretty-expanded FIXME #23616
+
extern crate moves_based_on_type_lib;
use moves_based_on_type_lib::f;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = 10;
let y = x;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::fmt::Debug;
trait MyTrait<T> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::fmt::Debug;
use std::default::Default;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*
* This is a multi-line oldcomment.
*/
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f<T:PartialEq + PartialOrd>(_: T) {
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn foo(&self, mut x: int) -> int {
let val = x;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _x: &mut [int] = &mut [ 1, 2, 3 ];
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test1() {
let mut ints = [0; 32];
ints[0] += 1;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum colour { red, green, blue, }
enum tree { children(Box<list>), leaf(colour), }
// aux-build:namespaced_enum_emulate_flat.rs
+// pretty-expanded FIXME #23616
+
extern crate namespaced_enum_emulate_flat;
use namespaced_enum_emulate_flat::{Foo, A, B, C};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub use Foo::*;
use nest::{Bar, D, E, F};
// aux-build:namespaced_enums.rs
+// pretty-expanded FIXME #23616
+
extern crate namespaced_enums;
fn _f(f: namespaced_enums::Foo) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod m2 {
pub enum Foo {
A,
// aux-build:namespaced_enums.rs
+// pretty-expanded FIXME #23616
+
extern crate namespaced_enums;
use namespaced_enums::Foo;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
A,
B(int),
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
match -5 {
-5 => {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/* This test checks that nested comments are supported
/*
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
struct b {
i: int,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*
#7770 ICE with sibling methods containing same-name-enum containing
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo { foo: bool, bar: Option<int>, baz: int }
pub fn main() {
//
// Issue #8587
+// pretty-expanded FIXME #23616
+
pub struct X;
impl X {
// aux-build:nested_item.rs
+// pretty-expanded FIXME #23616
+
extern crate nested_item;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, alloc)]
// Tests that the new `box` syntax works with unique pointers.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
pub fn main() {
let s = "\u{2603}";
assert_eq!(s, "☃");
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let _a: *const int = 3 as *const int;
let _a: *mut int = 3 as *mut int;
// expression
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+// pretty-expanded FIXME #23616
+
fn unique() -> Box<FnMut()+'static> { return Box::new(|| ()); }
pub fn main() {
// expression
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
+// pretty-expanded FIXME #23616
+
fn unique() -> Box<FnMut()+'static> { Box::new(|| ()) }
pub fn main() {
// Tests for the new |args| expr lambda syntax
+// pretty-expanded FIXME #23616
+
fn f<F>(i: int, f: F) -> int where F: FnOnce(int) -> int { f(i) }
fn g<G>(_g: G) where G: FnOnce() { }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Clone)]
struct myvec<X>(Vec<X> );
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
// Make sure the destructor is run for newtype structs.
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
use libc::c_int;
// aux-build:newtype_struct_xc.rs
+// pretty-expanded FIXME #23616
+
extern crate newtype_struct_xc;
use newtype_struct_xc::Au;
// aux-build:newtype_struct_xc.rs
+// pretty-expanded FIXME #23616
+
extern crate newtype_struct_xc;
pub fn main() {
// except according to those terms.
// Issue #901
+// pretty-expanded FIXME #23616
+
mod libc {
extern {
pub fn printf(x: ());
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() { let x = (); match x { () => { } } }
// compile-flags: -Z no-landing-pads
+// pretty-expanded FIXME #23616
+
use std::thread;
static mut HIT: bool = false;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! quote_tokens { () => (()) }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct X {
repr: int
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::cell::Cell;
struct C<'a> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main()
{
let all_nuls1 = "\0\x00\u{0}\u{0}";
// then we simply express the enum as just a pointer and not wrap it
// in a struct.
+// pretty-expanded FIXME #23616
+
use std::mem;
#[inline(never)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
enum E<T> { Thing(int, T), Nothing((), ((), ()), [i8; 0]) }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum blah { a, b, }
fn or_alt(q: blah) -> int {
// necessary. Testing the methods of the impls is done within the source
// file for each numeric type.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::ops::Add;
use std::num::ToPrimitive;
// Test that `Box<Test>` is equivalent to `Box<Test+'static>`, both in
// fields and fn arguments.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Test {
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Test {
// Test that the lifetime from the enclosing `&` is "inherited"
// through the `Box` struct.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Test {
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Test {
// Test that the lifetime from the enclosing `&` is "inherited"
// through the `MyBox` struct.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Test {
// Test that the lifetime of the enclosing `&` is used for the object
// lifetime bound.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Test {
// Test for using an object with an associated type binding as the
// instantiation for a generic type with a bound.
+// pretty-expanded FIXME #23616
+
trait SomeTrait {
type SomeType;
}
fn main() {
- let x = box 22 as Box<Wrap>;
+ let x = box 22isize as Box<Wrap>;
println!("x={}", x.get());
let y = x.wrap();
}
// Check that a trait is still object-safe (and usable) if it has
// methods with by-value self so long as they require `Self : Sized`.
+// pretty-expanded FIXME #23616
+
trait Counter {
fn tick(&mut self) -> u32;
fn get(self) -> u32 where Self : Sized;
// Check that a trait is still object-safe (and usable) if it has
// generic methods so long as they require `Self : Sized`.
+// pretty-expanded FIXME #23616
+
trait Counter {
fn tick(&mut self) -> u32;
fn with<F:FnOnce(u32)>(&self, f: F) where Self : Sized;
// Check that a trait is still object-safe (and usable) if it has
// methods that return `Self` so long as they require `Self : Sized`.
+// pretty-expanded FIXME #23616
+
trait Counter {
fn new() -> Self where Self : Sized;
fn tick(&mut self) -> u32;
// Test that we can coerce an `@Object` to an `&Object`
+// pretty-expanded FIXME #23616
+
trait Foo {
fn foo(&self) -> uint;
fn bar(&mut self) -> uint;
}
pub fn main() {
- let mut x = 22;
+ let mut x: uint = 22;
let obj = &mut x as &mut Foo;
do_it_mut(obj);
do_it_imm(obj, 23);
// closed over do not contain managed values, and thus the boxes do
// not have headers.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// closed over contain managed values. This implies that the boxes
// will have headers that must be skipped over.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Testing guarantees provided by once functions.
+// pretty-expanded FIXME #23616
+
use std::sync::Arc;
fn foo<F:FnOnce()>(blk: F) {
// Why one-tuples? Because macros.
+// pretty-expanded FIXME #23616
+
pub fn main() {
match ('c',) {
(x,) => {
// Testcase for issue #130, operator associativity.
+// pretty-expanded FIXME #23616
+
pub fn main() { assert!((3 * 5 / 2 == 7)); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
use std::cmp;
use std::ops;
impl ops::Index<bool> for Point {
type Output = int;
- fn index(&self, x: &bool) -> &int {
- if *x {
+ fn index(&self, x: bool) -> &int {
+ if x {
&self.x
} else {
&self.y
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(collections)]
+
pub fn main() {
let thing = "{{ f }}";
let f = thing.find_str("{{");
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
use std::cell::Cell;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum blah { a(int, int, uint), b(int, int), c, }
fn or_alt(q: blah) -> int {
// in ORDER matching up to when it ran.
// Correct order is: matched, inner, outer
+// pretty-expanded FIXME #23616
+
static mut ORDER: [uint; 3] = [0, 0, 0];
static mut INDEX: uint = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
#[cfg(target_os = "macos")]
//ignore-dragonfly
//ignore-bitrig
-#![feature(asm)]
+#![feature(asm, old_io, std_misc)]
use std::old_io::process::Command;
use std::env;
//ignore-dragonfly
//ignore-bitrig
-#![feature(asm)]
+#![feature(asm, old_io)]
use std::old_io::process::Command;
use std::env;
// ignore-android: FIXME (#20004)
-#![feature(asm)]
+#![feature(asm, old_io)]
use std::old_io::process::Command;
use std::env;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
pub struct Foo {
f1: int,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unused_variable)]
#![allow(unknown_features)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ops::Deref;
struct DerefArray<'a, T:'a> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::rc::Rc;
use std::ops::Deref;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ops::Deref;
struct DerefWithHelper<H, T> {
// aux-build:overloaded_autoderef_xc.rs
+// pretty-expanded FIXME #23616
+
extern crate overloaded_autoderef_xc;
fn main() {
// except according to those terms.
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, collections, core)]
use std::cell::RefCell;
use std::rc::Rc;
// Tests calls to closure arguments where the closure takes 1 argument.
// This is a bit tricky due to rust-call ABI.
+// pretty-expanded FIXME #23616
+
fn foo(f: &mut FnMut(int) -> int) -> int {
f(22)
}
// Tests calls to closure arguments where the closure takes 2 arguments.
// This is a bit tricky due to rust-call ABI.
+// pretty-expanded FIXME #23616
+
fn foo(f: &mut FnMut(int, int) -> int) -> int {
f(1, 2)
}
// Tests calls to closure arguments where the closure takes 0 arguments.
// This is a bit tricky due to rust-call ABI.
+// pretty-expanded FIXME #23616
+
fn foo(f: &mut FnMut() -> int) -> int {
f()
}
// Tests that nested vtables work with overloaded calls.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::marker::PhantomData;
use std::ops::Fn;
struct G<A>(PhantomData<A>);
impl<'a, A: Add<i32, Output=i32>> Fn<(A,)> for G<A> {
- type Output = i32;
-
extern "rust-call" fn call(&self, (arg,): (A,)) -> i32 {
arg.add(1)
}
}
+impl<'a, A: Add<i32, Output=i32>> FnMut<(A,)> for G<A> {
+ extern "rust-call" fn call_mut(&mut self, args: (A,)) -> i32 { self.call(args) }
+}
+
+impl<'a, A: Add<i32, Output=i32>> FnOnce<(A,)> for G<A> {
+ type Output = i32;
+ extern "rust-call" fn call_once(self, args: (A,)) -> i32 { self.call(args) }
+}
+
fn main() {
// ICE trigger
(G(PhantomData))(1);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(lang_items, unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(lang_items, unboxed_closures, core)]
use std::ops::{Fn, FnMut, FnOnce};
}
impl FnMut<(i32,)> for S1 {
- type Output = i32;
extern "rust-call" fn call_mut(&mut self, (z,): (i32,)) -> i32 {
self.x * self.y * z
}
}
+impl FnOnce<(i32,)> for S1 {
+ type Output = i32;
+ extern "rust-call" fn call_once(mut self, args: (i32,)) -> i32 {
+ self.call_mut(args)
+ }
+}
+
struct S2 {
x: i32,
y: i32,
}
impl Fn<(i32,)> for S2 {
- type Output = i32;
extern "rust-call" fn call(&self, (z,): (i32,)) -> i32 {
self.x * self.y * z
}
}
+impl FnMut<(i32,)> for S2 {
+ extern "rust-call" fn call_mut(&mut self, args: (i32,)) -> i32 { self.call(args) }
+}
+
+impl FnOnce<(i32,)> for S2 {
+ type Output = i32;
+ extern "rust-call" fn call_once(self, args: (i32,)) -> i32 { self.call(args) }
+}
+
struct S3 {
x: i32,
y: i32,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::ops::{FnMut};
}
impl FnMut<()> for S {
- type Output = i32;
extern "rust-call" fn call_mut(&mut self, (): ()) -> i32 {
self.x * self.y
}
}
+impl FnOnce<()> for S {
+ type Output = i32;
+ extern "rust-call" fn call_once(mut self, args: ()) -> i32 { self.call_mut(args) }
+}
+
fn main() {
let mut s = S {
x: 3,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::cell::Cell;
use std::ops::{Deref, DerefMut};
use std::vec::Vec;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(collections)]
+
use std::cell::RefCell;
use std::rc::Rc;
use std::string::String;
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::ops::Index;
struct AssociationList<K,V> {
}
}
-impl<K: PartialEq + std::fmt::Debug, V:Clone> Index<K> for AssociationList<K,V> {
+impl<'a, K: PartialEq + std::fmt::Debug, V:Clone> Index<&'a K> for AssociationList<K,V> {
type Output = V;
fn index<'a>(&'a self, index: &K) -> &'a V {
list.push(foo.clone(), 22);
list.push(bar.clone(), 44);
- assert!(list[foo] == 22);
- assert!(list[bar] == 44);
+ assert!(list[&foo] == 22);
+ assert!(list[&bar] == 44);
- assert!(list[foo] == 22);
- assert!(list[bar] == 44);
+ assert!(list[&foo] == 22);
+ assert!(list[&bar] == 44);
}
// Test overloaded indexing combined with autoderef.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, core)]
use std::ops::{Index, IndexMut};
impl Index<int> for Foo {
type Output = int;
- fn index(&self, z: &int) -> &int {
- if *z == 0 {
+ fn index(&self, z: int) -> &int {
+ if z == 0 {
&self.x
} else {
&self.y
}
impl IndexMut<int> for Foo {
- fn index_mut(&mut self, z: &int) -> &mut int {
- if *z == 0 {
+ fn index_mut(&mut self, z: int) -> &mut int {
+ if z == 0 {
&mut self.x
} else {
&mut self.y
// Test using overloaded indexing when the "map" is stored in a
// field. This caused problems at some point.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::ops::Index;
struct Foo {
impl Index<int> for Foo {
type Output = int;
- fn index(&self, z: &int) -> &int {
- if *z == 0 {
+ fn index(&self, z: int) -> &int {
+ if z == 0 {
&self.x
} else {
&self.y
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::ops::{Index, IndexMut};
struct Foo {
impl Index<int> for Foo {
type Output = int;
- fn index(&self, z: &int) -> &int {
- if *z == 0 {
+ fn index(&self, z: int) -> &int {
+ if z == 0 {
&self.x
} else {
&self.y
}
impl IndexMut<int> for Foo {
- fn index_mut(&mut self, z: &int) -> &mut int {
- if *z == 0 {
+ fn index_mut(&mut self, z: int) -> &mut int {
+ if z == 0 {
&mut self.x
} else {
&mut self.y
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f<T: 'static>(_x: T) {}
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[repr(packed)]
struct Foo {
bar: u8,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
#[repr(packed)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
#[repr(packed)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
#[repr(packed)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[repr(packed)]
struct Foo {
bar: u8,
// aux-build:packed.rs
+// pretty-expanded FIXME #23616
+
extern crate packed;
use std::mem;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
#[repr(packed)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
#[repr(packed)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
#[repr(packed)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::thread;
static mut dropped: bool = false;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
type T;
fn foo() -> Box<<Self as Foo>::T>;
// Test parsing binary operators after macro invocations.
+// pretty-expanded FIXME #23616
+
#![feature(macro_rules)]
macro_rules! id {
+// pretty-expanded FIXME #23616
+
mod foo {
pub fn bar(_offset: uint) { }
}
// pattern-bound var is an upvar (when translating
// the for-each body)
+// pretty-expanded FIXME #23616
+
fn foo(src: uint) {
match Some(src) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(rustc_private)]
+
extern crate arena;
use arena::Arena;
// this checks that a pred with a non-bool return
// type is rejected, even if the pred is never used
+// pretty-expanded FIXME #23616
+
fn bad(_a: int) -> int { return 37; } //~ ERROR Non-boolean return type
pub fn main() { }
// aux-build:priv-impl-prim-ty.rs
+// pretty-expanded FIXME #23616
+
extern crate "priv-impl-prim-ty" as bar;
pub fn main() {
// Check we do the correct privacy checks when we import a name and there is an
// item with that name in both the value and type namespaces.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
#![allow(unused_imports)]
// aux-build:privacy_reexport.rs
+// pretty-expanded FIXME #23616
+
extern crate privacy_reexport;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub mod test2 {
// This used to generate an ICE (make sure that default functions are
// parented to their trait to find the first private thing as the trait).
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct cat {
meows : uint,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct cat {
meows : uint,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io)]
+
use std::old_io::Command;
use std::env;
// intact.
// ignore-aarch64
+#![feature(path, fs, os, io, old_path)]
use std::io::prelude::*;
use std::io;
// Test coercions between pointers which don't do anything fancy like unsizing.
+// pretty-expanded FIXME #23616
+
pub fn main() {
// &mut -> &
let x: &mut int = &mut 42;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::transmute;
mod a {
// Issue #14660
+// pretty-expanded FIXME #23616
+
mod bleh {
macro_rules! foo {
() => {
// Issue #17436
+// pretty-expanded FIXME #23616
+
mod bleh {
macro_rules! foo {
() => {
// aux-build:pub_use_xcrate1.rs
// aux-build:pub_use_xcrate2.rs
+// pretty-expanded FIXME #23616
+
extern crate pub_use_xcrate2;
use pub_use_xcrate2::Foo;
// aux-build:pub_use_mods_xcrate.rs
+// pretty-expanded FIXME #23616
+
#![allow(unused_imports)]
extern crate pub_use_mods_xcrate;
// Check that functions can modify local state.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// good as the old one. Check out issue #21672, #21595 and #21649 for
// more details.
+// pretty-expanded FIXME #23616
+
fn main() {
let xs = (0..8).map(|i| i == 1u64).collect::<Vec<_>>();
assert_eq!(xs[1], true);
// Test range syntax.
+// pretty-expanded FIXME #23616
+
fn foo() -> int { 42 }
// Test that range syntax works in return statements
// Test that the precedence of ranges is correct
+// pretty-expanded FIXME #23616
+
struct Foo {
foo: uint,
}
+// pretty-expanded FIXME #23616
+
struct Point {x: int, y: int, z: int}
fn f(p: Point) { assert!((p.z == 12)); }
// Ideally this would be revised to use no_std, but for now it serves
// well enough to reproduce (and illustrate) the bug from #16687.
+#![feature(alloc)]
+
extern crate alloc;
use alloc::heap;
+// pretty-expanded FIXME #23616
+
struct Point {x: int, y: int}
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
struct Point {x: int, y: int}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
struct Rect {x: int, y: int, w: int, h: int}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum t1 { a(int), b(uint), }
struct T2 {x: t1, y: int}
enum t3 { c(T2, uint), }
// aux-build:reexport-should-still-link.rs
+// pretty-expanded FIXME #23616
+
extern crate "reexport-should-still-link" as foo;
pub fn main() {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod a {
pub fn f() {}
pub fn g() {}
// except according to those terms.
// aux-build:reexported_static_methods.rs
+// pretty-expanded FIXME #23616
+
extern crate reexported_static_methods;
use reexported_static_methods::Foo;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Point {
x: int,
y: int
// Test that the compiler considers the 'a bound declared in the
// trait. Issue #20890.
+// pretty-expanded FIXME #23616
+
trait Foo<'a> {
type Value: 'a;
// Test that the compiler considers the 'static bound declared in the
// trait. Issue #20890.
+// pretty-expanded FIXME #23616
+
trait Foo {
type Value: 'static;
fn dummy(&self) { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo(x: &[int]) -> int {
x[0]
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo(x: &[int]) -> int {
x[0]
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// A very limited test of the "bottom" region
+// pretty-expanded FIXME #23616
+
fn produce_static<T>() -> &'static T { panic!(); }
fn foo<T>(_x: &T) -> &uint { produce_static() }
// A test where we (successfully) close over a reference into
// an object.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, core)]
struct closure_box<'a> {
cl: Box<FnMut() + 'a>,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum ast<'a> {
num(uint),
add(&'a ast<'a>, &'a ast<'a>)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum ast<'a> {
num(uint),
add(&'a ast<'a>, &'a ast<'a>)
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct ctxt<'tcx> {
x: &'tcx i32
}
// Test lifetimes are linked properly when we create dependent region pointers.
// Issue #3148.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_patterns)]
#![feature(box_syntax)]
// Test lifetimes are linked properly when we autoslice a vector.
// Issue #3148.
+// pretty-expanded FIXME #23616
+
fn subslice<F>(v: F) -> F where F: FnOnce() { v }
fn both<F>(v: F) -> F where F: FnOnce() {
// Issue #3148.
+// pretty-expanded FIXME #23616
+
fn subslice1<'r>(v: &'r [uint]) -> &'r [uint] { v }
fn both<'r>(v: &'r [uint]) -> &'r [uint] {
// Test lifetimes are linked properly when we take reference
// to interior.
+// pretty-expanded FIXME #23616
+
struct Foo(int);
pub fn main() {
// Here the lifetime of the `&` should be at least the
// lifetime parameters must be early bound in the type of the
// associated item.
+// pretty-expanded FIXME #23616
+
use std::marker;
pub enum Value<'v> {
// Tests that you can use an early-bound lifetime parameter as
// on of the generic parameters in a trait.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
}
impl<'t> MakerTrait for Box<Trait<'t>+'static> {
- fn mk() -> Box<Trait<'t>+'static> { box() (4,5) as Box<Trait> }
+ fn mk() -> Box<Trait<'t>+'static> {
+ let tup: Box<(int, int)> = box() (4,5);
+ tup as Box<Trait>
+ }
}
enum List<'l> {
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
+// pretty-expanded FIXME #23616
+
trait GetRef<'a> {
fn get(&self) -> &'a int;
}
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
+// pretty-expanded FIXME #23616
+
trait GetRef<'a, T> {
fn get(&self) -> &'a T;
}
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
+// pretty-expanded FIXME #23616
+
trait Get<T> {
fn get(&self) -> T;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Test that you can insert an explicit lifetime in explicit self.
+// pretty-expanded FIXME #23616
+
struct Foo {
f: uint
}
// Here, `f` is a function that takes a pointer `x` and a function
// `g`, where `g` requires its argument `y` to be in the same region
// that `x` is in.
+// pretty-expanded FIXME #23616
+
fn has_same_region(f: Box<for<'a> FnMut(&'a int, Box<FnMut(&'a int)>)>) {
// `f` should be the type that `wants_same_region` wants, but
// right now the compiler complains that it isn't.
// Issue #2263.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unused_variable)]
#![allow(unknown_features)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::swap;
pub fn main() {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn view<T>(x: &[T]) -> &[T] {x}
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn takes_two(x: &int, y: &int) -> int { *x + *y }
fn with<T, F>(f: F) -> T where F: FnOnce(&int) -> T {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn takes_two(x: &int, y: &int) -> int { *x + *y }
fn has_two<'a,'b>(x: &'a int, y: &'b int) -> int {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct boxed_int<'a> {
f: &'a int,
}
// Test an edge case in region inference: the lifetime of the borrow
// of `*x` must be extended to at least 'a.
+// pretty-expanded FIXME #23616
+
fn foo<'a,'b>(x: &'a &'b mut int) -> &'a int {
let y = &*x; // should be inferred to have type &'a &'b mut int...
// check that the &int here does not cause us to think that `foo`
// contains region pointers
+// pretty-expanded FIXME #23616
+
struct foo(Box<FnMut(&int)+'static>);
fn take_foo<T:'static>(x: T) {}
// region variables contained within (otherwise, region inference will
// give `x` a very short lifetime).
+// pretty-expanded FIXME #23616
+
static i: uint = 3;
fn foo<F:FnOnce()+'static>(_: F) {}
fn read(_: uint) { }
// add inference constraints that the operands of a binary operator
// should outlive the binary operation itself.
+// pretty-expanded FIXME #23616
+
pub struct P<'a> {
_ptr: *const &'a u8,
}
// Regression test for issue #22246 -- we should be able to deduce
// that `&'a B::Owned` implies that `B::Owned : 'a`.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
use std::ops::Deref;
// doing region-folding, when really all clients of the region-folding
// case only want to see FREE lifetime variables, not bound ones.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// This test verifies that temporary lifetime is correctly computed
// for static objects in enclosing scopes.
+// pretty-expanded FIXME #23616
+
use std::cmp::PartialEq;
fn f<T:PartialEq>(o: &mut Option<T>) {
// Test that region inference correctly links up the regions when a
// `ref` borrow occurs inside a fn argument.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
fn with<'a, F>(_: F) where F: FnOnce(&'a Vec<int>) -> &'a Vec<int> { }
// - Multiple lifetime parameters
// - Arenas
+#![feature(rustc_private, libc, collections)]
+
extern crate arena;
extern crate collections;
extern crate libc;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
use std::mem;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
use std::marker;
// should not upset the variance inference for actual occurrences of
// that lifetime in type expressions.
+// pretty-expanded FIXME #23616
+
pub trait HasLife<'a> {
fn dummy(&'a self) { } // just to induce a variance on 'a
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum roption<'a> {
a, b(&'a uint)
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn region_identity(x: &uint) -> &uint { x }
fn apply<T, F>(t: T, f: F) -> T where F: FnOnce(T) -> T { f(t) }
// started out with a longer lifetime and was reassigned to a shorter
// one (it should infer to be the intersection).
+// pretty-expanded FIXME #23616
+
fn foo(x: &int) {
let a = 1;
let mut z = x;
// started out with a longer lifetime and was reassigned to a shorter
// one (it should infer to be the intersection).
+// pretty-expanded FIXME #23616
+
fn foo(x: &int) {
let a = 1;
match x {
// attempting to bootstrap librustc with new destructor lifetime
// semantics.
+// pretty-expanded FIXME #23616
+
use std::collections::HashMap;
use std::cell::RefCell;
// changes were caught. However, those uses in the compiler could
// easily get changed or refactored away in the future.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn get<T>(opt: &Option<T>) -> &T {
match *opt {
Some(ref v) => v,
// wrong path. The new algorithm avoids this problem and hence this
// example typechecks correctly.
+// pretty-expanded FIXME #23616
+
enum ScopeChain<'a> {
Link(Scope<'a>),
End
#![allow(unknown_features)]
#![feature(box_syntax)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, core)]
struct closure_box<'a> {
cl: Box<FnMut() + 'a>,
// attempting to bootstrap libsyntax; it is adapted from
// `syntax::ext::tt::generic_extension`.
+// pretty-expanded FIXME #23616
+
pub struct E<'a> {
pub f: &'a u8,
}
// Note: see compile-fail/variance-regions-*.rs for the tests that check that the
// variance inference works in the first place.
+// pretty-expanded FIXME #23616
+
struct Contravariant<'a> {
f: &'a int
}
// This is covariant with respect to 'a, meaning that
// Covariant<'foo> <: Covariant<'static> because
// 'foo <= 'static
+// pretty-expanded FIXME #23616
+
struct Covariant<'a> {
f: extern "Rust" fn(&'a int)
}
// This test can't be a unit test in std,
// because it needs TempDir, which is in extra
+// pretty-expanded FIXME #23616
+
+#![feature(tempdir, path_ext)]
+
use std::ffi::CString;
use std::fs::{self, TempDir, File, PathExt};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
static FOO: [int; 4] = [32; 4];
static BAR: [int; 4] = [32, 32, 32, 32];
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
const foo: int = 4 >> 1;
enum bs { thing = foo }
pub fn main() { assert!((bs::thing as int == foo)); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
// Ensures that class dtors run if the object is inside an enum
+// pretty-expanded FIXME #23616
+
enum option<T> { none, some(T), }
fn f<T>() -> option<T> { return option::none; }
// just to make sure that `return` is only returning from the closure,
// not the surrounding function.
+// pretty-expanded FIXME #23616
+
static mut calls: uint = 0;
fn surrounding() {
+// pretty-expanded FIXME #23616
+
fn f() { let x: () = (); return x; }
pub fn main() { let _x = f(); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(start)]
+#![feature(start, os, std_misc, old_io)]
use std::ffi;
use std::old_io::process::{Command, ProcessOutput};
// exec-env:RUST_LOG=rust-log-filter/foo
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, std_misc, rustc_private)]
#[macro_use]
extern crate log;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(old_io)]
+
use std::old_io::process::Command;
use std::env;
// Test that we can use `Self` types in impls in the expected way.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Assert that `mut self` on an immediate value doesn't
// allow mutating the original - issue #10615.
+// pretty-expanded FIXME #23616
+
#[derive(Copy)]
struct Value {
n: int
// Ensure assigning an owned or managed variable to itself works. In particular,
// that we do not glue_drop before we glue_take (#3290).
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod a {
pub mod b {
pub mod a {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait MyTrait {
fn f(&self) -> Self;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(core, std_misc)]
use std::thread::Thread;
use std::sync::Mutex;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::thread::Thread;
use std::sync::mpsc::channel;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::sync::mpsc::{channel, Sender};
// tests that ctrl's type gets inferred properly
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections, into_cow)]
+
extern crate collections;
use std::collections::HashMap;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections, into_cow)]
+
extern crate collections;
use self::collections::BTreeMap;
// Test that a class with only sendable fields can be sent
+// pretty-expanded FIXME #23616
+
use std::sync::mpsc::channel;
struct foo {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn test<F>(f: F) -> uint where F: FnOnce(uint) -> uint {
return f(22);
}
// Test accessing cross-crate inlined items from multiple compilation units.
+// pretty-expanded FIXME #23616
+
extern crate sepcomp_cci_lib;
use sepcomp_cci_lib::{cci_fn, CCI_STATIC};
// Test accessing external items from multiple compilation units.
+// pretty-expanded FIXME #23616
+
#[link(name = "sepcomp-extern-lib")]
extern {
#[allow(ctypes)]
// Generate some code in the first compilation unit before declaring any
// modules. This ensures that the first module doesn't go into the same
// compilation unit as the top-level module.
+// pretty-expanded FIXME #23616
+
fn pad() -> uint { 0 }
mod b {
// Generate some code in the first compilation unit before declaring any
// modules. This ensures that the first module doesn't go into the same
// compilation unit as the top-level module.
+// pretty-expanded FIXME #23616
+
fn one() -> uint { 1 }
mod a {
// Test linking against a library built with -C codegen-units > 1
+// pretty-expanded FIXME #23616
+
extern crate sepcomp_lib;
use sepcomp_lib::a::one;
use sepcomp_lib::b::two;
// Test references to static items across compilation units.
+// pretty-expanded FIXME #23616
+
fn pad() -> uint { 0 }
const ONE: uint = 1;
// In any case, this test should let us know if enabling parallel codegen ever
// breaks unwinding.
+// pretty-expanded FIXME #23616
+
use std::thread;
fn pad() -> uint { 0 }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert!(("hello".to_string() < "hellr".to_string()));
assert!(("hello ".to_string() > "hello".to_string()));
// Test that we can do shifts by any integral type.
+// pretty-expanded FIXME #23616
+
struct Panolpy {
i8: i8,
i16: i16,
// Testing shifts for various combinations of integers
// Issue #1570
+// pretty-expanded FIXME #23616
+
pub fn main() {
test_misc();
test_expr();
// ignore-windows
+#![feature(old_io)]
+#![feature(os)]
+
use std::env;
use std::old_io::process::{Command, ExitSignal, ExitStatus};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum test { thing = -5 >> 1_usize }
pub fn main() {
assert_eq!(test::thing as int, -3);
// Be sure that when a SIGPIPE would have been received that the entire process
// doesn't die in a ball of fire, but rather it's gracefully handled.
+// pretty-expanded FIXME #23616
+
use std::env;
use std::io::prelude::*;
use std::io;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
use std::simd::{i32x4, f32x4, u32x4};
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(simd)]
use std::ops;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+#![feature(core)]
#![feature(simd)]
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(simd)]
#![allow(non_camel_case_types)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(simd)]
#[simd]
+// pretty-expanded FIXME #23616
+
enum clam<T> { a(T), }
pub fn main() { let c = clam::a(2); match c { clam::a::<int>(_) => { } } }
+// pretty-expanded FIXME #23616
+
enum clam<T> { a(T), }
pub fn main() { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(custom_derive)]
#[derive_Clone]
// Possibly-dynamic size of typaram should be cleared at pointer boundary.
+// pretty-expanded FIXME #23616
+
fn bar<T: Sized>() { }
fn foo<T>() { bar::<&T>() }
pub fn main() { }
// Possibly-dynamic size of typaram should be cleared at pointer boundary.
+// pretty-expanded FIXME #23616
+
fn bar<T: Sized>() { }
fn foo<T>() { bar::<Box<T>>() }
pub fn main() { }
// Test slicing expressions on slices and Vecs.
+// pretty-expanded FIXME #23616
+
fn main() {
let x: &[int] = &[1, 2, 3, 4, 5];
let cmp: &[int] = &[1, 2, 3, 4, 5];
// Test that if a slicing expr[..] fails, the correct cleanups happen.
+// pretty-expanded FIXME #23616
+
use std::thread;
struct Foo;
// Test that if a slicing expr[..] fails, the correct cleanups happen.
+// pretty-expanded FIXME #23616
+
use std::thread;
struct Foo;
// Test slicing sugar.
-#![feature(associated_types)]
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
extern crate core;
use core::ops::{Index, IndexMut, Range, RangeTo, RangeFrom, RangeFull};
impl Index<Range<Foo>> for Foo {
type Output = Foo;
- fn index(&self, index: &Range<Foo>) -> &Foo {
+ fn index(&self, index: Range<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
}
impl Index<RangeTo<Foo>> for Foo {
type Output = Foo;
- fn index(&self, index: &RangeTo<Foo>) -> &Foo {
+ fn index(&self, index: RangeTo<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
}
impl Index<RangeFrom<Foo>> for Foo {
type Output = Foo;
- fn index(&self, index: &RangeFrom<Foo>) -> &Foo {
+ fn index(&self, index: RangeFrom<Foo>) -> &Foo {
unsafe { COUNT += 1; }
self
}
}
impl Index<RangeFull> for Foo {
type Output = Foo;
- fn index(&self, _index: &RangeFull) -> &Foo {
+ fn index(&self, _index: RangeFull) -> &Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<Range<Foo>> for Foo {
- fn index_mut(&mut self, index: &Range<Foo>) -> &mut Foo {
+ fn index_mut(&mut self, index: Range<Foo>) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<RangeTo<Foo>> for Foo {
- fn index_mut(&mut self, index: &RangeTo<Foo>) -> &mut Foo {
+ fn index_mut(&mut self, index: RangeTo<Foo>) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<RangeFrom<Foo>> for Foo {
- fn index_mut(&mut self, index: &RangeFrom<Foo>) -> &mut Foo {
+ fn index_mut(&mut self, index: RangeFrom<Foo>) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<RangeFull> for Foo {
- fn index_mut(&mut self, _index: &RangeFull) -> &mut Foo {
+ fn index_mut(&mut self, _index: RangeFull) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*!
* Tests the range assertion wraparound case in trans::middle::adt::load_discr.
*/
// Smallest "hello world" with a libc runtime
-#![feature(intrinsics, lang_items, start, no_std)]
+// pretty-expanded FIXME #23616
+
+#![feature(intrinsics, lang_items, start, no_std, libc)]
#![no_std]
extern crate libc;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(non_ascii_idents)]
#![deny(non_snake_case)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
fn x(s: String, n: int) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
/*
Make sure we can spawn tasks that take different types of
parameters. This is based on a test case for #520 provided by Rob
// Issue #2040
+// pretty-expanded FIXME #23616
+
pub fn main() {
- let foo = 1;
+ let foo: int = 1;
assert_eq!(&foo as *const int, &foo as *const int);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(tempdir, path_ext)]
+
use std::fs::{File, TempDir};
use std::io::prelude::*;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(static_assert)]
#[static_assert]
// aux-build:static_fn_inline_xc_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate "static_fn_inline_xc_aux" as mycore;
use mycore::num;
// aux-build:static_fn_trait_xc_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate "static_fn_trait_xc_aux" as mycore;
use mycore::num;
// except according to those terms.
// aux-build:static-function-pointer-aux.rs
+// pretty-expanded FIXME #23616
+
extern crate "static-function-pointer-aux" as aux;
fn f(x: int) -> int { x }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f(x: int) -> int { x }
fn g(x: int) -> int { 2 * x }
+// pretty-expanded FIXME #23616
+
pub trait plus {
fn plus(&self) -> int;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Deserializer {
fn read_int(&self) -> int;
}
// aux-build:static-methods-crate.rs
+// pretty-expanded FIXME #23616
+
extern crate static_methods_crate;
use static_methods_crate::read;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod a {
pub trait Foo {
fn foo() -> Self;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub trait Number: NumConv {
fn from<T:Number>(n: T) -> Self;
}
// statics cannot. This ensures that there's some form of error if this is
// attempted.
+// pretty-expanded FIXME #23616
+
+#![feature(libc)]
+
extern crate libc;
#[link(name = "rust_test_helpers")]
// aux-build:static_mut_xc.rs
+// pretty-expanded FIXME #23616
+
extern crate static_mut_xc;
unsafe fn static_bound(_: &'static int) {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc, alloc)]
+
use std::sync;
fn assert_both<T: Sync + Send>() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let a: String = "this \
is a test".to_string();
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let x = "\\\\\
";
// except according to those terms.
// aux-build:xcrate_struct_aliases.rs
+// pretty-expanded FIXME #23616
+
extern crate xcrate_struct_aliases;
use xcrate_struct_aliases::{S, S2};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct S {
x: int,
y: int,
// aux-build:struct_destructuring_cross_crate.rs
+// pretty-expanded FIXME #23616
+
extern crate struct_destructuring_cross_crate;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
Bar {
a: int,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
Bar {
x: int,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo {
new: int,
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct S { f0: String, f1: int }
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct S {
f0: String,
f1: String,
// Checks that functional-record-update order-of-eval is as expected
// even when no Drop-implementations are involved.
+// pretty-expanded FIXME #23616
+
use std::sync::atomic::{Ordering, AtomicUsize, ATOMIC_USIZE_INIT};
struct W { wrapped: u32 }
// Checks that struct-literal expression order-of-eval is as expected
// even when no Drop-implementations are involved.
+// pretty-expanded FIXME #23616
+
use std::sync::atomic::{Ordering, AtomicUsize, ATOMIC_USIZE_INIT};
struct W { wrapped: u32 }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod foo {
pub enum Foo {
Bar { a: int }
// except according to those terms.
// aux-build:struct_variant_xc_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate struct_variant_xc_aux;
use struct_variant_xc_aux::Enum::StructVariant;
// except according to those terms.
// aux-build:struct_variant_xc_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate struct_variant_xc_aux;
use struct_variant_xc_aux::Enum::{StructVariant, Variant};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub mod a {
pub fn f() {}
pub mod b {
// There is some other borrowck bug, so we make the stuff not mut.
+// pretty-expanded FIXME #23616
+
use std::ops::Add;
trait Positioned<S> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(libc)]
+
extern crate libc;
pub fn main() {
// aux-build:svh-b.rs
// aux-build:svh-a-comment.rs
+// pretty-expanded FIXME #23616
+
extern crate a;
extern crate b;
// aux-build:svh-b.rs
// aux-build:svh-a-doc.rs
+// pretty-expanded FIXME #23616
+
extern crate a;
extern crate b;
// aux-build:svh-b.rs
// aux-build:svh-a-macro.rs
+// pretty-expanded FIXME #23616
+
extern crate a;
extern crate b;
// aux-build:svh-b.rs
// aux-build:svh-a-no-change.rs
+// pretty-expanded FIXME #23616
+
extern crate a;
extern crate b;
// aux-build:svh-b.rs
// aux-build:svh-a-redundant-cfg.rs
+// pretty-expanded FIXME #23616
+
extern crate a;
extern crate b;
// aux-build:svh-b.rs
// aux-build:svh-a-whitespace.rs
+// pretty-expanded FIXME #23616
+
extern crate a;
extern crate b;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::swap;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::swap;
pub fn main() {
// Issue #5041 - avoid overlapping memcpy when src and dest of a swap are the same
+// pretty-expanded FIXME #23616
+
use std::ptr;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_mut)]
#![feature(collections)]
// compile-flags: --cfg foo --cfg qux="foo"
+// pretty-expanded FIXME #23616
+
pub fn main() {
// check
if ! cfg!(foo) { panic!() }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
// This test is brittle!
// ignore-pretty - the pretty tests lose path information, breaking include!
macro_rules! indirect_line { () => ( line!() ) }
pub fn main() {
- assert_eq!(line!(), 25);
+ assert_eq!(line!(), 27);
assert!((column!() == 4));
- assert_eq!(indirect_line!(), 27);
+ assert_eq!(indirect_line!(), 29);
assert!((file!().ends_with("syntax-extension-source-utils.rs")));
assert_eq!(stringify!((2*3) + 5).to_string(), "( 2 * 3 ) + 5".to_string());
assert!(include!("syntax-extension-source-utils-files/includeme.\
// The Windows tests are wrapped in an extra module for some reason
assert!((m1::m2::where_am_i().ends_with("m1::m2")));
- assert!(match (45, "( 2 * 3 ) + 5") {
+ assert!(match (47, "( 2 * 3 ) + 5") {
(line!(), stringify!((2*3) + 5)) => true,
_ => false
})
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(optin_builtin_traits)]
+// pretty-expanded FIXME #23616
+
+#![feature(optin_builtin_traits, core)]
use std::marker::{MarkerTrait, Send};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
enum Tag<A> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
enum Tag<A,B> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem;
enum Tag {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use alder::*;
mod alder {
+// pretty-expanded FIXME #23616
+
fn foo() {
fn zed(_z: bar) { }
enum bar { nil, }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum color {
red = 1,
blue = 2,
// <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.
+// pretty-expanded FIXME #23616
+
use color::{red, green, blue, black, white, imaginary, purple, orange};
#[derive(Copy)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum colour { red(int, int), green, }
impl PartialEq for colour {
// use of tail calls causes arg slot leaks, issue #160.
+// pretty-expanded FIXME #23616
+
fn inner(dummy: String, b: bool) { if b { return inner(dummy, false); } }
pub fn main() {
+// pretty-expanded FIXME #23616
+
pub fn main() { assert!((even(42))); assert!((odd(45))); }
fn even(n: int) -> bool { if n == 0 { return true; } else { return odd(n - 1); } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
pub fn main() { test00(); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::sync::mpsc::{channel, Sender};
use std::thread::Thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
pub fn main() { test00(); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::sync::mpsc::{channel, Sender};
use std::thread::Thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::sync::mpsc::{channel, Sender};
use std::thread::Thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::sync::mpsc::{channel, Sender};
use std::thread::Thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
// Issue #922
// This test is specifically about spawning temporary closures.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
// no-pretty-expanded FIXME #15189
use std::thread::Thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::sync::mpsc::channel;
pub fn main() { test00(); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
use std::sync::mpsc::channel;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
#![allow(dead_assignment)]
use std::sync::mpsc::{channel, Sender};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
use std::sync::mpsc::{channel, Sender};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::sync::mpsc::channel;
// rustboot can't transmit nils across channels because they don't have
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(std_misc)]
+
use std::thread::Thread;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, std_misc)]
use std::thread::Thread;
use std::sync::mpsc::channel;
pub fn main() {
let (tx, rx) = channel::<uint>();
- let x: Box<_> = box 1;
+ let x: Box<int> = box 1;
let x_in_parent = &(*x) as *const int as uint;
let _t = Thread::spawn(move || {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, old_io, std_misc, io, set_panic, set_stdio)]
use std::io::prelude::*;
use std::io;
// quite quickly and it takes a few seconds for the sockets to get
// recycled.
+#![feature(old_io, io, std_misc)]
+
use std::old_io::{TcpListener, Listener, Acceptor, EndOfFile, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#![reexport_test_harness_main = "test_main"]
#![allow(unused_imports)]
+#![feature(old_io, std_misc, io)]
use std::old_io::*;
use std::old_io::test::*;
// ignore-openbsd system ulimit (Too many open files)
// exec-env:RUST_LOG=debug
+#![feature(rustc_private, libc, old_io, io, std_misc)]
+#![allow(deprecated, unused_must_use)]
+
#[macro_use]
extern crate log;
extern crate libc;
// they're in a different location than before. Hence, these tests are all run
// serially here.
+#![feature(old_io, old_path, os, old_fs)]
+
use std::old_path::{Path, GenericPath};
use std::old_io::fs::PathExtensions;
use std::old_io::{fs, TempDir};
// Issue #787
// Don't try to clean up uninitialized locals
+// pretty-expanded FIXME #23616
+
use std::thread;
fn test_break() { loop { let _x: Box<int> = break; } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(test)]
+
// compile-flags: --test
// no-pretty-expanded
extern crate test;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(std_misc)]
+
use std::thread::Thread;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(advanced_slice_patterns,)]
fn f<T,>(_: T,) {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
trait Foo : ::std::marker::MarkerTrait {
}
// trait exactly, as long as the implementation doesn't demand *more* bounds
// than the trait.
+// pretty-expanded FIXME #23616
+
trait A {
fn foo<T: Eq + Ord>(&self);
}
// ignore-pretty
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, std_misc)]
#![feature(unboxed_closures)]
use std::sync::Arc;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
trait U : ::std::marker::MarkerTrait {}
trait T<X: U> { fn get(self) -> X; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
trait I { fn i(&self) -> Self; }
trait A<T:I> : ::std::marker::MarkerTrait {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait connection {
fn read(&self) -> int;
}
//
// See issue #18209.
+// pretty-expanded FIXME #23616
+
pub trait Foo {
fn load_from() -> Box<Self>;
fn load() -> Box<Self> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(box_syntax)]
+#![allow(unknown_features)]
+#![feature(box_syntax, old_io, io)]
use std::io::{self, Write};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn foo(&self);
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A<T> {
fn g<U>(&self, x: T, y: U) -> (T, U) { (x, y) }
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A<T> {
fn g(&self, x: T) -> T { x }
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A {
fn g<T>(&self, x: T, y: T) -> (T, T) { (x, y) }
}
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A<T> {
fn g(&self, x: uint) -> uint { x }
fn h(&self, x: T) { }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A {
fn g(&self) -> int { 10 }
}
// aux-build:trait_default_method_xc_aux_2.rs
+// pretty-expanded FIXME #23616
+
extern crate "trait_default_method_xc_aux" as aux;
extern crate "trait_default_method_xc_aux_2" as aux2;
use aux::A;
// aux-build:trait_default_method_xc_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate "trait_default_method_xc_aux" as aux;
use aux::{A, TestEquality, Something};
use aux::B;
// between the builtin rules for Sized and the where clause. Issue
// #20959.
+// pretty-expanded FIXME #23616
+
fn foo<K>(x: Option<K>)
where Option<K> : Sized
{
+// pretty-expanded FIXME #23616
+
trait to_str {
fn to_string_(&self) -> String;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub mod Foo {
pub trait Trait {
fn foo(&self);
// Test calling methods on an impl for a bare trait.
// aux-build:traitimpl.rs
+// pretty-expanded FIXME #23616
+
extern crate traitimpl;
use traitimpl::Bar;
// aux-build:trait_inheritance_auto_xc_2_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate "trait_inheritance_auto_xc_2_aux" as aux;
// aux defines impls of Foo, Bar and Baz for A
// aux-build:trait_inheritance_auto_xc_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate "trait_inheritance_auto_xc_aux" as aux;
use aux::{Foo, Bar, Baz, Quux};
// Testing that this impl turns A into a Quux, because
// A is already a Foo Bar Baz
+// pretty-expanded FIXME #23616
+
impl<T:Foo + Bar + Baz> Quux for T { }
trait Foo { fn f(&self) -> int; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo { fn f(&self) -> int; }
trait Bar : Foo { fn g(&self) -> int; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo { fn f(&self) -> int; }
trait Bar : Foo { fn g(&self) -> int; }
trait Baz : Bar { fn h(&self) -> int; }
// Testing that we can cast to a subtrait and call subtrait
// methods. Not testing supertrait methods
+// pretty-expanded FIXME #23616
+
trait Foo {
fn f(&self) -> int;
}
// Testing that supertrait methods can be called on subtrait object types
+// pretty-expanded FIXME #23616
+
trait Foo {
fn f(&self) -> int;
}
// aux-build:trait_inheritance_cross_trait_call_xc_aux.rs
+// pretty-expanded FIXME #23616
+
extern crate "trait_inheritance_cross_trait_call_xc_aux" as aux;
use aux::Foo;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo { fn f(&self) -> int; }
trait Bar : Foo { fn g(&self) -> int; }
// B and C both require A, so D does as well, twice, but that's just fine
+// pretty-expanded FIXME #23616
+
trait A { fn a(&self) -> int; }
trait B: A { fn b(&self) -> int; }
trait C: A { fn c(&self) -> int; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A { fn a(&self) -> int; }
trait B: A { fn b(&self) -> int; }
trait C: A { fn c(&self) -> int; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait A { fn a(&self) -> int; }
trait B: A { fn b(&self) -> int; }
trait C: A { fn c(&self) -> int; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::cmp::{PartialEq, PartialOrd};
use std::num::NumCast;
// Extending Num and using inherited static methods
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::cmp::PartialOrd;
use std::num::NumCast;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::cmp::PartialOrd;
use std::num::NumCast;
// A more complex example of numeric extensions
+#![feature(core)]
+
use std::cmp::{PartialEq, PartialOrd};
use std::num::NumCast;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(core)]
+
use std::cmp::{PartialEq, PartialOrd};
use std::num::NumCast;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::cmp::PartialEq;
use std::num::NumCast;
// aux-build:trait_inheritance_overloading_xc.rs
+// pretty-expanded FIXME #23616
+
extern crate trait_inheritance_overloading_xc;
use trait_inheritance_overloading_xc::{MyNum, MyInt};
// Test for issue #4183: use of Self in supertraits.
+// pretty-expanded FIXME #23616
+
use std::num::Float as StdFloat;
pub static FUZZY_EPSILON: f64 = 0.1;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo { fn f(&self) -> int; }
trait Bar : Foo { fn g(&self) -> int; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub trait MyNum {
fn from_int(int) -> Self;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
pub trait MyEq : ::std::marker::MarkerTrait { }
pub trait MyNum : ::std::marker::MarkerTrait {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub trait Add<RHS,Result> {
fn add(&self, rhs: &RHS) -> Result;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Panda<T> {
fn chomp(&self, bamboo: &T) -> T;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
mod traits {
pub trait Foo { fn f(&self) -> int; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo { fn f(&self) -> int; }
trait Bar { fn g(&self) -> int; }
trait Baz { fn h(&self) -> int; }
// test for #8664
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Uncovered during work on new scoping rules for safe destructors
// as an important use case to support properly.
+// pretty-expanded FIXME #23616
+
pub struct E<'a> {
pub f: &'a u8,
}
// Simple smoke test that unsafe traits can be compiled across crates.
+// pretty-expanded FIXME #23616
+
extern crate "trait-safety-lib" as lib;
use lib::Foo;
// Simple smoke test that unsafe traits can be compiled etc.
+// pretty-expanded FIXME #23616
+
unsafe trait Foo {
fn foo(&self) -> int;
}
//
// Issue #18453.
+// pretty-expanded FIXME #23616
+
use std::rc::Rc;
pub trait Foo<M> {
// Test case where an associated type is referenced from within the
// supertrait definition. Issue #20220.
+// pretty-expanded FIXME #23616
+
use std::vec::IntoIter;
pub trait Foo: Iterator<Item=<Self as Foo>::Key> {
// blanket impl for T:Copy coexists with an impl for Box<T>, because
// Box does not impl Copy.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// aux-build:go_trait.rs
+// pretty-expanded FIXME #23616
+
extern crate go_trait;
use go_trait::{Go, GoMut, GoOnce, go, go_mut, go_once};
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn bar(&self) -> String {
format!("test")
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unused_variable)]
// distinct scopes to be compared (`'g` and `'h`). The only important
// thing is that compilation succeeds here.
+// pretty-expanded FIXME #23616
+
#![allow(missing_copy_implementations)]
#![allow(unused_variables)]
// and the blanket impl. The only important thing is that compilation
// succeeds here. Issue #22110.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
trait Foo<A> {
// Regression test for issue #22655: This test should not lead to
// infinite recursion.
+// pretty-expanded FIXME #23616
+
unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
pub struct Unique<T:?Sized> {
// Async>::Cancel` be WF. This normalizes to `Receipt<Complete>`
// again, leading to an infinite cycle. Issue #23003.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
#![allow(unused_variables)]
// Test that we can infer the Target based on the Self or vice versa.
+// pretty-expanded FIXME #23616
+
use std::mem;
trait Convert<Target> {
// various methods in various ways successfully.
// See also `compile-fail/trait-repeated-supertrait-ambig.rs`.
+// pretty-expanded FIXME #23616
+
trait CompareTo<T> {
fn same_as(&self, t: T) -> bool;
}
// Last 7 bytes of Request struct are not occupied by any fields.
+// pretty-expanded FIXME #23616
+
enum TestOption<T> {
TestNone,
TestSome(T),
// Issue #7988
// Transmuting non-immediate type to immediate type
+// pretty-expanded FIXME #23616
+
pub fn main() {
unsafe {
::std::mem::transmute::<[int; 1],int>([1])
--- /dev/null
+// Copyright 2015 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 all coercions can actually be done using casts (modulo the lints).
+
+#![allow(trivial_casts, trivial_numeric_casts)]
+
+trait Foo {
+ fn foo(&self) {}
+}
+
+pub struct Bar;
+
+impl Foo for Bar {}
+
+pub fn main() {
+ // Numeric
+ let _ = 42_i32 as i32;
+ let _ = 42_u8 as u8;
+
+ // & to * pointers
+ let x: &u32 = &42;
+ let _ = x as *const u32;
+
+ let x: &mut u32 = &mut 42;
+ let _ = x as *mut u32;
+
+ // unsize array
+ let x: &[u32; 3] = &[42, 43, 44];
+ let _ = x as &[u32];
+ let _ = x as *const [u32];
+
+ let x: &mut [u32; 3] = &mut [42, 43, 44];
+ let _ = x as &mut [u32];
+ let _ = x as *mut [u32];
+
+ let x: Box<[u32; 3]> = Box::new([42, 43, 44]);
+ let _ = x as Box<[u32]>;
+
+ // unsize trait
+ let x: &Bar = &Bar;
+ let _ = x as &Foo;
+ let _ = x as *const Foo;
+
+ let x: &mut Bar = &mut Bar;
+ let _ = x as &mut Foo;
+ let _ = x as *mut Foo;
+
+ let x: Box<Bar> = Box::new(Bar);
+ let _ = x as Box<Foo>;
+
+ // functions
+ fn baz(_x: i32) {}
+ let _ = &baz as &Fn(i32);
+ let x = |_x: i32| {};
+ let _ = &x as &Fn(i32);
+}
+
+// subtyping
+pub fn test_subtyping<'a, 'b: 'a>(a: &'a Bar, b: &'b Bar) {
+ let _ = a as &'a Bar;
+ let _ = b as &'a Bar;
+ let _ = b as &'b Bar;
+}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
type point = (int, int);
fn f(p: point, x: int, y: int) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo<'a>(&'a [int]);
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Point(int, int);
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo(int, int, int);
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
use std::intrinsics::type_name;
// Test that type IDs correctly account for higher-rank lifetimes
// Also acts as a regression test for an ICE (issue #19791)
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::any::TypeId;
+// pretty-expanded FIXME #23616
+
mod a {
pub mod b {
pub type t = int;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct A { a: int }
fn a(a: A) -> int { return a.a; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
+// pretty-expanded FIXME #23616
+
type lteq<T> = extern fn(T) -> bool;
pub fn main() { }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct S<T> {
a: T,
b: uint,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f(a: *const int) -> *const int { return a; }
fn g(a: *const int) -> *const int { let b = f(a); return b; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::size_of;
struct t {a: u8, b: i8}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::ptr;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum T {
A(int),
B(f64)
// This test checks that the `_` type placeholder works
// correctly for enabling type inference.
+// pretty-expanded FIXME #23616
+
struct TestStruct {
- x: *const int
+ x: *const isize
}
unsafe impl Sync for TestStruct {}
-static CONSTEXPR: TestStruct = TestStruct{x: &413 as *const _};
+static CONSTEXPR: TestStruct = TestStruct{ x: &413 };
pub fn main() {
let x: Vec<_> = (0..5).collect();
- let expected: &[uint] = &[0,1,2,3,4];
+ let expected: &[usize] = &[0,1,2,3,4];
assert_eq!(x, expected);
let x = (0..5).collect::<Vec<_>>();
let y: _ = "hello";
assert_eq!(y.len(), 5);
- let ptr = &5;
+ let ptr: &usize = &5;
let ptr2 = ptr as *const _;
- assert_eq!(ptr as *const uint as uint, ptr2 as uint);
+ assert_eq!(ptr as *const usize as usize, ptr2 as usize);
}
// aux-build:typeid-intrinsic.rs
// aux-build:typeid-intrinsic2.rs
+// pretty-expanded FIXME #23616
+
+#![feature(hash, core)]
+
extern crate "typeid-intrinsic" as other1;
extern crate "typeid-intrinsic2" as other2;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unused_variable)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let (x, y) = (10, 20);
let z = x + y;
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut word: u32 = 200000;
word = word - 1;
// These constants were chosen because they aren't used anywhere
// in the rest of the generated code so they're easily grep-able.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut x: u8 = 19; // 0x13
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut x: u8 = 12;
let y: u8 = 12;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(macro_rules)]
+// pretty-expanded FIXME #23616
+
+#![feature(collections, rand, into_cow)]
use std::borrow::{Cow, IntoCow};
use std::collections::BitVec;
// Test that when you use ufcs form to invoke a trait method (on a
// trait object) everything works fine.
+// pretty-expanded FIXME #23616
+
trait Foo {
fn test(&self) -> i32;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo<T> {
fn get(&self) -> T;
}
+// pretty-expanded FIXME #23616
+
pub fn main() { let _x: uint = 10 as uint; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(lang_items, unboxed_closures)]
fn a<F:Fn(int, int) -> int>(f: F) -> int {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
// Test by-ref capture of environment in unboxed closure types
// Test that the call operator autoderefs when calling a bounded type parameter.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
use std::ops::FnMut;
// Test that the call operator autoderefs when calling a bounded type parameter.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
use std::ops::FnMut;
// Test that we mutate a counter on the stack only when we expect to.
+// pretty-expanded FIXME #23616
+
fn call<F>(f: F) where F : FnOnce() {
f();
}
// Acts as a regression test for #16790, #18378 and #18543
// aux-build:unboxed-closures-cross-crate.rs
+// pretty-expanded FIXME #23616
+
extern crate "unboxed-closures-cross-crate" as ubcc;
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
fn main() {
// A battery of tests to ensure destructors of unboxed closure environments
// run at the right times.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
static mut DROP_COUNT: uint = 0;
// Checks that higher-ranked extern fn pointers implement the full range of Fn traits.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::ops::{Fn,FnMut,FnOnce};
// Checks that extern fn pointers implement the full range of Fn traits.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
#![feature(unboxed_closures)]
// Checks that the Fn trait hierarchy rules permit
// any Fn trait to be used where Fn is implemented.
-#![feature(unboxed_closures)]
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::ops::{Fn,FnMut,FnOnce};
struct S;
impl Fn<(i32,)> for S {
- type Output = i32;
extern "rust-call" fn call(&self, (x,): (i32,)) -> i32 {
x * x
}
}
+impl FnMut<(i32,)> for S {
+ extern "rust-call" fn call_mut(&mut self, args: (i32,)) -> i32 { self.call(args) }
+}
+
+impl FnOnce<(i32,)> for S {
+ type Output = i32;
+ extern "rust-call" fn call_once(self, args: (i32,)) -> i32 { self.call(args) }
+}
+
fn call_it<F:Fn(i32)->i32>(f: &F, x: i32) -> i32 {
f(x)
}
// Checks that the Fn trait hierarchy rules permit
// FnMut or FnOnce to be used where FnMut is implemented.
-#![feature(unboxed_closures)]
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::ops::{FnMut,FnOnce};
struct S;
impl FnMut<(i32,)> for S {
- type Output = i32;
-
extern "rust-call" fn call_mut(&mut self, (x,): (i32,)) -> i32 {
x * x
}
}
+impl FnOnce<(i32,)> for S {
+ type Output = i32;
+
+ extern "rust-call" fn call_once(mut self, args: (i32,)) -> i32 { self.call_mut(args) }
+}
+
fn call_it_mut<F:FnMut(i32)->i32>(f: &mut F, x: i32) -> i32 {
f(x)
}
// Test that we are able to infer that the type of `x` is `int` based
// on the expected type from the object.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::num::ToPrimitive;
// Test that we are able to infer that the type of `x` is `int` based
// on the expected type from the object.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::num::ToPrimitive;
// Test that we are able to infer that the type of `x` is `int` based
// on the expected type from the object.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::num::ToPrimitive;
// Test that we are able to infer a suitable kind for this closure
// that is just called (`FnMut`).
+// pretty-expanded FIXME #23616
+
fn main() {
let mut counter = 0;
// Test that we are able to infer a suitable kind for this `move`
// closure that is just called (`FnMut`).
+// pretty-expanded FIXME #23616
+
fn main() {
let mut counter = 0;
// Test that we are able to infer a suitable kind for this closure
// that is just called (`FnMut`).
+// pretty-expanded FIXME #23616
+
fn main() {
let mut counter = 0;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
// Test that we are able to infer a suitable kind for this `move`
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
// Test that we are able to infer a suitable kind for this closure
// Test that we can infer the "kind" of an unboxed closure based on
// the expected type.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
// Test by-ref capture of environment in unboxed closure types
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(core,unboxed_closures)]
use std::marker::PhantomData;
}
impl<A,R,F : Fn(&Fn(A) -> R, A) -> R> Fn<(A,)> for YCombinator<F,A,R> {
- type Output = R;
-
extern "rust-call" fn call(&self, (arg,): (A,)) -> R {
(self.func)(self, arg)
}
}
+impl<A,R,F : Fn(&Fn(A) -> R, A) -> R> FnMut<(A,)> for YCombinator<F,A,R> {
+ extern "rust-call" fn call_mut(&mut self, args: (A,)) -> R { self.call(args) }
+}
+
+impl<A,R,F : Fn(&Fn(A) -> R, A) -> R> FnOnce<(A,)> for YCombinator<F,A,R> {
+ type Output = R;
+ extern "rust-call" fn call_once(self, args: (A,)) -> R { self.call(args) }
+}
+
fn main() {
let factorial = |recur: &Fn(u32) -> u32, arg: u32| -> u32 {
if arg == 0 {1} else {arg * recur(arg-1)}
// Test that the type variable in the type(`Vec<_>`) of a closed over
// variable does not interfere with type inference.
+// pretty-expanded FIXME #23616
+
fn f<F: FnMut()>(mut f: F) {
f();
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(unboxed_closures)]
+// pretty-expanded FIXME #23616
+
+#![feature(unboxed_closures, core)]
use std::ops::FnMut;
struct S;
impl FnMut<(i32,)> for S {
- type Output = i32;
-
extern "rust-call" fn call_mut(&mut self, (x,): (i32,)) -> i32 {
x * x
}
}
+impl FnOnce<(i32,)> for S {
+ type Output = i32;
+
+ extern "rust-call" fn call_once(mut self, args: (i32,)) -> i32 { self.call_mut(args) }
+}
+
fn call_it<F:FnMut(i32)->i32>(mut f: F, x: i32) -> i32 {
f(x) + 3
}
#![allow(unknown_features)]
#![feature(box_syntax)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, core)]
fn main(){
fn bar<'a, T:Clone+'a> (t: T) -> Box<FnMut()->T + 'a> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
#![deny(unused_mut)]
// Test that in a by-ref once closure we move some variables even as
// we capture others by mutable reference.
+// pretty-expanded FIXME #23616
+
fn call<F>(f: F) where F : FnOnce() {
f();
}
// Tests that the reexports of `FnOnce` et al from the prelude work.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
-#![feature(unboxed_closures)]
+#![feature(unboxed_closures, core)]
fn main() {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
use std::ops::FnMut;
// Ensures that single-word environments work right in unboxed closures.
// These take a different path in codegen.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
fn a<F:Fn(int, int) -> int>(f: F) -> int {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
fn main() {
// Test unboxed closure sugar used in object types.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
#![feature(unboxed_closures)]
//
// compile-flags: -g
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
use std::ptr;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
fn main() {
// no-pretty-expanded FIXME #15189
+// pretty-expanded FIXME #23616
+
+#![feature(core)]
+
use std::iter::Unfold;
// Unfold had a bug with 'a that mean it didn't work
// unified with the type *T, and so the type variable
// in that type gets resolved.
+// pretty-expanded FIXME #23616
+
use std::mem;
fn null<T>() -> *const T {
// Test the uninit() construct returning various empty types.
+// pretty-expanded FIXME #23616
+
use std::mem;
#[derive(Clone)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_assignment)]
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let _: Box<int>;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_patterns)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Issue #976
+// pretty-expanded FIXME #23616
+
fn f<T>(x: Box<T>) {
let _x2 = x;
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Issue #961
+// pretty-expanded FIXME #23616
+
fn altsimple() {
match Box::new(true) {
_ => { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_variable)]
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Issue #5192
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_patterns)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_patterns)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Make sure the destructor is run for unit-like structs.
+// pretty-expanded FIXME #23616
+
+#![feature(alloc)]
+
use std::boxed::BoxAny;
use std::thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_variable)]
#![allow(dead_assignment)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn good(_a: &int) {
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unreachable_code)]
#![allow(unused_variable)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(path_statement)]
#![allow(unreachable_code)]
#![allow(unused_variable)]
// Check that safe fns are not a subtype of unsafe fns.
+// pretty-expanded FIXME #23616
+
fn foo(x: i32) -> i32 {
x * 22
}
//
// See also: compile-fail/unsafe-fn-called-from-safe.rs
+// pretty-expanded FIXME #23616
+
unsafe fn f() { return; }
fn g() {
//
// See also: compile-fail/unsafe-fn-called-from-safe.rs
+// pretty-expanded FIXME #23616
+
unsafe fn f() { return; }
unsafe fn g() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn f(x: *const int) {
unsafe {
assert_eq!(*x, 3);
// Test syntax checks for `?Sized` syntax.
+// pretty-expanded FIXME #23616
+
use std::marker::{PhantomData, PhantomFn};
trait T1 : PhantomFn<Self> { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Test structs with always-unsized fields.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
-#![feature(box_syntax)]
+#![feature(box_syntax, core)]
use std::mem;
use std::raw;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// Issue Name: Unused move causes a crash
// Abstract: zero-fill to block after drop
+// pretty-expanded FIXME #23616
+
#![allow(path_statement)]
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// except according to those terms.
// Issue #1706
+// pretty-expanded FIXME #23616
+
extern crate "std" as stdlib;
pub fn main() {}
+// pretty-expanded FIXME #23616
+
mod foo {
pub fn x() -> int { return 1; }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub use foo::bar::{self, First};
use self::bar::Second;
// Issue #1761
+// pretty-expanded FIXME #23616
+
impl foo for int { fn foo(&self) -> int { 10 } }
trait foo { fn foo(&self) -> int; }
pub fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unused_imports)]
#![feature(start, no_std)]
#![no_std]
// aux-build:inline_dtor.rs
+// pretty-expanded FIXME #23616
+
extern crate inline_dtor;
pub fn main() {
//
// ignore-lexer-test FIXME #15679
+#![feature(collections, core, str_char)]
+
use std::str;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc, std_misc)]
+
extern crate libc;
use std::ffi::{self, CString};
// us from approximating the lifetimes of `field1` and `field2` to a
// common intersection.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
+#![feature(core)]
struct List<'l> {
field1: &'l i32,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
// Get<T> is covariant in T
// Test that vec is now covariant in its argument type.
+// pretty-expanded FIXME #23616
+
#![allow(dead_code)]
+#![feature(core)]
fn foo<'a,'b>(v1: Vec<&'a i32>, v2: Vec<&'b i32>) -> i32 {
bar(v1, v2).cloned().unwrap_or(0) // only type checks if we can intersect 'a and 'b
// except according to those terms.
// pp-exact - Make sure we actually print the attributes
+// pretty-expanded FIXME #23616
+
#![feature(custom_attribute)]
enum crew_of_enterprise_d {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
enum Foo {
Bar { x: int },
Baz { y: int }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+#![feature(collections)]
+
use std::vec;
pub fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::mem::size_of;
pub fn main() {
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut v = vec!(1);
v.push(2);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![feature(lang_items, start, no_std)]
+// pretty-expanded FIXME #23616
+
+#![feature(lang_items, start, no_std, core, libc, collections)]
#![no_std]
extern crate "std" as other;
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert_eq!(vec![1; 3], vec![1, 1, 1]);
assert_eq!(vec![1; 2], vec![1, 1]);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn one() -> i32 { 1 }
// Make sure the vec![...] macro doesn't introduce hidden rvalue
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
macro_rules! vec [
($($e:expr),*) => ({
let mut _temp = ::std::vec::Vec::new();
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert_eq!(vec!(1), vec!(1,));
assert_eq!(vec!(1, 2, 3), vec!(1, 2, 3,));
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let x = [1, 2, 3];
match x {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(advanced_slice_patterns)]
fn a() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(advanced_slice_patterns)]
fn foldl<T, U, F>(values: &[T],
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(advanced_slice_patterns)]
fn a() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() { let mut v = vec!(1, 2, 3); v.push(1); }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() { let _a = [0; 1 as uint]; }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_destructor)]
use std::cell::Cell;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let v = vec![1,2,3,4,5];
let v2 = &v[1..3];
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct Foo {
string: String
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
assert_eq!(format!("{:?}", vec!(0, 1)), "[0, 1]".to_string());
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let v: Vec<int> = vec!(10, 20);
assert_eq!(v[0], 10);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![allow(unknown_features)]
#![feature(box_syntax)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(rand, core)]
+
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use std::rand::{thread_rng, Rng, Rand};
use std::thread;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(visible_private_types)]
trait Foo { fn dummy(&self) { } }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(libc, old_io)]
+
extern crate libc;
use std::old_io::process::Command;
// compile-flags:-D improper-ctypes
+// pretty-expanded FIXME #23616
+
#![allow(improper_ctypes)]
mod libc {
// aux-build:weak-lang-items.rs
+// pretty-expanded FIXME #23616
+
extern crate "weak-lang-items" as other;
use std::thread;
// Test that the `wf` checker properly handles bound regions in object
// types. Compiling this code used to trigger an ICE.
+// pretty-expanded FIXME #23616
+
pub struct Context<'tcx> {
vec: &'tcx Vec<int>
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Bound {
fn dummy(&self) { }
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait TheTrait { fn dummy(&self) { } }
impl TheTrait for &'static int { }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
trait Foo<T> { fn dummy(&self, arg: T) { } }
trait Bar<A> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
struct A<'a, 'b> where 'a : 'b { x: &'a int, y: &'b int }
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn foo<'a, I>(mut it: I) where I: Iterator<Item=&'a int> {}
fn main() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unboxed_closures)]
struct Bencher;
// Test that we can quantify lifetimes outside a constraint (i.e., including
// the self type) in a where clause.
+// pretty-expanded FIXME #23616
+
use std::marker::PhantomFn;
static mut COUNT: u32 = 1;
+// pretty-expanded FIXME #23616
+
pub fn main() { let x: int = 10; while x == 10 && x == 11 { let _y = 0xf00_usize; } }
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub fn main() {
let mut i = 100;
'w: while 1 + 1 == 2 {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
use std::collections::BinaryHeap;
fn make_pq() -> BinaryHeap<int> {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
+#![feature(collections)]
+
use std::string::String;
#[derive(PartialEq)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
use std::sync::Mutex;
struct Point {x: int, y: int, z: int}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
pub type HANDLE = u32;
pub type DWORD = u32;
pub type SIZE_T = u32;
// aux-build:xcrate_address_insignificant.rs
+// pretty-expanded FIXME #23616
+
extern crate "xcrate_address_insignificant" as foo;
pub fn main() {
// aux-build:xcrate_static_addresses.rs
+// pretty-expanded FIXME #23616
+
extern crate xcrate_static_addresses;
use xcrate_static_addresses as other;
// aux-build:xcrate-trait-lifetime-param.rs
+// pretty-expanded FIXME #23616
+
extern crate "xcrate-trait-lifetime-param" as other;
struct Reader<'a> {
// except according to those terms.
// aux-build:xcrate_unit_struct.rs
+// pretty-expanded FIXME #23616
+
extern crate xcrate_unit_struct;
const s1: xcrate_unit_struct::Struct = xcrate_unit_struct::Struct;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
#![feature(unsafe_no_drop_flag)]
static mut destructions : int = 3;
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+// pretty-expanded FIXME #23616
+
fn main() {
let x = [(), ()];
// The subslice used to go out of bounds for zero-sized array items, check that this doesn't
// happen anymore
match x {
- [_, y..] => assert_eq!(&x[1] as *const _, &y[0] as *const _)
+ [_, y..] => assert_eq!(&x[1] as *const (), &y[0] as *const ())
}
}