# This is hardly all there is to know of The Rust Build System's
# mysteries. The tale continues on the wiki[1][2].
#
-# [1]: https://github.com/rust-lang/rust/wiki/Note-build-system
+# [1]: https://github.com/rust-lang/rust/wiki/Note-getting-started-developing-Rust
# [2]: https://github.com/rust-lang/rust/wiki/Note-testsuite
#
# If you really feel like getting your hands dirty, then:
# * dist-docs - Stage docs for upload
PKG_NAME := $(CFG_PACKAGE_NAME)
+DOC_PKG_NAME := rust-docs-$(CFG_PACKAGE_VERS)
+MINGW_PKG_NAME := rust-mingw-$(CFG_PACKAGE_VERS)
# License suitable for displaying in a popup
LICENSE.txt: $(S)COPYRIGHT $(S)LICENSE-APACHE $(S)LICENSE-MIT
$$(Q)$$(PREPARE_MAN_CMD) $$(S)LICENSE-APACHE $$(PREPARE_DEST_DIR)
$$(Q)$$(PREPARE_MAN_CMD) $$(S)LICENSE-MIT $$(PREPARE_DEST_DIR)
$$(Q)$$(PREPARE_MAN_CMD) $$(S)README.md $$(PREPARE_DEST_DIR)
- $$(Q)[ ! -d doc ] || cp -r doc $$(PREPARE_DEST_DIR)
+ $$(Q)mkdir -p $$(PREPARE_DEST_DIR)/share/doc/rust
+ $$(Q)$$(PREPARE_MAN_CMD) $$(S)COPYRIGHT $$(PREPARE_DEST_DIR)/share/doc/rust
+ $$(Q)$$(PREPARE_MAN_CMD) $$(S)LICENSE-APACHE $$(PREPARE_DEST_DIR)/share/doc/rust
+ $$(Q)$$(PREPARE_MAN_CMD) $$(S)LICENSE-MIT $$(PREPARE_DEST_DIR)/share/doc/rust
+ $$(Q)$$(PREPARE_MAN_CMD) $$(S)README.md $$(PREPARE_DEST_DIR)/share/doc/rust
dist/$$(PKG_NAME)-$(1).tar.gz: dist-install-dir-$(1)
@$(call E, build: $$@)
+# Copy essential gcc components into installer
+ifdef CFG_WINDOWSY_$(1)
+ $$(Q)rm -Rf dist/win-rust-gcc-$(1)
+ $$(Q)$$(CFG_PYTHON) $$(S)src/etc/make-win-dist.py tmp/dist/$$(PKG_NAME)-$(1)-image dist/win-rust-gcc-$(1) $(1)
+ $$(Q)cp -r $$(S)src/etc/third-party tmp/dist/$$(PKG_NAME)-$(1)-image/share/doc/
+endif
$$(Q)$$(S)src/rust-installer/gen-installer.sh \
--product-name=Rust \
--verify-bin=rustc \
--work-dir=tmp/dist \
--output-dir=dist \
--non-installed-prefixes=$$(NON_INSTALLED_PREFIXES) \
- --package-name=$$(PKG_NAME)-$(1)
+ --package-name=$$(PKG_NAME)-$(1) \
+ --component-name=rustc \
+ --legacy-manifest-dirs=rustlib,cargo
$$(Q)rm -R tmp/dist/$$(PKG_NAME)-$(1)-image
+dist-doc-install-dir-$(1): docs compiler-docs
+ $$(Q)mkdir -p tmp/dist/$$(DOC_PKG_NAME)-$(1)-image/share/doc/rust
+ $$(Q)cp -r doc tmp/dist/$$(DOC_PKG_NAME)-$(1)-image/share/doc/rust/html
+
+dist/$$(DOC_PKG_NAME)-$(1).tar.gz: dist-doc-install-dir-$(1)
+ @$(call E, build: $$@)
+ $$(Q)$$(S)src/rust-installer/gen-installer.sh \
+ --product-name=Rust-Documentation \
+ --rel-manifest-dir=rustlib \
+ --success-message=Rust-documentation-is-installed. \
+ --image-dir=tmp/dist/$$(DOC_PKG_NAME)-$(1)-image \
+ --work-dir=tmp/dist \
+ --output-dir=dist \
+ --package-name=$$(DOC_PKG_NAME)-$(1) \
+ --component-name=rust-docs \
+ --legacy-manifest-dirs=rustlib,cargo \
+ --bulk-dirs=share/doc/rust/html
+ $$(Q)rm -R tmp/dist/$$(DOC_PKG_NAME)-$(1)-image
+
+dist-mingw-install-dir-$(1):
+ $$(Q)mkdir -p tmp/dist/rust-mingw-tmp-$(1)-image
+ $$(Q)rm -Rf tmp/dist/$$(MINGW_PKG_NAME)-$(1)-image
+ $$(Q)$$(CFG_PYTHON) $$(S)src/etc/make-win-dist.py \
+ tmp/dist/rust-mingw-tmp-$(1)-image tmp/dist/$$(MINGW_PKG_NAME)-$(1)-image $(1)
+
+dist/$$(MINGW_PKG_NAME)-$(1).tar.gz: dist-mingw-install-dir-$(1)
+ @$(call E, build: $$@)
+ $$(Q)$$(S)src/rust-installer/gen-installer.sh \
+ --product-name=Rust-MinGW \
+ --rel-manifest-dir=rustlib \
+ --success-message=Rust-MinGW-is-installed. \
+ --image-dir=tmp/dist/$$(MINGW_PKG_NAME)-$(1)-image \
+ --work-dir=tmp/dist \
+ --output-dir=dist \
+ --package-name=$$(MINGW_PKG_NAME)-$(1) \
+ --component-name=rust-mingw \
+ --legacy-manifest-dirs=rustlib,cargo
+ $$(Q)rm -R tmp/dist/$$(MINGW_PKG_NAME)-$(1)-image
+
endef
ifneq ($(CFG_ENABLE_DIST_HOST_ONLY),)
dist-install-dirs: $(foreach host,$(CFG_HOST),dist-install-dir-$(host))
-dist-tar-bins: $(foreach host,$(CFG_HOST),dist/$(PKG_NAME)-$(host).tar.gz)
+ifdef CFG_WINDOWSY_$(CFG_BUILD)
+MAYBE_MINGW_TARBALLS=$(foreach host,$(CFG_HOST),dist/$(MINGW_PKG_NAME)-$(host).tar.gz)
+endif
+
+ifeq ($(CFG_DISABLE_DOCS),)
+MAYBE_DOC_TARBALLS=$(foreach host,$(CFG_HOST),dist/$(DOC_PKG_NAME)-$(host).tar.gz)
+endif
+
+dist-tar-bins: $(foreach host,$(CFG_HOST),dist/$(PKG_NAME)-$(host).tar.gz) \
+ $(MAYBE_DOC_TARBALLS) $(MAYBE_MINGW_TARBALLS)
# Just try to run the compiler for the build host
distcheck-tar-bins: dist-tar-bins
# Primary targets (dist, distcheck)
######################################################################
-ifdef CFG_WINDOWSY_$(CFG_BUILD)
-
-dist: dist-win dist-tar-bins
-
-distcheck: distcheck-win
- $(Q)rm -Rf tmp/distcheck
- @echo
- @echo -----------------------------------------------
- @echo "Rust ready for distribution (see ./dist)"
- @echo -----------------------------------------------
-
-else
+MAYBE_DIST_TAR_SRC=dist-tar-src
+MAYBE_DISTCHECK_TAR_SRC=distcheck-tar-src
# FIXME #13224: On OS X don't produce tarballs simply because --exclude-vcs don't work.
# This is a huge hack because I just don't have time to figure out another solution.
ifeq ($(CFG_OSTYPE), apple-darwin)
MAYBE_DIST_TAR_SRC=
MAYBE_DISTCHECK_TAR_SRC=
-else
-MAYBE_DIST_TAR_SRC=dist-tar-src
-MAYBE_DISTCHECK_TAR_SRC=distcheck-tar-src
+endif
+
+# Don't bother with source tarballs on windows just because we historically haven't.
+ifeq ($(CFG_OSTYPE), pc-windows-gnu)
+MAYBE_DIST_TAR_SRC=
+MAYBE_DISTCHECK_TAR_SRC=
endif
ifneq ($(CFG_DISABLE_DOCS),)
MAYBE_DISTCHECK_DOCS=distcheck-docs
endif
-dist: $(MAYBE_DIST_TAR_SRC) dist-osx dist-tar-bins $(MAYBE_DIST_DOCS)
+dist: $(MAYBE_DIST_TAR_SRC) dist-osx dist-win dist-tar-bins $(MAYBE_DIST_DOCS)
-distcheck: $(MAYBE_DISTCHECK_TAR_SRC) distcheck-osx distcheck-tar-bins $(MAYBE_DISTCHECK_DOCS)
+distcheck: $(MAYBE_DISTCHECK_TAR_SRC) distcheck-osx distcheck-win distcheck-tar-bins $(MAYBE_DISTCHECK_DOCS)
$(Q)rm -Rf tmp/distcheck
@echo
@echo -----------------------------------------------
@echo "Rust ready for distribution (see ./dist)"
@echo -----------------------------------------------
-endif
-
.PHONY: dist distcheck
$(Q)mkdir -p $(BG)
$(BG)RustLexer.class: $(BG) $(SG)RustLexer.g4
- $(Q)$(CFG_ANTLR4) -o $(B)grammar $(SG)RustLexer.g4
+ $(Q)$(CFG_ANTLR4) -o $(BG) $(SG)RustLexer.g4
$(Q)$(CFG_JAVAC) -d $(BG) $(BG)RustLexer.java
check-build-lexer-verifier: $(BG)verify
$(Q)sudo -u "$$SUDO_USER" $(MAKE) prepare_install
else
$(Q)$(MAKE) prepare_install
+endif
+ifeq ($(CFG_DISABLE_DOCS),)
+ $(Q)cd tmp/empty_dir && sh ../../tmp/dist/$(DOC_PKG_NAME)-$(CFG_BUILD)/install.sh --prefix="$(DESTDIR)$(CFG_PREFIX)" --libdir="$(DESTDIR)$(CFG_LIBDIR)" --mandir="$(DESTDIR)$(CFG_MANDIR)" "$(MAYBE_DISABLE_VERIFY)"
endif
$(Q)cd tmp/empty_dir && sh ../../tmp/dist/$(PKG_NAME)-$(CFG_BUILD)/install.sh --prefix="$(DESTDIR)$(CFG_PREFIX)" --libdir="$(DESTDIR)$(CFG_LIBDIR)" --mandir="$(DESTDIR)$(CFG_MANDIR)" "$(MAYBE_DISABLE_VERIFY)"
# Remove tmp files because it's a decent amount of disk space
$(Q)sudo -u "$$SUDO_USER" $(MAKE) prepare_uninstall
else
$(Q)$(MAKE) prepare_uninstall
+endif
+ifeq ($(CFG_DISABLE_DOCS),)
+ $(Q)cd tmp/empty_dir && sh ../../tmp/dist/$(DOC_PKG_NAME)-$(CFG_BUILD)/install.sh --uninstall --prefix="$(DESTDIR)$(CFG_PREFIX)" --libdir="$(DESTDIR)$(CFG_LIBDIR)" --mandir="$(DESTDIR)$(CFG_MANDIR)"
endif
$(Q)cd tmp/empty_dir && sh ../../tmp/dist/$(PKG_NAME)-$(CFG_BUILD)/install.sh --uninstall --prefix="$(DESTDIR)$(CFG_PREFIX)" --libdir="$(DESTDIR)$(CFG_LIBDIR)" --mandir="$(DESTDIR)$(CFG_MANDIR)"
# Remove tmp files because it's a decent amount of disk space
TEST_LOG_FILE=tmp/check-stage$(1)-T-$(2)-H-$(3)-$(4).log
TEST_OK_FILE=tmp/check-stage$(1)-T-$(2)-H-$(3)-$(4).ok
-# If we're sharding the testsuite between parallel testers,
-# pass this argument along to the compiletest and crate test
-# invocations.
-ifdef TEST_SHARD
- CTEST_TESTARGS += --test-shard=$(TEST_SHARD)
- CRATE_TEST_EXTRA_ARGS += --test-shard=$(TEST_SHARD)
-endif
-
define DEF_TARGET_COMMANDS
ifdef CFG_UNIXY_$(1)
| grep '^$(S)src/doc' -v \
| grep '^$(S)src/compiler-rt' -v \
| grep '^$(S)src/libbacktrace' -v \
+ | grep '^$(S)src/rust-installer' -v \
| xargs $(CFG_PYTHON) $(S)src/etc/check-binaries.py
endif
-% The Rust Tasks and Communication Guide
+% The Rust Threads and Communication Guide
-**NOTE** This guide is badly out of date an needs to be rewritten.
+**NOTE** This guide is badly out of date and needs to be rewritten.
# Introduction
relates to the Rust type system, and introduce the fundamental library
abstractions for constructing concurrent programs.
-Tasks provide failure isolation and recovery. When a fatal error occurs in Rust
+Threads provide failure isolation and recovery. When a fatal error occurs in Rust
code as a result of an explicit call to `panic!()`, an assertion failure, or
-another invalid operation, the runtime system destroys the entire task. Unlike
+another invalid operation, the runtime system destroys the entire thread. Unlike
in languages such as Java and C++, there is no way to `catch` an exception.
-Instead, tasks may monitor each other to see if they panic.
+Instead, threads may monitor each other to see if they panic.
-Tasks use Rust's type system to provide strong memory safety guarantees. In
-particular, the type system guarantees that tasks cannot induce a data race
+Threads use Rust's type system to provide strong memory safety guarantees. In
+particular, the type system guarantees that threads cannot induce a data race
from shared mutable state.
# Basics
-At its simplest, creating a task is a matter of calling the `spawn` function
-with a closure argument. `spawn` executes the closure in the new task.
+At its simplest, creating a thread is a matter of calling the `spawn` function
+with a closure argument. `spawn` executes the closure in the new thread.
```{rust,ignore}
-# use std::task::spawn;
+# use std::thread::spawn;
-// Print something profound in a different task using a named function
-fn print_message() { println!("I am running in a different task!"); }
+// Print something profound in a different thread using a named function
+fn print_message() { println!("I am running in a different thread!"); }
spawn(print_message);
// Alternatively, use a `move ||` expression instead of a named function.
// `||` expressions evaluate to an unnamed closure. The `move` keyword
// indicates that the closure should take ownership of any variables it
// touches.
-spawn(move || println!("I am also running in a different task!"));
+spawn(move || println!("I am also running in a different thread!"));
```
-In Rust, a task is not a concept that appears in the language semantics.
+In Rust, a thread is not a concept that appears in the language semantics.
Instead, Rust's type system provides all the tools necessary to implement safe
concurrency: particularly, ownership. The language leaves the implementation
details to the standard library.
closure is limited to capturing `Send`-able data from its environment
(that is, data which is deeply owned). Limiting the closure to `Send`
ensures that `spawn` can safely move the entire closure and all its
-associated state into an entirely different task for execution.
+associated state into an entirely different thread for execution.
```{rust,ignore}
-# use std::task::spawn;
-# fn generate_task_number() -> int { 0 }
+# use std::thread::spawn;
+# fn generate_thread_number() -> int { 0 }
// Generate some state locally
-let child_task_number = generate_task_number();
+let child_thread_number = generate_thread_number();
spawn(move || {
- // Capture it in the remote task. The `move` keyword indicates
- // that this closure should move `child_task_number` into its
+ // Capture it in the remote thread. The `move` keyword indicates
+ // that this closure should move `child_thread_number` into its
// environment, rather than capturing a reference into the
// enclosing stack frame.
- println!("I am child number {}", child_task_number);
+ println!("I am child number {}", child_thread_number);
});
```
## Communication
-Now that we have spawned a new task, it would be nice if we could communicate
+Now that we have spawned a new thread, it would be nice if we could communicate
with it. For this, we use *channels*. A channel is simply a pair of endpoints:
one for sending messages and another for receiving messages.
example of calculating two results concurrently:
```{rust,ignore}
-# use std::task::spawn;
+# use std::thread::spawn;
let (tx, rx): (Sender<int>, Receiver<int>) = channel();
let (tx, rx): (Sender<int>, Receiver<int>) = channel();
```
-The child task will use the sender to send data to the parent task, which will
+The child thread will use the sender to send data to the parent thread, which will
wait to receive the data on the receiver. The next statement spawns the child
-task.
+thread.
```{rust,ignore}
-# use std::task::spawn;
+# use std::thread::spawn;
# fn some_expensive_computation() -> int { 42 }
# let (tx, rx) = channel();
spawn(move || {
});
```
-Notice that the creation of the task closure transfers `tx` to the child task
+Notice that the creation of the thread closure transfers `tx` to the child thread
implicitly: the closure captures `tx` in its environment. Both `Sender` and
-`Receiver` are sendable types and may be captured into tasks or otherwise
-transferred between them. In the example, the child task runs an expensive
+`Receiver` are sendable types and may be captured into threads or otherwise
+transferred between them. In the example, the child thread runs an expensive
computation, then sends the result over the captured channel.
Finally, the parent continues with some other expensive computation, then waits
communication between a single sender and a single receiver, but multiple
senders cannot use a single `Sender` value, and multiple receivers cannot use a
single `Receiver` value. What if our example needed to compute multiple
-results across a number of tasks? The following program is ill-typed:
+results across a number of threads? The following program is ill-typed:
```{rust,ignore}
# fn some_expensive_computation() -> int { 42 }
let (tx, rx) = channel();
for init_val in range(0u, 3) {
- // Create a new channel handle to distribute to the child task
+ // Create a new channel handle to distribute to the child thread
let child_tx = tx.clone();
spawn(move || {
child_tx.send(some_expensive_computation(init_val));
```
Cloning a `Sender` produces a new handle to the same channel, allowing multiple
-tasks to send data to a single receiver. It upgrades the channel internally in
+threads to send data to a single receiver. It upgrades the channel internally in
order to allow this functionality, which means that channels that are not
cloned can avoid the overhead required to handle multiple senders. But this
fact has no bearing on the channel's usage: the upgrade is transparent.
reference, written with multiple streams, it might look like the example below.
```{rust,ignore}
-# use std::task::spawn;
+# use std::thread::spawn;
-// Create a vector of ports, one for each child task
+// Create a vector of ports, one for each child thread
let rxs = Vec::from_fn(3, |init_val| {
let (tx, rx) = channel();
spawn(move || {
## Sharing without copying: Arc
-To share data between tasks, a first approach would be to only use channel as
+To share data between threads, a first approach would be to only use channel as
we have seen previously. A copy of the data to share would then be made for
-each task. In some cases, this would add up to a significant amount of wasted
+each thread. In some cases, this would add up to a significant amount of wasted
memory and would require copying the same data more than necessary.
To tackle this issue, one can use an Atomically Reference Counted wrapper
(`Arc`) as implemented in the `sync` library of Rust. With an Arc, the data
-will no longer be copied for each task. The Arc acts as a reference to the
+will no longer be copied for each thread. The Arc acts as a reference to the
shared data and only this reference is shared and cloned.
Here is a small example showing how to use Arcs. We wish to run concurrently
-several computations on a single large vector of floats. Each task needs the
+several computations on a single large vector of floats. Each thread needs the
full vector to perform its duty.
```{rust,ignore}
let numbers_arc = Arc::new(numbers);
for num in range(1u, 10) {
- let task_numbers = numbers_arc.clone();
+ let thread_numbers = numbers_arc.clone();
spawn(move || {
- println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
+ println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
});
}
}
# }
```
-and a clone is captured for each task via a procedure. This only copies
-the wrapper and not its contents. Within the task's procedure, the captured
+and a clone is captured for each thread via a procedure. This only copies
+the wrapper and not its contents. Within the thread's procedure, the captured
Arc reference can be used as a shared reference to the underlying vector as
if it were local.
# let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
# let numbers_arc = Arc::new(numbers);
# let num = 4;
-let task_numbers = numbers_arc.clone();
+let thread_numbers = numbers_arc.clone();
spawn(move || {
- // Capture task_numbers and use it as if it was the underlying vector
- println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
+ // Capture thread_numbers and use it as if it was the underlying vector
+ println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
});
# }
```
-# Handling task panics
+# Handling thread panics
Rust has a built-in mechanism for raising exceptions. The `panic!()` macro
(which can also be written with an error string as an argument: `panic!(
~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a
-boolean expression is false) are both ways to raise exceptions. When a task
-raises an exception, the task unwinds its stack—running destructors and
+boolean expression is false) are both ways to raise exceptions. When a thread
+raises an exception, the thread unwinds its stack—running destructors and
freeing memory along the way—and then exits. Unlike exceptions in C++,
-exceptions in Rust are unrecoverable within a single task: once a task panics,
+exceptions in Rust are unrecoverable within a single thread: once a thread panics,
there is no way to "catch" the exception.
-While it isn't possible for a task to recover from panicking, tasks may notify
+While it isn't possible for a thread to recover from panicking, threads may notify
each other if they panic. The simplest way of handling a panic is with the
`try` function, which is similar to `spawn`, but immediately blocks and waits
-for the child task to finish. `try` returns a value of type
+for the child thread to finish. `try` returns a value of type
`Result<T, Box<Any + Send>>`. `Result` is an `enum` type with two variants:
`Ok` and `Err`. In this case, because the type arguments to `Result` are `int`
and `()`, callers can pattern-match on a result to check whether it's an `Ok`
Unlike `spawn`, the function spawned using `try` may return a value, which
`try` will dutifully propagate back to the caller in a [`Result`] enum. If the
-child task terminates successfully, `try` will return an `Ok` result; if the
-child task panics, `try` will return an `Error` result.
+child thread terminates successfully, `try` will return an `Ok` result; if the
+child thread panics, `try` will return an `Error` result.
[`Result`]: std/result/index.html
-> *Note:* A panicked task does not currently produce a useful error
+> *Note:* A panicked thread does not currently produce a useful error
> value (`try` always returns `Err(())`). In the
-> future, it may be possible for tasks to intercept the value passed to
+> future, it may be possible for threads to intercept the value passed to
> `panic!()`.
But not all panics are created equal. In some cases you might need to abort
indicates an unrecoverable logic error); in other cases you might want to
contain the panic at a certain boundary (perhaps a small piece of input from
the outside world, which you happen to be processing in parallel, is malformed
-such that the processing task cannot proceed).
+such that the processing thread cannot proceed).
in the `$`s, they just indicate the start of each command):
```bash
-$ curl -s https://static.rust-lang.org/rustup.sh | sudo sh
+curl -L https://static.rust-lang.org/rustup.sh | sudo sh
```
-(If you're concerned about `curl | sudo sh`, please keep reading. Disclaimer
-below.)
+If you're concerned about the [potential insecurity](http://curlpipesh.tumblr.com/) of using `curl | sudo sh`,
+please keep reading and see our disclaimer below. And feel free to use a two-step version of the installation and examine our installation script:
+
+```bash
+curl -L https://static.rust-lang.org/rustup.sh -O
+sudo sh rustup.sh
+```
If you're on Windows, please download either the [32-bit
installer](https://static.rust-lang.org/dist/rust-nightly-i686-pc-windows-gnu.exe)
Giving it a type will compile, though:
-```{ignore}
+```{rust}
let x: int;
```
These two will not be equal, even if they have the same values:
-```{rust,ignore}
+```{rust}
+# struct Color(int, int, int);
+# struct Point(int, int, int);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
```
let mut m = [1i, 2i, 3i]; // mut m: [int, ..3]
```
-You can create an array with a given number of elements, all initialized to the
-same value, with `[val, ..N]` syntax. The compiler ensures that arrays are
-always initialized.
-
There's a shorthand for initializing each element of an array to the same
value. In this example, each element of `a` will be initialized to `0i`:
Cargo gets this information from your environment. If it's not correct, go ahead
and fix that.
-Finally, Cargo generated a hello, world for us. Check out `src/main.rs`:
+Finally, Cargo generated a "Hello, world!" for us. Check out `src/main.rs`:
```{rust}
fn main() {
failures:
---- foo stdout ----
- task 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3
+ thread 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
-task '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
+thread '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
```
Lots of output! Let's break this down:
failures:
---- foo stdout ----
- task 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3
+ thread 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
-task '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
+thread '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
```
After all the tests run, Rust will show us any output from our failed tests.
it uses. Ordinary closures, in contrast, just create a reference into
the enclosing stack frame. Moving closures are most useful with Rust's
concurrency features, and so we'll just leave it at this for
-now. We'll talk about them more in the "Tasks" section of the guide.
+now. We'll talk about them more in the "Threads" section of the guide.
## Accepting closures as arguments
We've seen this before. We make a closure that takes an integer, and returns
its square.
-```{rust,ignore}
+```{rust}
+# fn twice(x: int, f: |int| -> int) -> int { f(x) + f(x) }
+# let square = |x: int| { x * x };
twice(5i, square); // evaluates to 50
```
hence 'statically dispatched'. The downside is that we have two copies of
the same function, so our binary is a little bit larger.
-# Tasks
-
-**NOTE**: this section is currently out of date and will be rewritten soon.
+# Threads
Concurrency and parallelism are topics that are of increasing interest to a
broad subsection of software developers. Modern computers are often multi-core,
issues that programmers have with concurrency. Many concurrency errors that are
runtime errors in other languages are compile-time errors in Rust.
-Rust's concurrency primitive is called a **task**. Tasks are similar to
-threads, and do not share memory in an unsafe manner, preferring message
-passing to communicate. It's worth noting that tasks are implemented as a
-library, and not part of the language. This means that in the future, other
-concurrency libraries can be written for Rust to help in specific scenarios.
-Here's an example of creating a task:
+Rust's concurrency primitive is called a **thread**. It's worth noting that
+threads are implemented as a library, and not part of the language. This means
+that in the future, other concurrency libraries can be written for Rust to help
+in specific scenarios. Here's an example of creating a thread:
```{rust,ignore}
spawn(move || {
- println!("Hello from a task!");
+ println!("Hello from a thread!");
});
```
The `spawn` function takes a closure as an argument, and runs that
-closure in a new task. Typically, you will want to use a moving
+closure in a new thread. Typically, you will want to use a moving
closure, so that the closure takes ownership of any variables that it
touches. This implies that those variables are not usable from the
-parent task after the child task is spawned:
+parent thread after the child thread is spawned:
```{rust,ignore}
let mut x = vec![1i, 2i, 3i];
other languages would let us do this, but it's not safe to do
so. Rust's borrow checker catches the error.
-If tasks were only able to capture these values, they wouldn't be very useful.
-Luckily, tasks can communicate with each other through **channel**s. Channels
+If threads were only able to capture these values, they wouldn't be very useful.
+Luckily, threads can communicate with each other through **channel**s. Channels
work like this:
```{rust,ignore}
let (tx, rx) = channel();
spawn(move || {
- tx.send("Hello from a task!".to_string());
+ tx.send("Hello from a thread!".to_string());
});
let message = rx.recv();
method blocks until it gets a message. There's a similar method, `.try_recv()`,
which returns an `Result<T, TryRecvError>` and does not block.
-If you want to send messages to the task as well, create two channels!
+If you want to send messages to the thread as well, create two channels!
```{rust,ignore}
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
spawn(move || {
- tx1.send("Hello from a task!".to_string());
+ tx1.send("Hello from a thread!".to_string());
let message = rx2.recv();
println!("{}", message);
});
tx2.send("Goodbye from main!".to_string());
```
-The closure has one sending end and one receiving end, and the main
-task has one of each as well. Now they can talk back and forth in
-whatever way they wish.
+The closure has one sending end and one receiving end, and the main thread has
+one of each as well. Now they can talk back and forth in whatever way they
+wish.
Notice as well that because `Sender` and `Receiver` are generic, while you can
pass any kind of information through the channel, the ends are strongly typed.
## Success and failure
-Tasks don't always succeed, they can also panic. A task that wishes to panic
+Threads don't always succeed, they can also panic. A thread that wishes to panic
can call the `panic!` macro, passing a message:
```{rust,ignore}
});
```
-If a task panics, it is not possible for it to recover. However, it can
-notify other tasks that it has panicked. We can do this with `task::try`:
+If a thread panics, it is not possible for it to recover. However, it can
+notify other thread that it has panicked. We can do this with `thread::try`:
```{rust,ignore}
-use std::task;
+use std::thread;
use std::rand;
-let result = task::try(move || {
+let result = thread::try(move || {
if rand::random() {
println!("OK");
} else {
});
```
-This task will randomly panic or succeed. `task::try` returns a `Result`
+This thread will randomly panic or succeed. `thread::try` returns a `Result`
type, so we can handle the response like any other computation that may
fail.
}
```
-You can have the macros expanded like this: `rustc print.rs --pretty=expanded`, which will
+You can have the macros expanded like this: `rustc --pretty=expanded print.rs`, which will
give us this huge result:
```{rust,ignore}
* [Strings](guide-strings.html)
* [Pointers](guide-pointers.html)
* [Crates and modules](guide-crates.html)
-* [Tasks and Communication](guide-tasks.html)
+* [Threads and Communication](guide-threads.html)
* [Error Handling](guide-error-handling.html)
* [Foreign Function Interface](guide-ffi.html)
* [Writing Unsafe and Low-Level Code](guide-unsafe.html)
for i in range(0u, 3u) {
let number = numbers.clone();
Thread::spawn(move || {
- let mut array = number.lock();
+ let mut array = number.lock().unwrap();
(*array)[i] += 1;
| else | enum | extern | false | final |
| fn | for | if | impl | in |
| let | loop | match | mod | move |
-| mut | offsetof | once | override | priv |
-| pub | pure | ref | return | sizeof |
-| static | self | struct | super | true |
-| trait | type | typeof | unsafe | unsized |
-| use | virtual | where | while | yield |
+| mut | offsetof | override | priv | pub |
+| pure | ref | return | sizeof | static |
+| self | struct | super | true | trait |
+| type | typeof | unsafe | unsized | use |
+| virtual | where | while | yield |
Each of these keywords has special meaning in its grammar, and all of them are
// Load the `vec` module from `vec.rs`
mod vec;
-mod task {
- // Load the `local_data` module from `task/local_data.rs`
+mod thread {
+ // Load the `local_data` module from `thread/local_data.rs`
mod local_data;
}
```
influenced with the `path` attribute.
```{.ignore}
-#[path = "task_files"]
-mod task {
- // Load the `local_data` module from `task_files/tls.rs`
+#[path = "thread_files"]
+mod thread {
+ // Load the `local_data` module from `thread_files/tls.rs`
#[path = "tls.rs"]
mod local_data;
}
Unsafe blocks are used to wrap foreign libraries, make direct use of hardware
or implement features not directly present in the language. For example, Rust
provides the language features necessary to implement memory-safe concurrency
-in the language but the implementation of tasks and message passing is in the
+in the language but the implementation of threads and message passing is in the
standard library.
Rust's type system is a conservative approximation of the dynamic safety
hard to run into, and this is obviously a very large source of race conditions
or other bugs. For this reason, an `unsafe` block is required when either
reading or writing a mutable static variable. Care should be taken to ensure
-that modifications to a mutable static are safe with respect to other tasks
+that modifications to a mutable static are safe with respect to other threads
running in the same process.
Mutable statics are still very useful, however. They can be used with C
* `drop`
: Have destructors.
* `send`
- : Able to be sent across task boundaries.
+ : Able to be sent across thread boundaries.
* `sized`
: Has a size known at compile time.
* `sync`
- : Able to be safely shared between tasks when aliased.
+ : Able to be safely shared between threads when aliased.
#### Operators
LLVM's implementation which works in concert with the kernel
loader and dynamic linker. This is not necessarily available
on all platforms, and usage of it is discouraged (rust
- focuses more on task-local data instead of thread-local
+ focuses more on thread-local data instead of thread-local
data).
* `trace_macros` - Allows use of the `trace_macros` macro, which is a nasty
be assigned to.
Indices are zero-based, and may be of any integral type. Vector access is
-bounds-checked at run-time. When the check fails, it will put the task in a
+bounds-checked at run-time. When the check fails, it will put the thread in a
_panicked state_.
```{should-fail}
components of the type. The kinds are:
* `Send`
- : Types of this kind can be safely sent between tasks.
+ : Types of this kind can be safely sent between threads.
This kind includes scalars, boxes, procs, and
structural types containing only other owned types.
All `Send` types are `'static`.
# Memory and concurrency models
-Rust has a memory model centered around concurrently-executing _tasks_. Thus
+Rust has a memory model centered around concurrently-executing _threads_. Thus
its memory model and its concurrency model are best discussed simultaneously,
as parts of each only make sense when considered from the perspective of the
other.
When reading about the memory model, keep in mind that it is partitioned in
-order to support tasks; and when reading about tasks, keep in mind that their
+order to support threads; and when reading about threads, keep in mind that their
isolation and communication mechanisms are only possible due to the ownership
and lifetime semantics of the memory model.
## Memory model
A Rust program's memory consists of a static set of *items*, a set of
-[tasks](#tasks) each with its own *stack*, and a *heap*. Immutable portions of
-the heap may be shared between tasks, mutable portions may not.
+[threads](#threads) each with its own *stack*, and a *heap*. Immutable portions of
+the heap may be shared between threads, mutable portions may not.
Allocations in the stack consist of *slots*, and allocations in the heap
consist of *boxes*.
value calculated at compile-time and stored uniquely in the memory image of the
rust process. Items are neither dynamically allocated nor freed.
-A task's _stack_ consists of activation frames automatically allocated on entry
-to each function as the task executes. A stack allocation is reclaimed when
+A thread's _stack_ consists of activation frames automatically allocated on entry
+to each function as the thread executes. A stack allocation is reclaimed when
control leaves the frame containing it.
The _heap_ is a general term that describes boxes. The lifetime of an
### Memory ownership
-A task owns all memory it can *safely* reach through local variables, as well
+A thread owns all memory it can *safely* reach through local variables, as well
as boxes and references.
-When a task sends a value that has the `Send` trait to another task, it loses
+When a thread sends a value that has the `Send` trait to another thread, it loses
ownership of the value sent and can no longer refer to it. This is statically
guaranteed by the combined use of "move semantics", and the compiler-checked
_meaning_ of the `Send` trait: it is only instantiated for (transitively)
When a stack frame is exited, its local allocations are all released, and its
references to boxes are dropped.
-When a task finishes, its stack is necessarily empty and it therefore has no
+When a thread finishes, its stack is necessarily empty and it therefore has no
references to any boxes; the remainder of its heap is immediately freed.
### Memory slots
-A task's stack contains slots.
+A thread's stack contains slots.
A _slot_ is a component of a stack frame, either a function parameter, a
[temporary](#lvalues,-rvalues-and-temporaries), or a local variable.
// attempting to use `x` will result in an error here
```
-## Tasks
+## Threads
-An executing Rust program consists of a tree of tasks. A Rust _task_ consists
-of an entry function, a stack, a set of outgoing communication channels and
-incoming communication ports, and ownership of some portion of the heap of a
-single operating-system process.
+Rust's primary concurrency mechanism is called a **thread**.
-### Communication between tasks
+### Communication between threads
-Rust tasks are isolated and generally unable to interfere with one another's
+Rust threads are isolated and generally unable to interfere with one another's
memory directly, except through [`unsafe` code](#unsafe-functions). All
-contact between tasks is mediated by safe forms of ownership transfer, and data
+contact between threads is mediated by safe forms of ownership transfer, and data
races on memory are prohibited by the type system.
-When you wish to send data between tasks, the values are restricted to the
+When you wish to send data between threads, the values are restricted to the
[`Send` type-kind](#type-kinds). Restricting communication interfaces to this
-kind ensures that no references move between tasks. Thus access to an entire
+kind ensures that no references move between threads. Thus access to an entire
data structure can be mediated through its owning "root" value; no further
locking or copying is required to avoid data races within the substructure of
such a value.
-### Task lifecycle
+### Thread
-The _lifecycle_ of a task consists of a finite set of states and events that
-cause transitions between the states. The lifecycle states of a task are:
+The _lifecycle_ of a threads consists of a finite set of states and events that
+cause transitions between the states. The lifecycle states of a thread are:
* running
* blocked
* panicked
* dead
-A task begins its lifecycle — once it has been spawned — in the
+A thread begins its lifecycle — once it has been spawned — in the
*running* state. In this state it executes the statements of its entry
function, and any functions called by the entry function.
-A task may transition from the *running* state to the *blocked* state any time
+A thread may transition from the *running* state to the *blocked* state any time
it makes a blocking communication call. When the call can be completed —
when a message arrives at a sender, or a buffer opens to receive a message
-— then the blocked task will unblock and transition back to *running*.
+— then the blocked thread will unblock and transition back to *running*.
-A task may transition to the *panicked* state at any time, due being killed by
+A thread may transition to the *panicked* state at any time, due being killed by
some external event or internally, from the evaluation of a `panic!()` macro.
-Once *panicking*, a task unwinds its stack and transitions to the *dead* state.
-Unwinding the stack of a task is done by the task itself, on its own control
+Once *panicking*, a thread unwinds its stack and transitions to the *dead* state.
+Unwinding the stack of a thread is done by the thread itself, on its own control
stack. If a value with a destructor is freed during unwinding, the code for the
-destructor is run, also on the task's control stack. Running the destructor
+destructor is run, also on the thread's control stack. Running the destructor
code causes a temporary transition to a *running* state, and allows the
-destructor code to cause any subsequent state transitions. The original task
+destructor code to cause any subsequent state transitions. The original thread
of unwinding and panicking thereby may suspend temporarily, and may involve
(recursive) unwinding of the stack of a failed destructor. Nonetheless, the
outermost unwinding activity will continue until the stack is unwound and the
-task transitions to the *dead* state. There is no way to "recover" from task
-panics. Once a task has temporarily suspended its unwinding in the *panicking*
+thread transitions to the *dead* state. There is no way to "recover" from thread
+panics. Once a thread has temporarily suspended its unwinding in the *panicking*
state, a panic occurring from within this destructor results in *hard* panic.
A hard panic currently results in the process aborting.
-A task in the *dead* state cannot transition to other states; it exists only to
-have its termination status inspected by other tasks, and/or to await
+A thread in the *dead* state cannot transition to other states; it exists only to
+have its termination status inspected by other threads, and/or to await
reclamation when the last reference to it drops.
# Runtime services, linkage and debugging
The Rust _runtime_ is a relatively compact collection of Rust code that
-provides fundamental services and datatypes to all Rust tasks at run-time. It
+provides fundamental services and datatypes to all Rust threads at run-time. It
is smaller and simpler than many modern language runtimes. It is tightly
-integrated into the language's execution model of memory, tasks, communication
+integrated into the language's execution model of memory, threads, communication
and logging.
### Memory allocation
needed. The default implementation of the service-provider interface consists
of the C runtime functions `malloc` and `free`.
-The runtime memory-management system, in turn, supplies Rust tasks with
+The runtime memory-management system, in turn, supplies Rust threads with
facilities for allocating releasing stacks, as well as allocating and freeing
heap data.
The runtime provides C and Rust code to assist with various built-in types,
such as arrays, strings, and the low level communication system (ports,
-channels, tasks).
+channels, threads).
Support for other built-in types such as simple types, tuples and enums is
open-coded by the Rust compiler.
-### Task scheduling and communication
+### Thread scheduling and communication
-The runtime provides code to manage inter-task communication. This includes
-the system of task-lifecycle state transitions depending on the contents of
+The runtime provides code to manage inter-thread communication. This includes
+the system of thread-lifecycle state transitions depending on the contents of
queues, as well as code to copy values between queues and their recipients and
to serialize values for transmission over operating-system inter-process
communication facilities.
<context attribute="CharEscape" lineEndContext="#pop" name="CharEscape">
<AnyChar String="nrt\'"" attribute="CharEscape" context="#pop"/>
<RegExpr String="x[0-9a-fA-F]{2}" attribute="CharEscape" context="#pop"/>
+ <RegExpr String="u\{[0-9a-fA-F]{1,6}\}" attribute="CharEscape" context="#pop"/>
<RegExpr String="u[0-9a-fA-F]{4}" attribute="CharEscape" context="#pop"/>
<RegExpr String="U[0-9a-fA-F]{8}" attribute="CharEscape" context="#pop"/>
<RegExpr String="." attribute="Error" context="#pop"/>
<Detect2Chars char="*" char1="/" attribute="Comment" context="#pop" endRegion="Comment"/>
</context>
</contexts>
- <itemDatas>
+ <itemDatas>
<itemData name="Normal Text" defStyleNum="dsNormal"/>
<itemData name="Keyword" defStyleNum="dsKeyword" color="#770088" bold="1"/>
<itemData name="Self" defStyleNum="dsKeyword" color="#FF0000" bold="1"/>
for src in target_libs:
shutil.copy(src, target_lib_dir)
- # Copy license files
- lic_dir = os.path.join(rust_root, "bin", "third-party")
- if os.path.exists(lic_dir):
- shutil.rmtree(lic_dir) # copytree() won't overwrite existing files
- shutil.copytree(os.path.join(os.path.dirname(__file__), "third-party"), lic_dir)
-
if __name__=="__main__":
make_win_dist(sys.argv[1], sys.argv[2], sys.argv[3])
;
LIT_FLOAT
- : [0-9][0-9_]* ('.' | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? SUFFIX?)
+ : [0-9][0-9_]* ( '.' {_input.LA(1) != '.'}?
+ | ('.' [0-9][0-9_]*)? ([eE] [-+]? [0-9][0-9_]*)? SUFFIX?)
;
LIT_STR
"SHL" => token::BinOp(token::Shl),
"LBRACE" => token::OpenDelim(token::Brace),
"RARROW" => token::RArrow,
- "LIT_STR" => token::Literal(token::Str_(Name(0))),
+ "LIT_STR" => token::Literal(token::Str_(Name(0)), None),
"DOTDOT" => token::DotDot,
"MOD_SEP" => token::ModSep,
"DOTDOTDOT" => token::DotDotDot,
"ANDAND" => token::AndAnd,
"AT" => token::At,
"LBRACKET" => token::OpenDelim(token::Bracket),
- "LIT_STR_RAW" => token::Literal(token::StrRaw(Name(0), 0)),
+ "LIT_STR_RAW" => token::Literal(token::StrRaw(Name(0), 0), None),
"RPAREN" => token::CloseDelim(token::Paren),
"SLASH" => token::BinOp(token::Slash),
"COMMA" => token::Comma,
"TILDE" => token::Tilde,
"IDENT" => id(),
"PLUS" => token::BinOp(token::Plus),
- "LIT_CHAR" => token::Literal(token::Char(Name(0))),
- "LIT_BYTE" => token::Literal(token::Byte(Name(0))),
+ "LIT_CHAR" => token::Literal(token::Char(Name(0)), None),
+ "LIT_BYTE" => token::Literal(token::Byte(Name(0)), None),
"EQ" => token::Eq,
"RBRACKET" => token::CloseDelim(token::Bracket),
"COMMENT" => token::Comment,
"BINOP" => token::BinOp(token::Plus),
"POUND" => token::Pound,
"OROR" => token::OrOr,
- "LIT_INTEGER" => token::Literal(token::Integer(Name(0))),
+ "LIT_INTEGER" => token::Literal(token::Integer(Name(0)), None),
"BINOPEQ" => token::BinOpEq(token::Plus),
- "LIT_FLOAT" => token::Literal(token::Float(Name(0))),
+ "LIT_FLOAT" => token::Literal(token::Float(Name(0)), None),
"WHITESPACE" => token::Whitespace,
"UNDERSCORE" => token::Underscore,
"MINUS" => token::BinOp(token::Minus),
"OR" => token::BinOp(token::Or),
"GT" => token::Gt,
"LE" => token::Le,
- "LIT_BINARY" => token::Literal(token::Binary(Name(0))),
- "LIT_BINARY_RAW" => token::Literal(token::BinaryRaw(Name(0), 0)),
+ "LIT_BINARY" => token::Literal(token::Binary(Name(0)), None),
+ "LIT_BINARY_RAW" => token::Literal(token::BinaryRaw(Name(0), 0), None),
_ => continue,
};
token::BinOp(..) => token::BinOp(str_to_binop(content)),
token::BinOpEq(..) => token::BinOpEq(str_to_binop(content.slice_to(
content.len() - 1))),
- token::Literal(token::Str_(..)) => token::Literal(token::Str_(fix(content))),
- token::Literal(token::StrRaw(..)) => token::Literal(token::StrRaw(fix(content),
- count(content))),
- token::Literal(token::Char(..)) => token::Literal(token::Char(fixchar(content))),
- token::Literal(token::Byte(..)) => token::Literal(token::Byte(fixchar(content))),
+ token::Literal(token::Str_(..), n) => token::Literal(token::Str_(fix(content)), n),
+ token::Literal(token::StrRaw(..), n) => token::Literal(token::StrRaw(fix(content),
+ count(content)), n),
+ token::Literal(token::Char(..), n) => token::Literal(token::Char(fixchar(content)), n),
+ token::Literal(token::Byte(..), n) => token::Literal(token::Byte(fixchar(content)), n),
token::DocComment(..) => token::DocComment(nm),
- token::Literal(token::Integer(..)) => token::Literal(token::Integer(nm)),
- token::Literal(token::Float(..)) => token::Literal(token::Float(nm)),
- token::Literal(token::Binary(..)) => token::Literal(token::Binary(nm)),
- token::Literal(token::BinaryRaw(..)) => token::Literal(token::BinaryRaw(fix(content),
- count(content))),
+ token::Literal(token::Integer(..), n) => token::Literal(token::Integer(nm), n),
+ token::Literal(token::Float(..), n) => token::Literal(token::Float(nm), n),
+ token::Literal(token::Binary(..), n) => token::Literal(token::Binary(nm), n),
+ token::Literal(token::BinaryRaw(..), n) => token::Literal(token::BinaryRaw(fix(content),
+ count(content)), n),
token::Ident(..) => token::Ident(ast::Ident { name: nm, ctxt: 0 },
token::ModName),
token::Lifetime(..) => token::Lifetime(ast::Ident { name: nm, ctxt: 0 }),
};
let sp = syntax::codemap::Span {
- lo: syntax::codemap::BytePos(from_str::<u32>(start).unwrap() - offset),
- hi: syntax::codemap::BytePos(from_str::<u32>(end).unwrap() + 1),
+ lo: syntax::codemap::BytePos(start.parse::<u32>().unwrap() - offset),
+ hi: syntax::codemap::BytePos(end.parse::<u32>().unwrap() + 1),
expn_id: syntax::codemap::NO_EXPANSION
};
let token_map = parse_token_list(token_file.read_to_string().unwrap().as_slice());
let mut stdin = std::io::stdin();
- let mut antlr_tokens = stdin.lines().map(|l| parse_antlr_token(l.unwrap().as_slice().trim(),
+ let mut lock = stdin.lock();
+ let lines = lock.lines();
+ let mut antlr_tokens = lines.map(|l| parse_antlr_token(l.unwrap().as_slice().trim(),
&token_map));
let code = File::open(&Path::new(args[1].as_slice())).unwrap().read_to_string().unwrap();
ref c => assert!(c == &antlr_tok.tok, "{} is not {}", rustc_tok, antlr_tok)
}
)
- )
+ );
matches!(
- token::Literal(token::Byte(..)),
- token::Literal(token::Char(..)),
- token::Literal(token::Integer(..)),
- token::Literal(token::Float(..)),
- token::Literal(token::Str_(..)),
- token::Literal(token::StrRaw(..)),
- token::Literal(token::Binary(..)),
- token::Literal(token::BinaryRaw(..)),
+ token::Literal(token::Byte(..), _),
+ token::Literal(token::Char(..), _),
+ token::Literal(token::Integer(..), _),
+ token::Literal(token::Float(..), _),
+ token::Literal(token::Str_(..), _),
+ token::Literal(token::StrRaw(..), _),
+ token::Literal(token::Binary(..), _),
+ token::Literal(token::BinaryRaw(..), _),
token::Ident(..),
token::Lifetime(..),
token::Interpolated(..),
//! let five = five.clone();
//!
//! Thread::spawn(move || {
-//! let mut number = five.lock();
+//! let mut number = five.lock().unwrap();
//!
//! *number += 1;
//!
use core::ops::{Drop, Deref};
use core::option::Option;
use core::option::Option::{Some, None};
-use core::ptr::{mod, RawPtr};
+use core::ptr::{mod, PtrExt};
use heap::deallocate;
/// An atomically reference counted wrapper for shared state.
let a = Arc::new(Cycle { x: Mutex::new(None) });
let b = a.clone().downgrade();
- *a.x.lock() = Some(b);
+ *a.x.lock().unwrap() = Some(b);
// hopefully we don't double-free (or leak)...
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use core::ptr::RawPtr;
+use core::ptr::PtrExt;
// FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias`
mod test {
extern crate test;
use self::test::Bencher;
- use core::ptr::RawPtr;
+ use core::ptr::PtrExt;
use heap;
#[test]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Task-local reference-counted boxes (the `Rc<T>` type).
+//! Thread-local reference-counted boxes (the `Rc<T>` type).
//!
//! The `Rc<T>` type provides shared ownership of an immutable value. Destruction is deterministic,
//! and will occur as soon as the last owner is gone. It is marked as non-sendable because it
use core::ops::{Deref, Drop};
use core::option::Option;
use core::option::Option::{Some, None};
-use core::ptr::{mod, RawPtr};
+use core::ptr::{mod, PtrExt};
use core::result::Result;
use core::result::Result::{Ok, Err};
let size = calculate_size::<T>(self.capacity);
deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size,
mem::min_align_of::<TypedArenaChunk<T>>());
- if next.is_not_null() {
+ if !next.is_null() {
let capacity = (*next).capacity;
(*next).destroy(capacity);
}
/// Convert the `Rawlink` into an Option value
fn resolve_immut<'a>(&self) -> Option<&'a T> {
unsafe {
- self.p.as_ref()
+ mem::transmute(self.p.as_ref())
}
}
pub use core::ops::{Drop, Fn, FnMut, FnOnce};
pub use core::option::Option;
pub use core::option::Option::{Some, None};
- pub use core::ptr::RawPtr;
+ pub use core::ptr::PtrExt;
pub use core::result::Result;
pub use core::result::Result::{Ok, Err};
// in core and collections (may differ).
pub use slice::{PartialEqSliceExt, OrdSliceExt};
pub use slice::{AsSlice, SliceExt};
- pub use str::{from_str, Str};
+ pub use str::{from_str, Str, StrExt};
// from other crates.
pub use alloc::boxed::Box;
use core::mem;
use core::ops::{FnMut,SliceMut};
use core::prelude::{Clone, Greater, Iterator, IteratorExt, Less, None, Option};
-use core::prelude::{Ord, Ordering, RawPtr, Some, range};
+use core::prelude::{Ord, Ordering, PtrExt, Some, range};
use core::ptr;
use core::slice as core_slice;
use self::Direction::*;
#[cfg(test)]
mod tests {
use std::boxed::Box;
- use prelude::*;
+ use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal};
+ use prelude::{SliceExt, Iterator, IteratorExt, DoubleEndedIteratorExt};
+ use prelude::{OrdSliceExt, CloneSliceExt, PartialEqSliceExt, AsSlice};
+ use prelude::{RandomAccessIterator, Ord, VectorVector};
use core::cell::Cell;
use core::default::Default;
use core::mem;
- use std::rand::{Rng, task_rng};
+ use std::rand::{Rng, thread_rng};
use std::rc::Rc;
use super::ElementSwaps;
fn test_sort() {
for len in range(4u, 25) {
for _ in range(0i, 100) {
- let mut v = task_rng().gen_iter::<uint>().take(len)
+ let mut v = thread_rng().gen_iter::<uint>().take(len)
.collect::<Vec<uint>>();
let mut v1 = v.clone();
// number this element is, i.e. the second elements
// will occur in sorted order.
let mut v = range(0, len).map(|_| {
- let n = task_rng().gen::<uint>() % 10;
+ let n = thread_rng().gen::<uint>() % 10;
counts[n] += 1;
(n, counts[n])
}).collect::<Vec<(uint, int)>>();
pub use core::str::{Split, SplitTerminator};
pub use core::str::{SplitN, RSplitN};
-// FIXME(conventions): ensure bit/char conventions are followed by str's API
-
/*
Section: Creating a string
*/
#[cfg(test)]
mod tests {
- use std::iter::AdditiveIterator;
- use std::iter::range;
- use std::default::Default;
- use std::char::Char;
- use std::clone::Clone;
- use std::cmp::{Ord, PartialOrd, Equiv};
- use std::cmp::Ordering::{Equal, Greater, Less};
- use std::option::Option::{mod, Some, None};
- use std::result::Result::{Ok, Err};
- use std::ptr::RawPtr;
- use std::iter::{Iterator, IteratorExt, DoubleEndedIteratorExt};
+ use prelude::*;
- use super::*;
+ use core::default::Default;
+ use core::iter::AdditiveIterator;
+ use super::{from_utf8, is_utf8, raw};
use super::MaybeOwned::{Owned, Slice};
- use std::slice::{AsSlice, SliceExt};
- use string::{String, ToString};
- use vec::Vec;
- use slice::CloneSliceExt;
-
- use unicode::char::UnicodeChar;
+ use super::Utf8Error;
#[test]
fn test_le() {
#[cfg(test)]
mod bench {
use super::*;
- use prelude::*;
+ use prelude::{SliceExt, IteratorExt, DoubleEndedIteratorExt};
use test::Bencher;
use test::black_box;
//! An owned, growable string that enforces that its contents are valid UTF-8.
+#![stable]
+
use core::prelude::*;
use core::borrow::{Cow, IntoCow};
vec: Vec<u8>,
}
+/// A possible error value from the `String::from_utf8` function.
+#[stable]
+pub struct FromUtf8Error {
+ bytes: Vec<u8>,
+ error: Utf8Error,
+}
+
+/// A possible error value from the `String::from_utf16` function.
+#[stable]
+#[allow(missing_copy_implementations)]
+pub struct FromUtf16Error(());
+
impl String {
/// Creates a new string buffer initialized with the empty string.
///
/// use std::str::Utf8Error;
///
/// let hello_vec = vec![104, 101, 108, 108, 111];
- /// let s = String::from_utf8(hello_vec);
- /// assert_eq!(s, Ok("hello".to_string()));
+ /// let s = String::from_utf8(hello_vec).unwrap();
+ /// assert_eq!(s, "hello");
///
/// let invalid_vec = vec![240, 144, 128];
- /// let s = String::from_utf8(invalid_vec);
- /// assert_eq!(s, Err((vec![240, 144, 128], Utf8Error::TooShort)));
+ /// let s = String::from_utf8(invalid_vec).err().unwrap();
+ /// assert_eq!(s.utf8_error(), Utf8Error::TooShort);
+ /// assert_eq!(s.into_bytes(), vec![240, 144, 128]);
/// ```
#[inline]
- #[unstable = "error type may change"]
- pub fn from_utf8(vec: Vec<u8>) -> Result<String, (Vec<u8>, Utf8Error)> {
+ #[stable]
+ pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
match str::from_utf8(vec.as_slice()) {
Ok(..) => Ok(String { vec: vec }),
- Err(e) => Err((vec, e))
+ Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
}
}
/// let output = String::from_utf8_lossy(input);
/// assert_eq!(output.as_slice(), "Hello \u{FFFD}World");
/// ```
- #[unstable = "return type may change"]
+ #[stable]
pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> {
match str::from_utf8(v) {
Ok(s) => return Cow::Borrowed(s),
/// // 𝄞music
/// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0x0069, 0x0063];
- /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
+ /// assert_eq!(String::from_utf16(v).unwrap(),
+ /// "𝄞music".to_string());
///
/// // 𝄞mu<invalid>ic
/// v[4] = 0xD800;
- /// assert_eq!(String::from_utf16(v), None);
+ /// assert!(String::from_utf16(v).is_err());
/// ```
- #[unstable = "error value in return may change"]
- pub fn from_utf16(v: &[u16]) -> Option<String> {
+ #[stable]
+ pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
let mut s = String::with_capacity(v.len());
for c in unicode_str::utf16_items(v) {
match c {
Utf16Item::ScalarValue(c) => s.push(c),
- Utf16Item::LoneSurrogate(_) => return None
+ Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
}
}
- Some(s)
+ Ok(s)
}
/// Decode a UTF-16 encoded vector `v` into a string, replacing
/// # Examples
///
/// ```rust
+ /// # #![allow(deprecated)]
/// let chars = &['h', 'e', 'l', 'l', 'o'];
/// let s = String::from_chars(chars);
/// assert_eq!(s.as_slice(), "hello");
/// ```
#[inline]
- #[unstable = "may be removed in favor of .collect()"]
+ #[deprecated = "use .collect() instead"]
pub fn from_chars(chs: &[char]) -> String {
chs.iter().map(|c| *c).collect()
}
/// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
/// * We assume that the `Vec` contains valid UTF-8.
#[inline]
- #[unstable = "function just moved from string::raw"]
+ #[stable]
pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
String {
vec: Vec::from_raw_parts(buf, length, capacity),
/// it contains valid UTF-8. This is unsafe because it assumes that
/// the UTF-8-ness of the vector has already been validated.
#[inline]
- #[unstable = "awaiting stabilization"]
+ #[stable]
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String {
String { vec: bytes }
}
/// # Examples
///
/// ```
+ /// # #![allow(deprecated)]
/// let s = String::from_char(5, 'a');
/// assert_eq!(s.as_slice(), "aaaaa");
/// ```
#[inline]
- #[unstable = "may be replaced with iterators, questionable usability, and \
- the name may change"]
+ #[deprecated = "use repeat(ch).take(length).collect() instead"]
pub fn from_char(length: uint, ch: char) -> String {
if length == 0 {
return String::new()
/// assert_eq!(s.as_slice(), "foobar");
/// ```
#[inline]
- #[unstable = "extra variants of `push`, could possibly be based on iterators"]
+ #[stable]
pub fn push_str(&mut self, string: &str) {
self.vec.push_all(string.as_bytes())
}
/// # Examples
///
/// ```
+ /// # #![allow(deprecated)]
/// let mut s = String::from_str("foo");
/// s.grow(5, 'Z');
/// assert_eq!(s.as_slice(), "fooZZZZZ");
/// ```
#[inline]
- #[unstable = "duplicate of iterator-based functionality"]
+ #[deprecated = "deprecated in favor of .extend(repeat(ch).take(count))"]
pub fn grow(&mut self, count: uint, ch: char) {
for _ in range(0, count) {
self.push(ch)
}
}
- /// Returns the number of bytes that this string buffer can hold without reallocating.
+ /// Returns the number of bytes that this string buffer can hold without
+ /// reallocating.
///
/// # Examples
///
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
- #[unstable = "matches collection reform specification, waiting for dust to settle"]
+ #[stable]
pub fn capacity(&self) -> uint {
self.vec.capacity()
}
self.vec.reserve(extra)
}
- /// Reserves capacity for at least `additional` more bytes to be inserted in the given
- /// `String`. The collection may reserve more space to avoid frequent reallocations.
+ /// Reserves capacity for at least `additional` more bytes to be inserted
+ /// in the given `String`. The collection may reserve more space to avoid
+ /// frequent reallocations.
///
/// # Panics
///
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
- #[unstable = "matches collection reform specification, waiting for dust to settle"]
+ #[stable]
pub fn reserve(&mut self, additional: uint) {
self.vec.reserve(additional)
}
- /// Reserves the minimum capacity for exactly `additional` more bytes to be inserted in the
- /// given `String`. Does nothing if the capacity is already sufficient.
+ /// Reserves the minimum capacity for exactly `additional` more bytes to be
+ /// inserted in the given `String`. Does nothing if the capacity is already
+ /// sufficient.
///
- /// Note that the allocator may give the collection more space than it requests. Therefore
- /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
- /// insertions are expected.
+ /// Note that the allocator may give the collection more space than it
+ /// requests. Therefore capacity can not be relied upon to be precisely
+ /// minimal. Prefer `reserve` if future insertions are expected.
///
/// # Panics
///
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
- #[unstable = "matches collection reform specification, waiting for dust to settle"]
+ #[stable]
pub fn reserve_exact(&mut self, additional: uint) {
self.vec.reserve_exact(additional)
}
/// assert_eq!(s.capacity(), 3);
/// ```
#[inline]
- #[unstable = "matches collection reform specification, waiting for dust to settle"]
+ #[stable]
pub fn shrink_to_fit(&mut self) {
self.vec.shrink_to_fit()
}
/// assert_eq!(s.as_slice(), "abc123");
/// ```
#[inline]
- #[stable = "function just renamed from push_char"]
+ #[stable]
pub fn push(&mut self, ch: char) {
if (ch as u32) < 0x80 {
self.vec.push(ch as u8);
/// assert_eq!(s.as_slice(), "he");
/// ```
#[inline]
- #[unstable = "the panic conventions for strings are under development"]
+ #[stable]
pub fn truncate(&mut self, new_len: uint) {
assert!(self.is_char_boundary(new_len));
self.vec.truncate(new_len)
/// assert_eq!(s.pop(), None);
/// ```
#[inline]
- #[unstable = "this function was just renamed from pop_char"]
+ #[stable]
pub fn pop(&mut self) -> Option<char> {
let len = self.len();
if len == 0 {
}
/// Removes the character from the string buffer at byte position `idx` and
- /// returns it. Returns `None` if `idx` is out of bounds.
+ /// returns it.
///
/// # Warning
///
///
/// # Panics
///
- /// If `idx` does not lie on a character boundary, then this function will
- /// panic.
+ /// If `idx` does not lie on a character boundary, or if it is out of
+ /// bounds, then this function will panic.
///
/// # Examples
///
/// ```
/// let mut s = String::from_str("foo");
- /// assert_eq!(s.remove(0), Some('f'));
- /// assert_eq!(s.remove(1), Some('o'));
- /// assert_eq!(s.remove(0), Some('o'));
- /// assert_eq!(s.remove(0), None);
+ /// assert_eq!(s.remove(0), 'f');
+ /// assert_eq!(s.remove(1), 'o');
+ /// assert_eq!(s.remove(0), 'o');
/// ```
- #[unstable = "the panic semantics of this function and return type \
- may change"]
- pub fn remove(&mut self, idx: uint) -> Option<char> {
+ #[stable]
+ pub fn remove(&mut self, idx: uint) -> char {
let len = self.len();
- if idx >= len { return None }
+ assert!(idx <= len);
let CharRange { ch, next } = self.char_range_at(idx);
unsafe {
len - next);
self.vec.set_len(len - (next - idx));
}
- Some(ch)
+ ch
}
/// Insert a character into the string buffer at byte position `idx`.
///
/// If `idx` does not lie on a character boundary or is out of bounds, then
/// this function will panic.
- #[unstable = "the panic semantics of this function are uncertain"]
+ #[stable]
pub fn insert(&mut self, idx: uint, ch: char) {
let len = self.len();
assert!(idx <= len);
/// }
/// assert_eq!(s.as_slice(), "olleh");
/// ```
- #[unstable = "the name of this method may be changed"]
+ #[stable]
pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
&mut self.vec
}
/// v.push('a');
/// assert!(!v.is_empty());
/// ```
+ #[stable]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Truncates the string, returning it to 0 length.
}
}
+impl FromUtf8Error {
+ /// Consume this error, returning the bytes that were attempted to make a
+ /// `String` with.
+ #[stable]
+ pub fn into_bytes(self) -> Vec<u8> { self.bytes }
+
+ /// Access the underlying UTF8-error that was the cause of this error.
+ #[stable]
+ pub fn utf8_error(&self) -> Utf8Error { self.error }
+}
+
+impl fmt::Show for FromUtf8Error {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.error.fmt(f)
+ }
+}
+
+impl fmt::Show for FromUtf16Error {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ "invalid utf-16: lone surrogate found".fmt(f)
+ }
+}
+
#[experimental = "waiting on FromIterator stabilization"]
impl FromIterator<char> for String {
fn from_iter<I:Iterator<char>>(iterator: I) -> String {
}
/// Trait for converting a type to a string, consuming it in the process.
+#[deprecated = "trait will be removed"]
pub trait IntoString {
/// Consume and convert to a string.
fn into_string(self) -> String;
use prelude::*;
use test::Bencher;
- use str::{StrExt, Utf8Error};
+ use str::Utf8Error;
use str;
use super::as_string;
#[test]
fn test_from_utf8() {
let xs = b"hello".to_vec();
- assert_eq!(String::from_utf8(xs),
- Ok(String::from_str("hello")));
+ assert_eq!(String::from_utf8(xs).unwrap(),
+ String::from_str("hello"));
let xs = "ศไทย中华Việt Nam".as_bytes().to_vec();
- assert_eq!(String::from_utf8(xs),
- Ok(String::from_str("ศไทย中华Việt Nam")));
+ assert_eq!(String::from_utf8(xs).unwrap(),
+ String::from_str("ศไทย中华Việt Nam"));
let xs = b"hello\xFF".to_vec();
- assert_eq!(String::from_utf8(xs),
- Err((b"hello\xFF".to_vec(), Utf8Error::TooShort)));
+ let err = String::from_utf8(xs).err().unwrap();
+ assert_eq!(err.utf8_error(), Utf8Error::TooShort);
+ assert_eq!(err.into_bytes(), b"hello\xff".to_vec());
}
#[test]
fn test_utf16_invalid() {
// completely positive cases tested above.
// lead + eof
- assert_eq!(String::from_utf16(&[0xD800]), None);
+ assert!(String::from_utf16(&[0xD800]).is_err());
// lead + lead
- assert_eq!(String::from_utf16(&[0xD800, 0xD800]), None);
+ assert!(String::from_utf16(&[0xD800, 0xD800]).is_err());
// isolated trail
- assert_eq!(String::from_utf16(&[0x0061, 0xDC00]), None);
+ assert!(String::from_utf16(&[0x0061, 0xDC00]).is_err());
// general
- assert_eq!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]), None);
+ assert!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]).is_err());
}
#[test]
#[test]
fn remove() {
let mut s = "ศไทย中华Việt Nam; foobar".to_string();;
- assert_eq!(s.remove(0), Some('ศ'));
+ assert_eq!(s.remove(0), 'ศ');
assert_eq!(s.len(), 33);
assert_eq!(s, "ไทย中华Việt Nam; foobar");
- assert_eq!(s.remove(33), None);
- assert_eq!(s.remove(300), None);
- assert_eq!(s.remove(17), Some('ệ'));
+ assert_eq!(s.remove(17), 'ệ');
assert_eq!(s, "ไทย中华Vit Nam; foobar");
}
use clone::Clone;
use cmp::PartialEq;
use default::Default;
-use kinds::{marker, Copy};
+use kinds::{Copy, Send};
use ops::{Deref, DerefMut, Drop};
use option::Option;
use option::Option::{None, Some};
#[stable]
pub struct Cell<T> {
value: UnsafeCell<T>,
- noshare: marker::NoSync,
}
impl<T:Copy> Cell<T> {
pub fn new(value: T) -> Cell<T> {
Cell {
value: UnsafeCell::new(value),
- noshare: marker::NoSync,
}
}
}
}
+#[stable]
+unsafe impl<T> Send for Cell<T> where T: Send {}
+
#[stable]
impl<T:Copy> Clone for Cell<T> {
fn clone(&self) -> Cell<T> {
pub struct RefCell<T> {
value: UnsafeCell<T>,
borrow: Cell<BorrowFlag>,
- noshare: marker::NoSync,
}
// Values [1, MAX-1] represent the number of `Ref` active
RefCell {
value: UnsafeCell::new(value),
borrow: Cell::new(UNUSED),
- noshare: marker::NoSync,
}
}
}
}
+#[stable]
+unsafe impl<T> Send for RefCell<T> where T: Send {}
+
#[stable]
impl<T: Clone> Clone for RefCell<T> {
fn clone(&self) -> RefCell<T> {
/// but can be overridden to reuse the resources of `a` to avoid unnecessary
/// allocations.
#[inline(always)]
- #[unstable = "this function rarely unused"]
+ #[unstable = "this function is rarely used"]
fn clone_from(&mut self, source: &Self) {
*self = source.clone()
}
);
}
-/// Runtime assertion, only without `--cfg ndebug`
-#[macro_export]
-macro_rules! debug_assert {
- ($(a:tt)*) => ({
- if cfg!(not(ndebug)) {
- assert!($($a)*);
- }
- })
-}
-
/// Runtime assertion for equality, for details see std::macros
#[macro_export]
macro_rules! assert_eq {
})
}
-/// Runtime assertion, disableable at compile time
+/// Runtime assertion, disableable at compile time with `--cfg ndebug`
#[macro_export]
macro_rules! debug_assert {
($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
pub use num::{ToPrimitive, FromPrimitive};
pub use option::Option;
pub use option::Option::{Some, None};
-pub use ptr::RawPtr;
+pub use ptr::{PtrExt, MutPtrExt};
pub use result::Result;
pub use result::Result::{Ok, Err};
pub use str::{Str, StrExt};
//! typically limited to a few patterns.
//!
//! Use the [`null` function](fn.null.html) to create null pointers,
-//! the [`is_null`](trait.RawPtr.html#tymethod.is_null)
-//! and [`is_not_null`](trait.RawPtr.html#method.is_not_null)
-//! methods of the [`RawPtr` trait](trait.RawPtr.html) to check for null.
-//! The `RawPtr` trait is imported by the prelude, so `is_null` etc.
-//! work everywhere. The `RawPtr` also defines the `offset` method,
+//! 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.
//!
//! # Common ways to create unsafe pointers
//! but C APIs hand out a lot of pointers generally, so are a common source
//! of unsafe pointers in Rust.
+#![stable]
+
use mem;
use clone::Clone;
use intrinsics;
+use option::Option::{mod, Some, None};
use kinds::{Send, Sync};
-use option::Option;
-use option::Option::{Some, None};
use cmp::{PartialEq, Eq, Ord, PartialOrd, Equiv};
-use cmp::Ordering;
-use cmp::Ordering::{Less, Equal, Greater};
+use cmp::Ordering::{mod, Less, Equal, Greater};
// FIXME #19649: instrinsic docs don't render, so these have no docs :(
/// assert!(p.is_null());
/// ```
#[inline]
-#[unstable = "may need a different name after pending changes to pointer types"]
+#[stable]
pub fn null<T>() -> *const T { 0 as *const T }
/// Creates a null mutable raw pointer.
/// assert!(p.is_null());
/// ```
#[inline]
-#[unstable = "may need a different name after pending changes to pointer types"]
+#[stable]
pub fn null_mut<T>() -> *mut T { 0 as *mut T }
-/// Zeroes out `count * size_of::<T>` bytes of memory at `dst`. `count` may be `0`.
+/// Zeroes out `count * size_of::<T>` bytes of memory at `dst`. `count` may be
+/// `0`.
///
/// # Safety
///
-/// Beyond accepting a raw pointer, this is unsafe because it will not drop the contents of `dst`,
-/// and may be used to create invalid instances of `T`.
+/// Beyond accepting a raw pointer, this is unsafe because it will not drop the
+/// contents of `dst`, and may be used to create invalid instances of `T`.
#[inline]
-#[experimental = "uncertain about naming and semantics"]
-#[allow(experimental)]
+#[unstable = "may play a larger role in std::ptr future extensions"]
pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
set_memory(dst, 0, count);
}
/// Swaps the values at two mutable locations of the same type, without
-/// deinitialising either. They may overlap, unlike `mem::swap` which is otherwise
-/// equivalent.
+/// deinitialising either. They may overlap, unlike `mem::swap` which is
+/// otherwise equivalent.
///
/// # Safety
///
/// This is only unsafe because it accepts a raw pointer.
#[inline]
-#[unstable]
+#[stable]
pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
// Give ourselves some scratch space to work with
let mut tmp: T = mem::uninitialized();
/// This is only unsafe because it accepts a raw pointer.
/// Otherwise, this operation is identical to `mem::replace`.
#[inline]
-#[unstable]
+#[stable]
pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
mem::swap(mem::transmute(dest), &mut src); // cannot overlap
src
/// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
/// because it will attempt to drop the value previously at `*src`.
#[inline(always)]
-#[unstable]
+#[stable]
pub unsafe fn read<T>(src: *const T) -> T {
let mut tmp: T = mem::uninitialized();
copy_nonoverlapping_memory(&mut tmp, src, 1);
///
/// This is unsafe for the same reasons that `read` is unsafe.
#[inline(always)]
-#[experimental]
-#[allow(experimental)]
+#[unstable = "may play a larger role in std::ptr future extensions"]
pub unsafe fn read_and_zero<T>(dest: *mut T) -> T {
// Copy the data out from `dest`:
let tmp = read(&*dest);
tmp
}
-/// Overwrites a memory location with the given value without reading or dropping
-/// the old value.
+/// Overwrites a memory location with the given value without reading or
+/// dropping the old value.
///
/// # Safety
///
/// not drop the contents of `dst`. This could leak allocations or resources,
/// so care must be taken not to overwrite an object that should be dropped.
///
-/// This is appropriate for initializing uninitialized memory, or overwritting memory
-/// that has previously been `read` from.
+/// This is appropriate for initializing uninitialized memory, or overwritting
+/// memory that has previously been `read` from.
#[inline]
-#[unstable]
+#[stable]
pub unsafe fn write<T>(dst: *mut T, src: T) {
intrinsics::move_val_init(&mut *dst, src)
}
/// Methods on raw pointers
-pub trait RawPtr<T> {
- /// Returns a null raw pointer.
+#[stable]
+pub trait PtrExt<T> {
+ /// Returns the null pointer.
+ #[deprecated = "call ptr::null instead"]
fn null() -> Self;
/// Returns true if the pointer is null.
- fn is_null(&self) -> bool;
+ #[stable]
+ fn is_null(self) -> bool;
- /// Returns true if the pointer is not null.
- fn is_not_null(&self) -> bool { !self.is_null() }
+ /// Returns true if the pointer is not equal to the null pointer.
+ #[deprecated = "use !p.is_null() instead"]
+ fn is_not_null(self) -> bool { !self.is_null() }
- /// Returns the address of the pointer.
- fn to_uint(&self) -> uint;
+ /// Returns true if the pointer is not null.
+ #[deprecated = "use `as uint` instead"]
+ fn to_uint(self) -> uint;
- /// Returns `None` if the pointer is null, or else returns a reference to the
- /// value wrapped in `Some`.
+ /// Returns `None` if the pointer is null, or else returns a reference to
+ /// the value wrapped in `Some`.
///
/// # Safety
///
- /// While this method and its mutable counterpart are useful for null-safety,
- /// it is important to note that this is still an unsafe operation because
- /// the returned value could be pointing to invalid memory.
+ /// While this method and its mutable counterpart are useful for
+ /// null-safety, it is important to note that this is still an unsafe
+ /// operation because the returned value could be pointing to invalid
+ /// memory.
+ #[unstable = "Option is not clearly the right return type, and we may want \
+ to tie the return lifetime to a borrow of the raw pointer"]
unsafe fn as_ref<'a>(&self) -> Option<&'a T>;
/// Calculates the offset from a pointer. `count` is in units of T; e.g. a
///
/// # Safety
///
- /// The offset must be in-bounds of the object, or one-byte-past-the-end. Otherwise
- /// `offset` invokes Undefined Behaviour, regardless of whether the pointer is used.
+ /// The offset must be in-bounds of the object, or one-byte-past-the-end.
+ /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
+ /// the pointer is used.
+ #[stable]
unsafe fn offset(self, count: int) -> Self;
}
/// Methods on mutable raw pointers
-pub trait RawMutPtr<T>{
- /// Returns `None` if the pointer is null, or else returns a mutable reference
- /// to the value wrapped in `Some`.
+#[stable]
+pub trait MutPtrExt<T>{
+ /// Returns `None` if the pointer is null, or else returns a mutable
+ /// reference to the value wrapped in `Some`.
///
/// # Safety
///
/// As with `as_ref`, this is unsafe because it cannot verify the validity
/// of the returned pointer.
+ #[unstable = "Option is not clearly the right return type, and we may want \
+ to tie the return lifetime to a borrow of the raw pointer"]
unsafe fn as_mut<'a>(&self) -> Option<&'a mut T>;
}
-impl<T> RawPtr<T> for *const T {
+#[stable]
+impl<T> PtrExt<T> for *const T {
#[inline]
+ #[deprecated = "call ptr::null instead"]
fn null() -> *const T { null() }
#[inline]
- fn is_null(&self) -> bool { *self == RawPtr::null() }
+ #[stable]
+ fn is_null(self) -> bool { self as uint == 0 }
#[inline]
- fn to_uint(&self) -> uint { *self as uint }
+ #[deprecated = "use `as uint` instead"]
+ fn to_uint(self) -> uint { self as uint }
#[inline]
+ #[stable]
unsafe fn offset(self, count: int) -> *const T {
intrinsics::offset(self, count)
}
#[inline]
+ #[unstable = "return value does not necessarily convey all possible \
+ information"]
unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
if self.is_null() {
None
}
}
-impl<T> RawPtr<T> for *mut T {
+#[stable]
+impl<T> PtrExt<T> for *mut T {
#[inline]
+ #[deprecated = "call ptr::null instead"]
fn null() -> *mut T { null_mut() }
#[inline]
- fn is_null(&self) -> bool { *self == RawPtr::null() }
+ #[stable]
+ fn is_null(self) -> bool { self as uint == 0 }
#[inline]
- fn to_uint(&self) -> uint { *self as uint }
+ #[deprecated = "use `as uint` instead"]
+ fn to_uint(self) -> uint { self as uint }
#[inline]
+ #[stable]
unsafe fn offset(self, count: int) -> *mut T {
intrinsics::offset(self as *const T, count) as *mut T
}
#[inline]
+ #[unstable = "return value does not necessarily convey all possible \
+ information"]
unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
if self.is_null() {
None
}
}
-impl<T> RawMutPtr<T> for *mut T {
+#[stable]
+impl<T> MutPtrExt<T> for *mut T {
#[inline]
+ #[unstable = "return value does not necessarily convey all possible \
+ information"]
unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> {
if self.is_null() {
None
/// raw `*mut T` (which conveys no particular ownership semantics).
/// Useful for building abstractions like `Vec<T>` or `Box<T>`, which
/// internally use raw pointers to manage the memory that they own.
+#[unstable = "recently added to this module"]
pub struct Unique<T>(pub *mut T);
/// `Unique` pointers are `Send` if `T` is `Send` because the data they
/// reference is unaliased. Note that this aliasing invariant is
/// unenforced by the type system; the abstraction using the
/// `Unique` must enforce it.
+#[unstable = "recently added to this module"]
unsafe impl<T:Send> Send for Unique<T> { }
/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
/// reference is unaliased. Note that this aliasing invariant is
/// unenforced by the type system; the abstraction using the
/// `Unique` must enforce it.
+#[unstable = "recently added to this module"]
unsafe impl<T:Sync> Sync for Unique<T> { }
impl<T> Unique<T> {
/// Returns a null Unique.
+ #[unstable = "recently added to this module"]
pub fn null() -> Unique<T> {
- Unique(RawPtr::null())
+ Unique(null_mut())
}
/// Return an (unsafe) pointer into the memory owned by `self`.
+ #[unstable = "recently added to this module"]
pub unsafe fn offset(self, offset: int) -> *mut T {
- (self.0 as *const T).offset(offset) as *mut T
+ self.0.offset(offset)
}
}
/// Convert from `Result<T, E>` to `Option<E>`
///
- /// Converts `self` into an `Option<T>`, consuming `self`,
+ /// Converts `self` into an `Option<E>`, consuming `self`,
/// and discarding the value, if any.
///
/// # Example
use option::Option;
use option::Option::{None, Some};
use ptr;
-use ptr::RawPtr;
+use ptr::PtrExt;
use mem;
use mem::size_of;
use kinds::{Sized, marker};
#[deprecated]
pub mod raw {
use mem::transmute;
- use ptr::RawPtr;
+ use ptr::PtrExt;
use raw::Slice;
use ops::FnOnce;
use option::Option;
use num::Int;
use ops::{Fn, FnMut};
use option::Option::{mod, None, Some};
-use ptr::RawPtr;
+use ptr::PtrExt;
use raw::{Repr, Slice};
use result::Result::{mod, Ok, Err};
use slice::{mod, SliceExt};
/// Unsafe operations
#[deprecated]
pub mod raw {
- use ptr::RawPtr;
+ use ptr::PtrExt;
use raw::Slice;
use slice::SliceExt;
use str::StrExt;
#[test]
fn test_flate_round_trip() {
- let mut r = rand::task_rng();
+ let mut r = rand::thread_rng();
let mut words = vec!();
for _ in range(0u, 20) {
let range = r.gen_range(1u, 10);
/// use std::rand::distributions::{Exp, IndependentSample};
///
/// let exp = Exp::new(2.0);
-/// let v = exp.ind_sample(&mut rand::task_rng());
+/// let v = exp.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a Exp(2) distribution", v);
/// ```
#[deriving(Copy)]
/// use std::rand::distributions::{IndependentSample, Gamma};
///
/// let gamma = Gamma::new(2.0, 5.0);
-/// let v = gamma.ind_sample(&mut rand::task_rng());
+/// let v = gamma.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a Gamma(2, 5) distribution", v);
/// ```
///
/// use std::rand::distributions::{ChiSquared, IndependentSample};
///
/// let chi = ChiSquared::new(11.0);
-/// let v = chi.ind_sample(&mut rand::task_rng());
+/// let v = chi.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a χ²(11) distribution", v)
/// ```
pub struct ChiSquared {
/// use std::rand::distributions::{FisherF, IndependentSample};
///
/// let f = FisherF::new(2.0, 32.0);
-/// let v = f.ind_sample(&mut rand::task_rng());
+/// let v = f.ind_sample(&mut rand::thread_rng());
/// println!("{} is from an F(2, 32) distribution", v)
/// ```
pub struct FisherF {
/// use std::rand::distributions::{StudentT, IndependentSample};
///
/// let t = StudentT::new(11.0);
-/// let v = t.ind_sample(&mut rand::task_rng());
+/// let v = t.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a t(11) distribution", v)
/// ```
pub struct StudentT {
/// Weighted { weight: 4, item: 'b' },
/// Weighted { weight: 1, item: 'c' });
/// let wc = WeightedChoice::new(items.as_mut_slice());
-/// let mut rng = rand::task_rng();
+/// let mut rng = rand::thread_rng();
/// for _ in range(0u, 16) {
/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
/// println!("{}", wc.ind_sample(&mut rng));
///
/// // mean 2, standard deviation 3
/// let normal = Normal::new(2.0, 3.0);
-/// let v = normal.ind_sample(&mut rand::task_rng());
+/// let v = normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from a N(2, 9) distribution", v)
/// ```
#[deriving(Copy)]
///
/// // mean 2, standard deviation 3
/// let log_normal = LogNormal::new(2.0, 3.0);
-/// let v = log_normal.ind_sample(&mut rand::task_rng());
+/// let v = log_normal.ind_sample(&mut rand::thread_rng());
/// println!("{} is from an ln N(2, 9) distribution", v)
/// ```
#[deriving(Copy)]
///
/// fn main() {
/// let between = Range::new(10u, 10000u);
-/// let mut rng = std::rand::task_rng();
+/// let mut rng = std::rand::thread_rng();
/// let mut sum = 0;
/// for _ in range(0u, 1000) {
/// sum += between.ind_sample(&mut rng);
/// # Example
///
/// ```rust
- /// use std::rand::{task_rng, Rng};
+ /// use std::rand::{thread_rng, Rng};
///
/// let mut v = [0u8, .. 13579];
- /// task_rng().fill_bytes(&mut v);
+ /// thread_rng().fill_bytes(&mut v);
/// println!("{}", v.as_slice());
/// ```
fn fill_bytes(&mut self, dest: &mut [u8]) {
/// # Example
///
/// ```rust
- /// use std::rand::{task_rng, Rng};
+ /// use std::rand::{thread_rng, Rng};
///
- /// let mut rng = task_rng();
+ /// let mut rng = thread_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{}", rng.gen::<(f64, bool)>());
/// # Example
///
/// ```
- /// use std::rand::{task_rng, Rng};
+ /// use std::rand::{thread_rng, Rng};
///
- /// let mut rng = task_rng();
+ /// let mut rng = thread_rng();
/// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
/// println!("{}", x);
/// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
/// # Example
///
/// ```rust
- /// use std::rand::{task_rng, Rng};
+ /// use std::rand::{thread_rng, Rng};
///
- /// let mut rng = task_rng();
+ /// let mut rng = thread_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
/// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
/// # Example
///
/// ```rust
- /// use std::rand::{task_rng, Rng};
+ /// use std::rand::{thread_rng, Rng};
///
- /// let mut rng = task_rng();
+ /// let mut rng = thread_rng();
/// println!("{}", rng.gen_weighted_bool(3));
/// ```
fn gen_weighted_bool(&mut self, n: uint) -> bool {
/// # Example
///
/// ```rust
- /// use std::rand::{task_rng, Rng};
+ /// use std::rand::{thread_rng, Rng};
///
- /// let s: String = task_rng().gen_ascii_chars().take(10).collect();
+ /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
/// println!("{}", s);
/// ```
fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
/// # Example
///
/// ```
- /// use std::rand::{task_rng, Rng};
+ /// use std::rand::{thread_rng, Rng};
///
/// let choices = [1i, 2, 4, 8, 16, 32];
- /// let mut rng = task_rng();
+ /// let mut rng = thread_rng();
/// println!("{}", rng.choose(&choices));
/// assert_eq!(rng.choose(choices[..0]), None);
/// ```
/// # Example
///
/// ```rust
- /// use std::rand::{task_rng, Rng};
+ /// use std::rand::{thread_rng, Rng};
///
- /// let mut rng = task_rng();
+ /// let mut rng = thread_rng();
/// let mut y = [1i, 2, 3];
/// rng.shuffle(&mut y);
/// println!("{}", y.as_slice());
}
}
- pub fn rng() -> MyRng<rand::TaskRng> {
- MyRng { inner: rand::task_rng() }
+ pub fn rng() -> MyRng<rand::ThreadRng> {
+ MyRng { inner: rand::thread_rng() }
}
pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
#[cfg(test)]
mod tests {
use std::prelude::*;
- use std::rand::{Rng, task_rng, Open01, Closed01};
+ use std::rand::{Rng, thread_rng, Open01, Closed01};
struct ConstantRng(u64);
impl Rng for ConstantRng {
fn rand_open() {
// this is unlikely to catch an incorrect implementation that
// generates exactly 0 or 1, but it keeps it sane.
- let mut rng = task_rng();
+ let mut rng = thread_rng();
for _ in range(0u, 1_000) {
// strict inequalities
let Open01(f) = rng.gen::<Open01<f64>>();
#[test]
fn rand_closed() {
- let mut rng = task_rng();
+ let mut rng = thread_rng();
for _ in range(0u, 1_000) {
// strict inequalities
let Closed01(f) = rng.gen::<Closed01<f64>>();
};
self.chari = closer;
let greed = try!(self.get_next_greedy());
- let inner = String::from_chars(
- self.chars[start+1..closer]);
+ let inner = self.chars[start+1..closer].iter().cloned()
+ .collect::<String>();
// Parse the min and max values from the regex.
let (mut min, mut max): (uint, Option<uint>);
}
fn slice(&self, start: uint, end: uint) -> String {
- String::from_chars(self.chars[start..end])
+ self.chars[start..end].iter().cloned().collect()
}
}
// except according to those terms.
#![allow(non_snake_case)]
-use std::rand::{Rng, task_rng};
+use std::rand::{Rng, thread_rng};
use stdtest::Bencher;
+use std::iter::repeat;
use regex::{Regex, NoExpand};
fn no_exponential(b: &mut Bencher) {
let n = 100;
let re = Regex::new(format!("{}{}",
- "a?".repeat(n),
- "a".repeat(n)).as_slice()).unwrap();
- let text = "a".repeat(n);
+ repeat("a?").take(n).collect::<String>(),
+ repeat("a").take(n).collect::<String>()).as_slice()).unwrap();
+ let text = repeat("a").take(n).collect::<String>();
bench_assert_match(b, re, text.as_slice());
}
#[bench]
fn literal(b: &mut Bencher) {
let re = regex!("y");
- let text = format!("{}y", "x".repeat(50));
+ let text = format!("{}y", repeat("x").take(50).collect::<String>());
bench_assert_match(b, re, text.as_slice());
}
#[bench]
fn not_literal(b: &mut Bencher) {
let re = regex!(".y");
- let text = format!("{}y", "x".repeat(50));
+ let text = format!("{}y", repeat("x").take(50).collect::<String>());
bench_assert_match(b, re, text.as_slice());
}
#[bench]
fn match_class(b: &mut Bencher) {
let re = regex!("[abcdw]");
- let text = format!("{}w", "xxxx".repeat(20));
+ let text = format!("{}w", repeat("xxxx").take(20).collect::<String>());
bench_assert_match(b, re, text.as_slice());
}
fn match_class_in_range(b: &mut Bencher) {
// 'b' is between 'a' and 'c', so the class range checking doesn't help.
let re = regex!("[ac]");
- let text = format!("{}c", "bbbb".repeat(20));
+ let text = format!("{}c", repeat("bbbb").take(20).collect::<String>());
bench_assert_match(b, re, text.as_slice());
}
#[bench]
fn anchored_literal_long_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
- let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
+ let text = repeat("abcdefghijklmnopqrstuvwxyz").take(15).collect::<String>();
b.iter(|| re.is_match(text.as_slice()));
}
#[bench]
fn anchored_literal_long_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
- let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
+ let text = repeat("abcdefghijklmnopqrstuvwxyz").take(15).collect::<String>();
b.iter(|| re.is_match(text.as_slice()));
}
fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn gen_text(n: uint) -> String {
- let mut rng = task_rng();
+ let mut rng = thread_rng();
let mut bytes = rng.gen_ascii_chars().map(|n| n as u8).take(n)
.collect::<Vec<u8>>();
for (i, b) in bytes.iter_mut().enumerate() {
if self.is_internal(cx, item.span) { return }
match item.node {
- ast::ItemTrait(_, _, _, ref supertraits, _) => {
+ ast::ItemTrait(_, _, ref supertraits, _) => {
for t in supertraits.iter() {
- if let ast::TraitTyParamBound(ref t) = *t {
+ if let ast::TraitTyParamBound(ref t, _) = *t {
let id = ty::trait_ref_to_def_id(cx.tcx, &t.trait_ref);
self.lint(cx, id, t.trait_ref.path.span);
}
}
}
}
- ast::ItemTrait(_, _, _, _, ref ms) => {
+ ast::ItemTrait(_, _, _, ref ms) => {
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
encode_def_id(rbml_w, def_id);
use middle::ty;
use std::fmt;
use std::iter::AdditiveIterator;
-use std::iter::range_inclusive;
+use std::iter::{range_inclusive, repeat};
use std::num::Float;
use std::slice;
use syntax::ast::{mod, DUMMY_NODE_ID, NodeId, Pat};
}).collect();
let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1;
- let br = String::from_char(total_width, '+');
+ let br = repeat('+').take(total_width).collect::<String>();
try!(write!(f, "{}\n", br));
for row in pretty_printed_matrix.into_iter() {
try!(write!(f, "+"));
ident: ty_param.ident,
id: ty_param.id,
bounds: bounds,
- unbound: ty_param.unbound.clone(),
default: ty_param.default.clone(),
span: ty_param.span,
}
// be passing down a map.
ast::RegionTyParamBound(lt)
}
- &ast::TraitTyParamBound(ref poly_tr) => {
+ &ast::TraitTyParamBound(ref poly_tr, modifier) => {
let tr = &poly_tr.trait_ref;
let last_seg = tr.path.segments.last().unwrap();
let mut insert = Vec::new();
path: new_path,
ref_id: tr.ref_id,
}
- })
+ }, modifier)
}
}
})
// method to the root. In this case, if the trait is private, then
// parent all the methods to the trait to indicate that they're
// private.
- ast::ItemTrait(_, _, _, _, ref methods) if item.vis != ast::Public => {
+ ast::ItemTrait(_, _, _, ref methods) if item.vis != ast::Public => {
for m in methods.iter() {
match *m {
ast::ProvidedMethod(ref m) => {
// Default methods on traits are all public so long as the trait
// is public
- ast::ItemTrait(_, _, _, _, ref methods) if public_first => {
+ ast::ItemTrait(_, _, _, ref methods) if public_first => {
for method in methods.iter() {
match *method {
ast::ProvidedMethod(ref m) => {
}
}
- ast::ItemTrait(_, _, _, _, ref methods) => {
+ ast::ItemTrait(_, _, _, ref methods) => {
for m in methods.iter() {
match *m {
ast::ProvidedMethod(ref m) => {
ast::ItemStruct(ref def, _) => check_struct(&**def),
- ast::ItemTrait(_, _, _, _, ref methods) => {
+ ast::ItemTrait(_, _, _, ref methods) => {
for m in methods.iter() {
match *m {
ast::RequiredMethod(..) => {}
fn check_ty_param_bound(&self,
ty_param_bound: &ast::TyParamBound) {
- if let ast::TraitTyParamBound(ref trait_ref) = *ty_param_bound {
+ if let ast::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
if !self.tcx.sess.features.borrow().visible_private_types &&
self.path_is_private_type(trait_ref.trait_ref.ref_id) {
let span = trait_ref.trait_ref.path.span;
// namespace (the contents have their own privacies).
ast::ItemForeignMod(_) => {}
- ast::ItemTrait(_, _, _, ref bounds, _) => {
+ ast::ItemTrait(_, _, ref bounds, _) => {
if !self.trait_is_public(item.id) {
return
}
ast::ItemTy(_, ref generics) |
ast::ItemEnum(_, ref generics) |
ast::ItemStruct(_, ref generics) |
- ast::ItemTrait(_, ref generics, _, _, _) |
+ ast::ItemTrait(_, ref generics, _, _) |
ast::ItemImpl(_, ref generics, _, _, _) => {
// These kinds of items have only early bound lifetime parameters.
let lifetimes = &generics.lifetimes;
}
}
- fn visit_poly_trait_ref(&mut self, trait_ref: &ast::PolyTraitRef) {
+ fn visit_poly_trait_ref(&mut self, trait_ref:
+ &ast::PolyTraitRef,
+ _modifier: &ast::TraitBoundModifier) {
debug!("visit_poly_trait_ref trait_ref={}", trait_ref);
self.with(LateScope(&trait_ref.bound_lifetimes, self.scope), |old_scope, this| {
match cx.map.find(id.node) {
Some(ast_map::NodeItem(item)) => {
match item.node {
- ItemTrait(_, _, _, _, ref ms) => {
+ ItemTrait(_, _, _, ref ms) => {
let (_, p) =
ast_util::split_trait_methods(ms[]);
p.iter()
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsiOS => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsWindows => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsLinux => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsAndroid => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
},
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsiOS => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsWindows => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsLinux => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsAndroid => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
},
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsiOS => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsWindows => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsLinux => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsAndroid => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly => {
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string()
+ -a:0:64-n32".to_string()
}
},
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string(),
+ -a:0:64-n32".to_string(),
llvm_target: "arm-apple-ios".to_string(),
target_endian: "little".to_string(),
target_word_size: "32".to_string(),
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string(),
+ -a:0:64-n32".to_string(),
llvm_target: "arm-linux-androideabi".to_string(),
target_endian: "little".to_string(),
target_word_size: "32".to_string(),
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string(),
+ -a:0:64-n32".to_string(),
llvm_target: "arm-unknown-linux-gnueabi".to_string(),
target_endian: "little".to_string(),
target_word_size: "32".to_string(),
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string(),
+ -a:0:64-n32".to_string(),
llvm_target: "arm-unknown-linux-gnueabihf".to_string(),
target_endian: "little".to_string(),
target_word_size: "32".to_string(),
data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\
-i32:32:32-i64:32:64\
-f32:32:32-f64:32:64-v64:64:64\
- -v128:128:128-a0:0:64-f80:128:128\
+ -v128:128:128-a:0:64-f80:128:128\
-n8:16:32".to_string(),
llvm_target: "i386-apple-ios".to_string(),
target_endian: "little".to_string(),
data_layout: "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\
-i32:32:32-i64:32:64\
-f32:32:32-f64:32:64-v64:64:64\
- -v128:128:128-a0:0:64-f80:128:128\
+ -v128:128:128-a:0:64-f80:128:128\
-n8:16:32".to_string(),
llvm_target: "i686-apple-darwin".to_string(),
target_endian: "little".to_string(),
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string(),
+ -a:0:64-n32".to_string(),
llvm_target: "mips-unknown-linux-gnu".to_string(),
target_endian: "big".to_string(),
target_word_size: "32".to_string(),
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
- -a0:0:64-n32".to_string(),
+ -a:0:64-n32".to_string(),
llvm_target: "mipsel-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
target_word_size: "32".to_string(),
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64".to_string(),
llvm_target: "x86_64-apple-darwin".to_string(),
target_endian: "little".to_string(),
Target {
// FIXME: Test this. Copied from linux (#2398)
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(),
llvm_target: "x86_64-pc-windows-gnu".to_string(),
target_endian: "little".to_string(),
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(),
llvm_target: "x86_64-unknown-dragonfly".to_string(),
target_endian: "little".to_string(),
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(),
llvm_target: "x86_64-unknown-freebsd".to_string(),
target_endian: "little".to_string(),
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(),
llvm_target: "x86_64-unknown-linux-gnu".to_string(),
target_endian: "little".to_string(),
"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\
-i32:32:32-i64:32:64\
-f32:32:32-f64:32:64-v64:64:64\
- -v128:128:128-a0:0:64-f80:128:128\
+ -v128:128:128-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\
-i32:32:32-i64:32:64\
-f32:32:32-f64:32:64-v64:64:64\
- -v128:128:128-a0:0:64-f80:128:128\
+ -v128:128:128-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
data_layout: match target_os {
abi::OsMacos => {
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64".to_string()
}
abi::OsiOS => {
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64".to_string()
}
abi::OsWindows => {
// FIXME: Test this. Copied from Linux (#2398)
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
abi::OsLinux => {
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
abi::OsAndroid => {
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
abi::OsFreebsd => {
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
abi::OsDragonfly => {
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
- f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-\
+ f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string()
}
match cfg.spawn(move || { std::io::stdio::set_stderr(box w); f() }).join() {
Ok(()) => { /* fallthrough */ }
Err(value) => {
- // Task panicked without emitting a fatal diagnostic
+ // Thread panicked without emitting a fatal diagnostic
if !value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
#[deriving(Show,PartialEq,Clone,Copy)]
enum Shadowable {
Always,
- /// Means that the recorded import obeys the glob shadowing rules, i.e., can
- /// only be shadowed by another glob import.
- Glob,
Never
}
target.unwrap().shadowable
}
+
+ fn set_target_and_id(&mut self,
+ namespace: Namespace,
+ target: Option<Target>,
+ id: NodeId) {
+ match namespace {
+ TypeNS => {
+ self.type_target = target;
+ self.type_id = id;
+ }
+ ValueNS => {
+ self.value_target = target;
+ self.value_id = id;
+ }
+ }
+ }
}
/// The link from a module up to its nearest parent node.
ItemImpl(_, _, Some(_), _, _) => parent,
- ItemTrait(_, _, _, _, ref items) => {
+ ItemTrait(_, _, _, ref items) => {
let name_bindings =
self.add_child(name,
parent.clone(),
view_path.span,
id,
is_public,
- if shadowable == Shadowable::Never {
- Shadowable::Glob
- } else {
- shadowable
- });
+ shadowable);
}
}
}
// We've successfully resolved the import. Write the results in.
let mut import_resolutions = module_.import_resolutions.borrow_mut();
let import_resolution = &mut (*import_resolutions)[target];
+ {
+ let check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
+ let namespace_name = match namespace {
+ TypeNS => "type",
+ ValueNS => "value",
+ };
- match value_result {
- BoundResult(ref target_module, ref name_bindings) => {
- debug!("(resolving single import) found value target: {}",
- { name_bindings.value_def.borrow().clone().unwrap().def });
- self.check_for_conflicting_import(
- &import_resolution.value_target,
- directive.span,
- target,
- ValueNS);
-
- self.check_that_import_is_importable(
- &**name_bindings,
- directive.span,
- target,
- ValueNS);
-
- import_resolution.value_target =
- Some(Target::new(target_module.clone(),
- name_bindings.clone(),
- directive.shadowable));
- import_resolution.value_id = directive.id;
- import_resolution.is_public = directive.is_public;
- value_used_public = name_bindings.defined_in_public_namespace(ValueNS);
- }
- UnboundResult => { /* Continue. */ }
- UnknownResult => {
- panic!("value result should be known at this point");
- }
- }
- match type_result {
- BoundResult(ref target_module, ref name_bindings) => {
- debug!("(resolving single import) found type target: {}",
- { name_bindings.type_def.borrow().clone().unwrap().type_def });
- self.check_for_conflicting_import(
- &import_resolution.type_target,
- directive.span,
- target,
- TypeNS);
-
- self.check_that_import_is_importable(
- &**name_bindings,
- directive.span,
- target,
- TypeNS);
-
- import_resolution.type_target =
- Some(Target::new(target_module.clone(),
- name_bindings.clone(),
- directive.shadowable));
- import_resolution.type_id = directive.id;
- import_resolution.is_public = directive.is_public;
- type_used_public = name_bindings.defined_in_public_namespace(TypeNS);
- }
- UnboundResult => { /* Continue. */ }
- UnknownResult => {
- panic!("type result should be known at this point");
- }
+ match *result {
+ BoundResult(ref target_module, ref name_bindings) => {
+ debug!("(resolving single import) found {} target: {}",
+ namespace_name,
+ name_bindings.def_for_namespace(namespace));
+ self.check_for_conflicting_import(
+ &import_resolution.target_for_namespace(namespace),
+ directive.span,
+ target,
+ namespace);
+
+ self.check_that_import_is_importable(
+ &**name_bindings,
+ directive.span,
+ target,
+ namespace);
+
+ let target = Some(Target::new(target_module.clone(),
+ name_bindings.clone(),
+ directive.shadowable));
+ import_resolution.set_target_and_id(namespace, target, directive.id);
+ import_resolution.is_public = directive.is_public;
+ *used_public = name_bindings.defined_in_public_namespace(namespace);
+ }
+ UnboundResult => { /* Continue. */ }
+ UnknownResult => {
+ panic!("{} result should be known at this point", namespace_name);
+ }
+ }
+ };
+ check_and_write_import(ValueNS, &value_result, &mut value_used_public);
+ check_and_write_import(TypeNS, &type_result, &mut type_used_public);
}
self.check_for_conflicts_between_imports_and_items(
// Resolves a glob import. Note that this function cannot fail; it either
// succeeds or bails out (as importing * from an empty module or a module
- // that exports nothing is valid).
+ // that exports nothing is valid). containing_module is the module we are
+ // actually importing, i.e., `foo` in `use foo::*`.
fn resolve_glob_import(&mut self,
module_: &Module,
containing_module: Rc<Module>,
assert_eq!(containing_module.glob_count.get(), 0);
// Add all resolved imports from the containing module.
- let import_resolutions = containing_module.import_resolutions
- .borrow();
+ let import_resolutions = containing_module.import_resolutions.borrow();
for (ident, target_import_resolution) in import_resolutions.iter() {
debug!("(resolving glob import) writing module resolution \
{} into `{}`",
- target_import_resolution.type_target.is_none(),
+ token::get_name(*ident),
self.module_to_string(module_));
if !target_import_resolution.is_public {
// Continue.
}
Some(ref value_target) => {
- dest_import_resolution.value_target =
- Some(value_target.clone());
+ self.check_for_conflicting_import(&dest_import_resolution.value_target,
+ import_directive.span,
+ *ident,
+ ValueNS);
+ dest_import_resolution.value_target = Some(value_target.clone());
}
}
match target_import_resolution.type_target {
// Continue.
}
Some(ref type_target) => {
- dest_import_resolution.type_target =
- Some(type_target.clone());
+ self.check_for_conflicting_import(&dest_import_resolution.type_target,
+ import_directive.span,
+ *ident,
+ TypeNS);
+ dest_import_resolution.type_target = Some(type_target.clone());
}
}
dest_import_resolution.is_public = is_public;
// Add all children from the containing module.
self.populate_module_if_necessary(&containing_module);
- for (&name, name_bindings) in containing_module.children
- .borrow().iter() {
+ for (&name, name_bindings) in containing_module.children.borrow().iter() {
self.merge_import_resolution(module_,
containing_module.clone(),
import_directive,
}
// Add external module children from the containing module.
- for (&name, module) in containing_module.external_module_children
- .borrow().iter() {
+ for (&name, module) in containing_module.external_module_children.borrow().iter() {
let name_bindings =
Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
self.merge_import_resolution(module_,
debug!("(resolving glob import) writing resolution `{}` in `{}` \
to `{}`",
- token::get_name(name).get().to_string(),
+ token::get_name(name).get(),
self.module_to_string(&*containing_module),
self.module_to_string(module_));
// Merge the child item into the import resolution.
- if name_bindings.defined_in_namespace_with(ValueNS, IMPORTABLE | PUBLIC) {
- debug!("(resolving glob import) ... for value target");
- if dest_import_resolution.shadowable(ValueNS) == Shadowable::Never {
- let msg = format!("a value named `{}` has already been imported \
- in this module",
- token::get_name(name).get());
- self.session.span_err(import_directive.span, msg.as_slice());
- } else {
- dest_import_resolution.value_target =
- Some(Target::new(containing_module.clone(),
- name_bindings.clone(),
- import_directive.shadowable));
- dest_import_resolution.value_id = id;
- }
- }
- if name_bindings.defined_in_namespace_with(TypeNS, IMPORTABLE | PUBLIC) {
- debug!("(resolving glob import) ... for type target");
- if dest_import_resolution.shadowable(TypeNS) == Shadowable::Never {
- let msg = format!("a type named `{}` has already been imported \
- in this module",
- token::get_name(name).get());
- self.session.span_err(import_directive.span, msg.as_slice());
- } else {
- dest_import_resolution.type_target =
- Some(Target::new(containing_module,
- name_bindings.clone(),
- import_directive.shadowable));
- dest_import_resolution.type_id = id;
- }
+ {
+ let merge_child_item = |namespace| {
+ if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
+ let namespace_name = match namespace {
+ TypeNS => "type",
+ ValueNS => "value",
+ };
+ debug!("(resolving glob import) ... for {} target", namespace_name);
+ if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
+ let msg = format!("a {} named `{}` has already been imported \
+ in this module",
+ namespace_name,
+ token::get_name(name).get());
+ self.session.span_err(import_directive.span, msg.as_slice());
+ } else {
+ let target = Target::new(containing_module.clone(),
+ name_bindings.clone(),
+ import_directive.shadowable);
+ dest_import_resolution.set_target_and_id(namespace,
+ Some(target),
+ id);
+ }
+ }
+ };
+ merge_child_item(ValueNS);
+ merge_child_item(TypeNS);
}
+
dest_import_resolution.is_public = is_public;
self.check_for_conflicts_between_imports_and_items(
return
}
+ debug!("check_for_conflicting_import: {}; target exists: {}",
+ token::get_name(name).get(),
+ target.is_some());
+
match *target {
Some(ref target) if target.shadowable != Shadowable::Always => {
let msg = format!("a {} named `{}` has already been imported \
}
}
+ /// Searches the current set of local scopes and
+ /// applies translations for closures.
fn search_ribs(&self,
ribs: &[Rib],
name: Name,
None
}
+ /// Searches the current set of local scopes for labels.
+ /// Stops after meeting a closure.
+ fn search_label(&self, name: Name) -> Option<DefLike> {
+ for rib in self.label_ribs.iter().rev() {
+ match rib.kind {
+ NormalRibKind => {
+ // Continue
+ }
+ _ => {
+ // Do not resolve labels across function boundary
+ return None
+ }
+ }
+ let result = rib.bindings.get(&name).cloned();
+ if result.is_some() {
+ return result
+ }
+ }
+ None
+ }
+
fn resolve_crate(&mut self, krate: &ast::Crate) {
debug!("(resolving crate) starting");
impl_items[]);
}
- ItemTrait(_, ref generics, ref unbound, ref bounds, ref trait_items) => {
+ ItemTrait(_, ref generics, ref bounds, ref trait_items) => {
// Create a new rib for the self type.
let mut self_type_rib = Rib::new(ItemRibKind);
this.resolve_type_parameter_bounds(item.id, bounds,
TraitDerivation);
- match *unbound {
- Some(ref tpb) => {
- this.resolve_trait_reference(item.id, tpb, TraitDerivation);
- }
- None => {}
- }
-
for trait_item in (*trait_items).iter() {
// Create a new rib for the trait_item-specific type
// parameters.
self.resolve_type_parameter_bound(type_parameter.id, bound,
TraitBoundingTypeParameter);
}
- match &type_parameter.unbound {
- &Some(ref unbound) =>
- self.resolve_trait_reference(
- type_parameter.id, unbound, TraitBoundingTypeParameter),
- &None => {}
- }
match type_parameter.default {
Some(ref ty) => self.resolve_type(&**ty),
None => {}
type_parameter_bound: &TyParamBound,
reference_type: TraitReferenceType) {
match *type_parameter_bound {
- TraitTyParamBound(ref tref) => {
+ TraitTyParamBound(ref tref, _) => {
self.resolve_poly_trait_reference(id, tref, reference_type)
}
RegionTyParamBound(..) => {}
ExprBreak(Some(label)) | ExprAgain(Some(label)) => {
let renamed = mtwt::resolve(label);
- match self.search_ribs(self.label_ribs[],
- renamed, expr.span) {
+ match self.search_label(renamed) {
None => {
self.resolve_error(
expr.span,
}
fn dump(&mut self, handler: &Handler) {
- let mut buffer = self.buffer.lock();
+ let mut buffer = self.buffer.lock().unwrap();
for diag in buffer.iter() {
match diag.code {
Some(ref code) => {
msg: &str, code: Option<&str>, lvl: Level) {
assert!(cmsp.is_none(), "SharedEmitter doesn't support spans");
- self.buffer.lock().push(Diagnostic {
+ self.buffer.lock().unwrap().push(Diagnostic {
msg: msg.to_string(),
code: code.map(|s| s.to_string()),
lvl: lvl,
loop {
// Avoid holding the lock for the entire duration of the match.
- let maybe_work = work_items_arc.lock().pop();
+ let maybe_work = work_items_arc.lock().unwrap().pop();
match maybe_work {
Some(work) => {
execute_work_item(&cgcx, work);
item.id);
for field in struct_def.fields.iter() {
- self.process_struct_field_def(field, enum_name[], variant.node.id);
+ self.process_struct_field_def(field, qualname[], variant.node.id);
self.visit_ty(&*field.node.ty);
}
}
// super-traits
for super_bound in trait_refs.iter() {
let trait_ref = match *super_bound {
- ast::TraitTyParamBound(ref trait_ref) => {
+ ast::TraitTyParamBound(ref trait_ref, _) => {
trait_ref
}
ast::RegionTyParamBound(..) => {
}
fn process_path(&mut self,
- ex: &ast::Expr,
- path: &ast::Path) {
+ id: NodeId,
+ span: Span,
+ path: &ast::Path,
+ ref_kind: Option<recorder::Row>) {
if generated_code(path.span) {
return
}
let def_map = self.analysis.ty_cx.def_map.borrow();
- if !def_map.contains_key(&ex.id) {
- self.sess.span_bug(ex.span,
- format!("def_map has no key for {} in visit_expr",
- ex.id)[]);
+ if !def_map.contains_key(&id) {
+ self.sess.span_bug(span,
+ format!("def_map has no key for {} in visit_expr", id)[]);
}
- let def = &(*def_map)[ex.id];
- let sub_span = self.span.span_for_last_ident(ex.span);
+ let def = &(*def_map)[id];
+ let sub_span = self.span.span_for_last_ident(span);
match *def {
def::DefUpvar(..) |
def::DefLocal(..) |
def::DefStatic(..) |
def::DefConst(..) |
- def::DefVariant(..) => self.fmt.ref_str(recorder::VarRef,
- ex.span,
+ def::DefVariant(..) => self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
+ span,
sub_span,
def.def_id(),
self.cur_scope),
def::DefStruct(def_id) => self.fmt.ref_str(recorder::StructRef,
- ex.span,
+ span,
sub_span,
def_id,
- self.cur_scope),
+ self.cur_scope),
def::DefStaticMethod(declid, provenence) => {
- let sub_span = self.span.sub_span_for_meth_name(ex.span);
+ let sub_span = self.span.sub_span_for_meth_name(span);
let defid = if declid.krate == ast::LOCAL_CRATE {
let ti = ty::impl_or_trait_item(&self.analysis.ty_cx,
declid);
} else {
None
};
- self.fmt.meth_call_str(ex.span,
+ self.fmt.meth_call_str(span,
sub_span,
defid,
Some(declid),
self.cur_scope);
},
- def::DefFn(def_id, _) => self.fmt.fn_call_str(ex.span,
- sub_span,
- def_id,
- self.cur_scope),
- _ => self.sess.span_bug(ex.span,
+ def::DefFn(def_id, _) => self.fmt.fn_call_str(span,
+ sub_span,
+ def_id,
+ self.cur_scope),
+ _ => self.sess.span_bug(span,
format!("Unexpected def kind while looking up path in '{}'",
- self.span.snippet(ex.span))[]),
+ self.span.snippet(span))[]),
}
// modules or types in the path prefix
match *def {
- def::DefStaticMethod(..) => {
- self.write_sub_path_trait_truncated(path);
- },
+ def::DefStaticMethod(..) => self.write_sub_path_trait_truncated(path),
def::DefLocal(_) |
def::DefStatic(_,_) |
def::DefConst(..) |
def::DefStruct(_) |
+ def::DefVariant(..) |
def::DefFn(..) => self.write_sub_paths_truncated(path),
_ => {},
}
-
- visit::walk_path(self, path);
}
fn process_struct_lit(&mut self,
}
};
for &Spanned { node: ref field, span } in fields.iter() {
- self.visit_pat(&*field.pat);
+ let sub_span = self.span.span_for_first_ident(span);
let fields = ty::lookup_struct_fields(&self.analysis.ty_cx, struct_def);
for f in fields.iter() {
if f.name == field.ident.name {
self.fmt.ref_str(recorder::VarRef,
- p.span,
- Some(span),
+ span,
+ sub_span,
f.id,
self.cur_scope);
break;
}
}
+ self.visit_pat(&*field.pat);
}
}
ast::PatEnum(ref path, _) => {
&**typ,
impl_items)
}
- ast::ItemTrait(_, ref generics, _, ref trait_refs, ref methods) =>
+ ast::ItemTrait(_, ref generics, ref trait_refs, ref methods) =>
self.process_trait(item, generics, trait_refs, methods),
ast::ItemMod(ref m) => self.process_mod(item, m),
ast::ItemTy(ref ty, ref ty_params) => {
fn visit_generics(&mut self, generics: &ast::Generics) {
for param in generics.ty_params.iter() {
for bound in param.bounds.iter() {
- if let ast::TraitTyParamBound(ref trait_ref) = *bound {
+ if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
self.process_trait_ref(&trait_ref.trait_ref, None);
}
}
}
match i.node {
- ast::ViewItemUse(ref path) => {
- match path.node {
+ ast::ViewItemUse(ref item) => {
+ match item.node {
ast::ViewPathSimple(ident, ref path, id) => {
let sub_span = self.span.span_for_last_ident(path.span);
let mod_id = match self.lookup_type_ref(id) {
// 'use' always introduces an alias, if there is not an explicit
// one, there is an implicit one.
let sub_span =
- match self.span.sub_span_before_token(path.span, token::Eq) {
+ match self.span.sub_span_after_keyword(item.span, keywords::As) {
Some(sub_span) => Some(sub_span),
None => sub_span,
};
// because just walking the callee path does what we want.
visit::walk_expr(self, ex);
},
- ast::ExprPath(ref path) => self.process_path(ex, path),
+ ast::ExprPath(ref path) => {
+ self.process_path(ex.id, ex.span, path, None);
+ visit::walk_path(self, path);
+ }
ast::ExprStruct(ref path, ref fields, ref base) =>
self.process_struct_lit(ex, path, fields, base),
ast::ExprMethodCall(_, _, ref args) => self.process_method_call(ex, args),
fn visit_arm(&mut self, arm: &ast::Arm) {
assert!(self.collected_paths.len() == 0 && !self.collecting);
self.collecting = true;
-
for pattern in arm.pats.iter() {
// collect paths from the arm's patterns
self.visit_pat(&**pattern);
}
- self.collecting = false;
+
+ // This is to get around borrow checking, because we need mut self to call process_path.
+ let mut paths_to_process = vec![];
// process collected paths
for &(id, ref p, ref immut, ref_kind) in self.collected_paths.iter() {
- let value = if *immut {
- self.span.snippet(p.span).to_string()
- } else {
- "<mutable>".to_string()
- };
- let sub_span = self.span.span_for_first_ident(p.span);
let def_map = self.analysis.ty_cx.def_map.borrow();
if !def_map.contains_key(&id) {
self.sess.span_bug(p.span,
- format!("def_map has no key for {} in visit_arm",
- id)[]);
+ format!("def_map has no key for {} in visit_arm", id)[]);
}
let def = &(*def_map)[id];
match *def {
- def::DefLocal(id) => self.fmt.variable_str(p.span,
- sub_span,
- id,
- path_to_string(p)[],
- value[],
- ""),
- def::DefVariant(_,id,_) => self.fmt.ref_str(ref_kind,
- p.span,
- sub_span,
- id,
- self.cur_scope),
- // FIXME(nrc) what is this doing here?
+ def::DefLocal(id) => {
+ let value = if *immut {
+ self.span.snippet(p.span).to_string()
+ } else {
+ "<mutable>".to_string()
+ };
+
+ assert!(p.segments.len() == 1, "qualified path for local variable def in arm");
+ self.fmt.variable_str(p.span,
+ Some(p.span),
+ id,
+ path_to_string(p)[],
+ value[],
+ "")
+ }
+ def::DefVariant(..) => {
+ paths_to_process.push((id, p.span, p.clone(), Some(ref_kind)))
+ }
+ // FIXME(nrc) what are these doing here?
def::DefStatic(_, _) => {}
def::DefConst(..) => {}
- _ => error!("unexpected definition kind when processing collected paths: {}",
- *def)
+ _ => error!("unexpected definition kind when processing collected paths: {}", *def)
}
}
+ for &(id, span, ref path, ref_kind) in paths_to_process.iter() {
+ self.process_path(id, span, path, ref_kind);
+ }
+ self.collecting = false;
self.collected_paths.clear();
visit::walk_expr_opt(self, &arm.guard);
self.visit_expr(&*arm.body);
})
}
-#[deriving(Copy)]
+#[deriving(Copy,Show)]
pub enum Row {
Variable,
Enum,
}
pub fn sub_span_after_keyword(&self,
- span: Span,
- keyword: keywords::Keyword) -> Option<Span> {
+ span: Span,
+ keyword: keywords::Keyword) -> Option<Span> {
let mut toks = self.retokenise_span(span);
loop {
let ts = toks.real_token();
llfn: ValueRef,
llargs: &[ValueRef],
fn_ty: Ty<'tcx>,
- call_info: Option<NodeInfo>,
- // FIXME(15064) is_lang_item is a horrible hack, please remove it
- // at the soonest opportunity.
- is_lang_item: bool)
+ call_info: Option<NodeInfo>)
-> (ValueRef, Block<'blk, 'tcx>) {
let _icx = push_ctxt("invoke_");
if bcx.unreachable.get() {
return (C_null(Type::i8(bcx.ccx())), bcx);
}
- // FIXME(15064) Lang item methods may (in the reflect case) not have proper
- // types, so doing an attribute lookup will fail.
- let attributes = if is_lang_item {
- llvm::AttrBuilder::new()
- } else {
- get_fn_llvm_attributes(bcx.ccx(), fn_ty)
- };
+ let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
match bcx.opt_node_id {
None => {
}
// work around bizarre resolve errors
-pub type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
-pub type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
+type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
// create_datums_for_fn_args: creates rvalue datums for each of the
// incoming function arguments. These will later be stored into
debug!("Store {} -> {}",
self.ccx.tn().val_to_string(val),
self.ccx.tn().val_to_string(ptr));
- assert!(self.llbuilder.is_not_null());
+ assert!(!self.llbuilder.is_null());
self.count_insn("store");
unsafe {
llvm::LLVMBuildStore(self.llbuilder, val, ptr);
debug!("Store {} -> {}",
self.ccx.tn().val_to_string(val),
self.ccx.tn().val_to_string(ptr));
- assert!(self.llbuilder.is_not_null());
+ assert!(!self.llbuilder.is_null());
self.count_insn("store.volatile");
unsafe {
let insn = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
llfn,
llargs[],
callee_ty,
- call_info,
- dest.is_none());
+ call_info);
bcx = b;
llresult = llret;
}
// work around bizarre resolve errors
-pub type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
-pub type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
+type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
+type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
// Function context. Every LLVM function we create will have one of
// these.
class_did,
&[get_drop_glue_type(bcx.ccx(), t)],
ty::mk_nil(bcx.tcx()));
- let (_, variant_cx) = invoke(variant_cx, dtor_addr, args[], dtor_ty, None, false);
+ let (_, variant_cx) = invoke(variant_cx, dtor_addr, args[], dtor_ty, None);
variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope);
variant_cx
macro_rules! opt_val { ($e:expr) => (
unsafe {
match $e {
- p if p.is_not_null() => Some(Value(p)),
+ p if !p.is_null() => Some(Value(p)),
_ => None
}
}
pub fn get_parent(self) -> Option<BasicBlock> {
unsafe {
match llvm::LLVMGetInstructionParent(self.get()) {
- p if p.is_not_null() => Some(BasicBlock(p)),
+ p if !p.is_null() => Some(BasicBlock(p)),
_ => None
}
}
pub fn get_first_use(self) -> Option<Use> {
unsafe {
match llvm::LLVMGetFirstUse(self.get()) {
- u if u.is_not_null() => Some(Use(u)),
+ u if !u.is_null() => Some(Use(u)),
_ => None
}
}
/// Tests if this value is a terminator instruction
pub fn is_a_terminator_inst(self) -> bool {
unsafe {
- llvm::LLVMIsATerminatorInst(self.get()).is_not_null()
+ !llvm::LLVMIsATerminatorInst(self.get()).is_null()
}
}
}
pub fn get_next_use(self) -> Option<Use> {
unsafe {
match llvm::LLVMGetNextUse(self.get()) {
- u if u.is_not_null() => Some(Use(u)),
+ u if !u.is_null() => Some(Use(u)),
_ => None
}
}
let mut m = String::new();
let len = v.len();
for (i, (name, n)) in v.into_iter().enumerate() {
- m.push_str(if n == 1 {
+ let help_name = if name.is_empty() {
+ format!("argument {}", i + 1)
+ } else {
format!("`{}`", name)
+ };
+
+ m.push_str(if n == 1 {
+ help_name
} else {
- format!("one of `{}`'s {} elided lifetimes", name, n)
+ format!("one of {}'s {} elided lifetimes", help_name, n)
}[]);
if len == 2 && i == 0 {
let mut trait_def_ids = DefIdMap::new();
for ast_bound in ast_bounds.iter() {
match *ast_bound {
- ast::TraitTyParamBound(ref b) => {
+ ast::TraitTyParamBound(ref b, ast::TraitBoundModifier::None) => {
match ::lookup_def_tcx(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
def::DefTrait(trait_did) => {
match trait_def_ids.get(&trait_did) {
}
trait_bounds.push(b);
}
+ ast::TraitTyParamBound(_, ast::TraitBoundModifier::Maybe) => {}
ast::RegionTyParamBound(ref l) => {
region_bounds.push(l);
}
}
}
- ast::ItemTrait(_, _, _, _, ref trait_methods) => {
+ ast::ItemTrait(_, _, _, ref trait_methods) => {
let trait_def = ty::lookup_trait_def(ccx.tcx, local_def(it.id));
for trait_method in trait_methods.iter() {
match *trait_method {
trait_def: &ty::TraitDef<'tcx>) {
let tcx = ccx.tcx;
if let ast_map::NodeItem(item) = tcx.map.get(trait_id) {
- if let ast::ItemTrait(_, _, _, _, ref trait_items) = item.node {
+ if let ast::ItemTrait(_, _, _, ref trait_items) = item.node {
// For each method, construct a suitable ty::Method and
// store it into the `tcx.impl_or_trait_items` table:
for trait_item in trait_items.iter() {
ast::RegionTyParamBound(..) => { }
}
}
-
- match ty_param.unbound {
- Some(_) => { warn = true; }
- None => { }
- }
}
if warn {
AllowEqConstraints::DontAllow);
}
},
- ast::ItemTrait(_, _, _, _, ref trait_methods) => {
+ ast::ItemTrait(_, _, _, ref trait_methods) => {
let trait_def = trait_def_of_item(ccx, it);
debug!("trait_def: ident={} trait_def={}",
return def.clone();
}
- let (unsafety, generics, unbound, bounds, items) = match it.node {
+ let (unsafety, generics, bounds, items) = match it.node {
ast::ItemTrait(unsafety,
ref generics,
- ref unbound,
ref supertraits,
ref items) => {
- (unsafety, generics, unbound, supertraits, items.as_slice())
+ (unsafety, generics, supertraits, items.as_slice())
}
ref s => {
tcx.sess.span_bug(
token::SELF_KEYWORD_NAME,
self_param_ty,
bounds.as_slice(),
- unbound,
it.span);
let substs = mk_item_substs(ccx, &ty_generics);
create_type_parameters_for_associated_types)
}
-// Add the Sized bound, unless the type parameter is marked as `Sized?`.
+// Add the Sized bound, unless the type parameter is marked as `?Sized`.
fn add_unsized_bound<'tcx,AC>(this: &AC,
- unbound: &Option<ast::TraitRef>,
bounds: &mut ty::BuiltinBounds,
- desc: &str,
+ ast_bounds: &[ast::TyParamBound],
span: Span)
where AC: AstConv<'tcx> {
+ // Try to find an unbound in bounds.
+ let mut unbound = None;
+ for ab in ast_bounds.iter() {
+ if let &ast::TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = ab {
+ if unbound.is_none() {
+ assert!(ptr.bound_lifetimes.is_empty());
+ unbound = Some(ptr.trait_ref.clone());
+ } else {
+ this.tcx().sess.span_err(span, "type parameter has more than one relaxed default \
+ bound, only one is supported");
+ }
+ }
+ }
+
let kind_id = this.tcx().lang_items.require(SizedTraitLangItem);
match unbound {
- &Some(ref tpb) => {
+ Some(ref tpb) => {
// FIXME(#8559) currently requires the unbound to be built-in.
let trait_def_id = ty::trait_ref_to_def_id(this.tcx(), tpb);
match kind_id {
Ok(kind_id) if trait_def_id != kind_id => {
this.tcx().sess.span_warn(span,
- format!("default bound relaxed \
- for a {}, but this \
- does nothing because \
- the given bound is not \
- a default. \
- Only `Sized?` is \
- supported",
- desc)[]);
+ "default bound relaxed for a type parameter, but \
+ this does nothing because the given bound is not \
+ a default. Only `?Sized` is supported");
ty::try_add_builtin_trait(this.tcx(),
kind_id,
bounds);
ty::try_add_builtin_trait(this.tcx(), kind_id.unwrap(), bounds);
}
// No lang item for Sized, so we can't add it as a bound.
- &None => {}
+ None => {}
}
}
for bound in bound_pred.bounds.iter() {
match bound {
- &ast::TyParamBound::TraitTyParamBound(ref poly_trait_ref) => {
+ &ast::TyParamBound::TraitTyParamBound(ref poly_trait_ref, _) => {
let trait_ref = astconv::instantiate_poly_trait_ref(
this,
&ExplicitRscope,
for bound in param.bounds.iter() {
// In the above example, `ast_trait_ref` is `Iterator`.
let ast_trait_ref = match *bound {
- ast::TraitTyParamBound(ref r) => r,
+ ast::TraitTyParamBound(ref r, _) => r,
ast::RegionTyParamBound(..) => { continue; }
};
param.ident.name,
param_ty,
param.bounds[],
- ¶m.unbound,
param.span);
let default = match param.default {
None => None,
name_of_bounded_thing: ast::Name,
param_ty: ty::ParamTy,
ast_bounds: &[ast::TyParamBound],
- unbound: &Option<ast::TraitRef>,
span: Span)
-> ty::ParamBounds<'tcx>
where AC: AstConv<'tcx> {
param_ty,
ast_bounds);
-
add_unsized_bound(this,
- unbound,
&mut param_bounds.builtin_bounds,
- "type parameter",
+ ast_bounds,
span);
check_bounds_compatible(this.tcx(),
match item.node {
ast::ItemEnum(_, ref generics) |
ast::ItemStruct(_, ref generics) |
- ast::ItemTrait(_, ref generics, _, _, _) => {
+ ast::ItemTrait(_, ref generics, _, _) => {
for (i, p) in generics.lifetimes.iter().enumerate() {
let id = p.lifetime.id;
self.add_inferred(item.id, RegionParam, TypeSpace, i, id);
}
});
let trait_def = ty::lookup_trait_def(tcx, did);
- let (bounds, default_unbound) = trait_def.bounds.clean(cx);
+ let bounds = trait_def.bounds.clean(cx);
clean::Trait {
unsafety: def.unsafety,
generics: (&def.generics, subst::TypeSpace).clean(cx),
items: items.collect(),
bounds: bounds,
- default_unbound: default_unbound
}
}
derived: clean::detect_derived(attrs.as_slice()),
trait_: associated_trait.clean(cx).map(|bound| {
match bound {
- clean::TraitBound(polyt) => polyt.trait_,
+ clean::TraitBound(polyt, _) => polyt.trait_,
clean::RegionBound(..) => unreachable!(),
}
}),
pub did: ast::DefId,
pub bounds: Vec<TyParamBound>,
pub default: Option<Type>,
- /// An optional default bound on the parameter which is unbound, like `Sized?`
- pub default_unbound: Option<Type>
}
impl Clean<TyParam> for ast::TyParam {
did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
bounds: self.bounds.clean(cx),
default: self.default.clean(cx),
- default_unbound: self.unbound.clean(cx)
}
}
}
fn clean(&self, cx: &DocContext) -> TyParam {
cx.external_typarams.borrow_mut().as_mut().unwrap()
.insert(self.def_id, self.name.clean(cx));
- let (bounds, default_unbound) = self.bounds.clean(cx);
+ let bounds = self.bounds.clean(cx);
TyParam {
name: self.name.clean(cx),
did: self.def_id,
bounds: bounds,
default: self.default.clean(cx),
- default_unbound: default_unbound
}
}
}
#[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
pub enum TyParamBound {
RegionBound(Lifetime),
- TraitBound(PolyTrait)
+ TraitBound(PolyTrait, ast::TraitBoundModifier)
}
impl Clean<TyParamBound> for ast::TyParamBound {
fn clean(&self, cx: &DocContext) -> TyParamBound {
match *self {
ast::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
- ast::TraitTyParamBound(ref t) => TraitBound(t.clean(cx)),
+ ast::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
}
}
}
did: did,
},
lifetimes: vec![]
- })
+ }, ast::TraitBoundModifier::None)
}
}
TraitBound(PolyTrait {
trait_: ResolvedPath { path: path, typarams: None, did: self.def_id, },
lifetimes: late_bounds
- })
+ }, ast::TraitBoundModifier::None)
}
}
-// Returns (bounds, default_unbound)
-impl<'tcx> Clean<(Vec<TyParamBound>, Option<Type>)> for ty::ParamBounds<'tcx> {
- fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Option<Type>) {
+impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> {
+ fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
let mut v = Vec::new();
- let mut has_sized_bound = false;
- for b in self.builtin_bounds.iter() {
- if b != ty::BoundSized {
- v.push(b.clean(cx));
- } else {
- has_sized_bound = true;
- }
- }
for t in self.trait_bounds.iter() {
v.push(t.clean(cx));
}
for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) {
v.push(RegionBound(r));
}
- if has_sized_bound {
- (v, None)
- } else {
- let ty = match ty::BoundSized.clean(cx) {
- TraitBound(polyt) => polyt.trait_,
- _ => unreachable!()
- };
- (v, Some(ty))
- }
+ v
}
}
v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
trait_: t.clean(cx),
lifetimes: vec![]
- })));
+ }, ast::TraitBoundModifier::None)));
if v.len() > 0 {Some(v)} else {None}
}
}
pub items: Vec<TraitMethod>,
pub generics: Generics,
pub bounds: Vec<TyParamBound>,
- /// An optional default bound not required for `Self`, like `Sized?`
- pub default_unbound: Option<Type>
}
impl Clean<Item> for doctree::Trait {
items: self.items.clean(cx),
generics: self.generics.clean(cx),
bounds: self.bounds.clean(cx),
- default_unbound: self.default_unbound.clean(cx)
}),
}
}
},
bounds: vec![],
default: None,
- default_unbound: None
}),
visibility: None,
def_id: self.def_id,
pub whence: Span,
pub vis: ast::Visibility,
pub stab: Option<attr::Stability>,
- pub default_unbound: Option<ast::TraitRef> // FIXME(tomjakubowski)
}
pub struct Impl {
if i > 0 {
try!(f.write(", ".as_bytes()))
}
- if let Some(ref unbound) = tp.default_unbound {
- try!(write!(f, "{}? ", unbound));
- };
try!(f.write(tp.name.as_bytes()));
if tp.bounds.len() > 0 {
if gens.where_predicates.len() == 0 {
return Ok(());
}
- try!(f.write(" where ".as_bytes()));
+ try!(f.write(" <span class='where'>where ".as_bytes()));
for (i, pred) in gens.where_predicates.iter().enumerate() {
if i > 0 {
try!(f.write(", ".as_bytes()));
}
}
}
+ try!(f.write("</span>".as_bytes()));
Ok(())
}
}
clean::RegionBound(ref lt) => {
write!(f, "{}", *lt)
}
- clean::TraitBound(ref ty) => {
- write!(f, "{}", *ty)
+ clean::TraitBound(ref ty, modifier) => {
+ let modifier_str = match modifier {
+ ast::TraitBoundModifier::None => "",
+ ast::TraitBoundModifier::Maybe => "?",
+ };
+ write!(f, "{}{}", modifier_str, *ty)
}
}
}
for bound in decl.bounds.iter() {
match *bound {
clean::RegionBound(..) => {}
- clean::TraitBound(ref t) => {
+ clean::TraitBound(ref t, modifier) => {
if ret.len() == 0 {
ret.push_str(": ");
} else {
ret.push_str(" + ");
}
+ if modifier == ast::TraitBoundModifier::Maybe {
+ ret.push_str("?");
+ }
ret.push_str(format!("{}",
*t).as_slice());
}
fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
t: &clean::Trait) -> fmt::Result {
let mut bounds = String::new();
- if let Some(ref ty) = t.default_unbound {
- bounds.push_str(format!(" for {}?", ty).as_slice());
- }
if t.bounds.len() > 0 {
if bounds.len() > 0 {
bounds.push(' ');
font-size: 1em;
position: relative;
}
+/* Shift "where ..." part of method definition down a line */
+.content .method .where { display: block; }
+/* Bit of whitespace to indent it */
+.content .method .where::before { content: ' '; }
+
.content .methods .docblock { margin-left: 40px; }
.content .impl-items .docblock { margin-left: 40px; }
};
om.constants.push(s);
},
- ast::ItemTrait(unsafety, ref gen, ref def_ub, ref b, ref items) => {
+ ast::ItemTrait(unsafety, ref gen, ref b, ref items) => {
let t = Trait {
unsafety: unsafety,
name: name,
whence: item.span,
vis: item.vis,
stab: self.stability(item.id),
- default_unbound: def_ub.clone()
};
om.traits.push(t);
},
#[test]
fn test_base64_random() {
- use std::rand::{task_rng, random, Rng};
+ use std::rand::{thread_rng, random, Rng};
for _ in range(0u, 1000) {
- let times = task_rng().gen_range(1u, 100);
+ let times = thread_rng().gen_range(1u, 100);
let v = Vec::from_fn(times, |_| random::<u8>());
assert_eq!(v.to_base64(STANDARD)
.from_base64()
//! * `String`: equivalent to rust's `String`
//! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
//! same array
-//! * `Object`: equivalent to rust's `Treemap<String, json::Json>`
+//! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
//! * `Null`
//!
//! An object is a series of string keys mapping to values, in `"key": value` format.
#[test]
fn test_from_str_trait() {
let s = "null";
- assert!(::std::str::from_str::<Json>(s).unwrap() == from_str(s).unwrap());
+ assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
}
#[test]
let array3 = Array(vec!(U64(1), U64(2), U64(3)));
let object = {
let mut tree_map = BTreeMap::new();
- tree_map.insert("a".into_string(), U64(1));
- tree_map.insert("b".into_string(), U64(2));
+ tree_map.insert("a".to_string(), U64(1));
+ tree_map.insert("b".to_string(), U64(2));
Object(tree_map)
};
assert_eq!((vec![1u, 2]).to_json(), array2);
assert_eq!(vec!(1u, 2, 3).to_json(), array3);
let mut tree_map = BTreeMap::new();
- tree_map.insert("a".into_string(), 1u);
- tree_map.insert("b".into_string(), 2);
+ tree_map.insert("a".to_string(), 1u);
+ tree_map.insert("b".to_string(), 2);
assert_eq!(tree_map.to_json(), object);
let mut hash_map = HashMap::new();
hash_map.insert("a".to_string(), 1u);
/// - `empty`: an empty set of flags
/// - `all`: the set of all flags
/// - `bits`: the raw value of the flags currently stored
+/// - `from_bits`: convert from underlying bit representation, unless that
+/// representation contains bits that do not correspond to a flag
+/// - `from_bits_truncate`: convert from underlying bit representation, dropping
+/// any bits that do not correspond to flags
/// - `is_empty`: `true` if no flags are currently stored
/// - `is_all`: `true` if all flags are currently set
/// - `intersects`: `true` if there are flags common to both `self` and `other`
#[cfg(test)]
mod tests {
use super::*;
- use prelude::*;
+ use prelude::{spawn, Some, None, Option, FnOnce, ToString, CloneSliceExt};
+ use prelude::{Clone, PtrExt, Iterator, SliceExt, StrExt};
use ptr;
use thread::Thread;
use libc;
use ops::{Drop, FnOnce};
use option::Option;
use option::Option::{Some, None};
-use ptr::RawPtr;
+use ptr::PtrExt;
use ptr;
use raw;
use slice::AsSlice;
/// }
/// ```
///
-/// The easiest way to use `HashMap` with a custom type is to derive `Eq` and `Hash`.
+/// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`.
/// We must also derive `PartialEq`.
///
/// ```
/// use std::collections::HashMap;
///
/// #[deriving(Hash, Eq, PartialEq, Show)]
-/// struct Viking<'a> {
-/// name: &'a str,
-/// power: uint,
+/// struct Viking {
+/// name: String,
+/// country: String,
/// }
///
+/// impl Viking {
+/// /// Create a new Viking.
+/// fn new(name: &str, country: &str) -> Viking {
+/// Viking { name: name.to_string(), country: country.to_string() }
+/// }
+/// }
+///
+/// // Use a HashMap to store the vikings' health points.
/// let mut vikings = HashMap::new();
///
-/// vikings.insert("Norway", Viking { name: "Einar", power: 9u });
-/// vikings.insert("Denmark", Viking { name: "Olaf", power: 4u });
-/// vikings.insert("Iceland", Viking { name: "Harald", power: 8u });
+/// vikings.insert(Viking::new("Einar", "Norway"), 25u);
+/// vikings.insert(Viking::new("Olaf", "Denmark"), 24u);
+/// vikings.insert(Viking::new("Harald", "Iceland"), 12u);
///
-/// // Use derived implementation to print the vikings.
-/// for (land, viking) in vikings.iter() {
-/// println!("{} at {}", viking, land);
+/// // Use derived implementation to print the status of the vikings.
+/// for (viking, health) in vikings.iter() {
+/// println!("{} has {} hp", viking, health);
/// }
/// ```
#[deriving(Clone)]
/// }
/// ```
#[unstable = "matches collection reform specification, waiting for dust to settle"]
- pub fn iter(&self) -> Entries<K, V> {
- Entries { inner: self.table.iter() }
+ pub fn iter(&self) -> Iter<K, V> {
+ Iter { inner: self.table.iter() }
}
/// An iterator visiting all key-value pairs in arbitrary order,
}
/// HashMap iterator
-pub struct Entries<'a, K: 'a, V: 'a> {
- inner: table::Entries<'a, K, V>
+pub struct Iter<'a, K: 'a, V: 'a> {
+ inner: table::Iter<'a, K, V>
}
/// HashMap mutable values iterator
/// HashMap keys iterator
pub struct Keys<'a, K: 'a, V: 'a> {
- inner: Map<(&'a K, &'a V), &'a K, Entries<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
+ inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
}
/// HashMap values iterator
pub struct Values<'a, K: 'a, V: 'a> {
- inner: Map<(&'a K, &'a V), &'a V, Entries<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
+ inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
}
/// HashMap drain iterator
NoElem(EmptyBucket<K, V, M>),
}
-impl<'a, K, V> Iterator<(&'a K, &'a V)> for Entries<'a, K, V> {
+impl<'a, K, V> Iterator<(&'a K, &'a V)> for Iter<'a, K, V> {
#[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
#[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
}
use ops::{Deref, DerefMut, Drop};
use option::Option;
use option::Option::{Some, None};
-use ptr::{Unique, RawPtr, copy_nonoverlapping_memory, zero_memory};
+use ptr::{Unique, PtrExt, copy_nonoverlapping_memory, zero_memory};
use ptr;
use rt::heap::{allocate, deallocate};
}
}
- pub fn iter(&self) -> Entries<K, V> {
- Entries {
+ pub fn iter(&self) -> Iter<K, V> {
+ Iter {
iter: self.raw_buckets(),
elems_left: self.size(),
}
}
/// Iterator over shared references to entries in a table.
-pub struct Entries<'a, K: 'a, V: 'a> {
+pub struct Iter<'a, K: 'a, V: 'a> {
iter: RawBuckets<'a, K, V>,
elems_left: uint,
}
iter: RawBuckets<'static, K, V>,
}
-impl<'a, K, V> Iterator<(&'a K, &'a V)> for Entries<'a, K, V> {
+impl<'a, K, V> Iterator<(&'a K, &'a V)> for Iter<'a, K, V> {
fn next(&mut self) -> Option<(&'a K, &'a V)> {
self.iter.next().map(|bucket| {
self.elems_left -= 1;
// senders. Under the hood, however, there are actually three flavors of
// channels in play.
//
-// * Oneshots - these channels are highly optimized for the one-send use case.
+// * Flavor::Oneshots - these channels are highly optimized for the one-send use case.
// They contain as few atomics as possible and involve one and
// exactly one allocation.
// * Streams - these channels are optimized for the non-shared use case. They
pub use self::TryRecvError::*;
pub use self::TrySendError::*;
-use self::Flavor::*;
use alloc::arc::Arc;
use core::kinds;
use super::*;
use comm::*;
use thread::Thread;
- use prelude::*;
+ use prelude::{Ok, Err, spawn, range, drop, Box, Some, None, Option};
+ use prelude::{Vec, Buffer, from_str, Clone};
$(#[$a])* #[test] fn f() { $b }
}
#[unstable]
pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) {
let a = Arc::new(RacyCell::new(oneshot::Packet::new()));
- (Sender::new(Oneshot(a.clone())), Receiver::new(Oneshot(a)))
+ (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a)))
}
/// Creates a new synchronous, bounded channel.
of channel that is is creating"]
pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) {
let a = Arc::new(RacyCell::new(sync::Packet::new(bound)));
- (SyncSender::new(a.clone()), Receiver::new(Sync(a)))
+ (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a)))
}
////////////////////////////////////////////////////////////////////////////////
#[unstable = "this function may be renamed to send() in the future"]
pub fn send_opt(&self, t: T) -> Result<(), T> {
let (new_inner, ret) = match *unsafe { self.inner() } {
- Oneshot(ref p) => {
+ Flavor::Oneshot(ref p) => {
unsafe {
let p = p.get();
if !(*p).sent() {
} else {
let a =
Arc::new(RacyCell::new(stream::Packet::new()));
- match (*p).upgrade(Receiver::new(Stream(a.clone()))) {
+ match (*p).upgrade(Receiver::new(Flavor::Stream(a.clone()))) {
oneshot::UpSuccess => {
let ret = (*a.get()).send(t);
(a, ret)
}
}
}
- Stream(ref p) => return unsafe { (*p.get()).send(t) },
- Shared(ref p) => return unsafe { (*p.get()).send(t) },
- Sync(..) => unreachable!(),
+ Flavor::Stream(ref p) => return unsafe { (*p.get()).send(t) },
+ Flavor::Shared(ref p) => return unsafe { (*p.get()).send(t) },
+ Flavor::Sync(..) => unreachable!(),
};
unsafe {
- let tmp = Sender::new(Stream(new_inner));
+ let tmp = Sender::new(Flavor::Stream(new_inner));
mem::swap(self.inner_mut(), tmp.inner_mut());
}
return ret;
impl<T: Send> Clone for Sender<T> {
fn clone(&self) -> Sender<T> {
let (packet, sleeper, guard) = match *unsafe { self.inner() } {
- Oneshot(ref p) => {
+ Flavor::Oneshot(ref p) => {
let a = Arc::new(RacyCell::new(shared::Packet::new()));
unsafe {
let guard = (*a.get()).postinit_lock();
- match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) {
+ match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) {
oneshot::UpSuccess |
oneshot::UpDisconnected => (a, None, guard),
oneshot::UpWoke(task) => (a, Some(task), guard)
}
}
}
- Stream(ref p) => {
+ Flavor::Stream(ref p) => {
let a = Arc::new(RacyCell::new(shared::Packet::new()));
unsafe {
let guard = (*a.get()).postinit_lock();
- match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) {
+ match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) {
stream::UpSuccess |
stream::UpDisconnected => (a, None, guard),
stream::UpWoke(task) => (a, Some(task), guard),
}
}
}
- Shared(ref p) => {
+ Flavor::Shared(ref p) => {
unsafe { (*p.get()).clone_chan(); }
- return Sender::new(Shared(p.clone()));
+ return Sender::new(Flavor::Shared(p.clone()));
}
- Sync(..) => unreachable!(),
+ Flavor::Sync(..) => unreachable!(),
};
unsafe {
(*packet.get()).inherit_blocker(sleeper, guard);
- let tmp = Sender::new(Shared(packet.clone()));
+ let tmp = Sender::new(Flavor::Shared(packet.clone()));
mem::swap(self.inner_mut(), tmp.inner_mut());
}
- Sender::new(Shared(packet))
+ Sender::new(Flavor::Shared(packet))
}
}
impl<T: Send> Drop for Sender<T> {
fn drop(&mut self) {
match *unsafe { self.inner_mut() } {
- Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); },
- Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); },
- Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); },
- Sync(..) => unreachable!(),
+ Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); },
+ Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); },
+ Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); },
+ Flavor::Sync(..) => unreachable!(),
}
}
}
pub fn try_recv(&self) -> Result<T, TryRecvError> {
loop {
let new_port = match *unsafe { self.inner() } {
- Oneshot(ref p) => {
+ Flavor::Oneshot(ref p) => {
match unsafe { (*p.get()).try_recv() } {
Ok(t) => return Ok(t),
Err(oneshot::Empty) => return Err(Empty),
Err(oneshot::Upgraded(rx)) => rx,
}
}
- Stream(ref p) => {
+ Flavor::Stream(ref p) => {
match unsafe { (*p.get()).try_recv() } {
Ok(t) => return Ok(t),
Err(stream::Empty) => return Err(Empty),
Err(stream::Upgraded(rx)) => rx,
}
}
- Shared(ref p) => {
+ Flavor::Shared(ref p) => {
match unsafe { (*p.get()).try_recv() } {
Ok(t) => return Ok(t),
Err(shared::Empty) => return Err(Empty),
Err(shared::Disconnected) => return Err(Disconnected),
}
}
- Sync(ref p) => {
+ Flavor::Sync(ref p) => {
match unsafe { (*p.get()).try_recv() } {
Ok(t) => return Ok(t),
Err(sync::Empty) => return Err(Empty),
pub fn recv_opt(&self) -> Result<T, ()> {
loop {
let new_port = match *unsafe { self.inner() } {
- Oneshot(ref p) => {
+ Flavor::Oneshot(ref p) => {
match unsafe { (*p.get()).recv() } {
Ok(t) => return Ok(t),
Err(oneshot::Empty) => return unreachable!(),
Err(oneshot::Upgraded(rx)) => rx,
}
}
- Stream(ref p) => {
+ Flavor::Stream(ref p) => {
match unsafe { (*p.get()).recv() } {
Ok(t) => return Ok(t),
Err(stream::Empty) => return unreachable!(),
Err(stream::Upgraded(rx)) => rx,
}
}
- Shared(ref p) => {
+ Flavor::Shared(ref p) => {
match unsafe { (*p.get()).recv() } {
Ok(t) => return Ok(t),
Err(shared::Empty) => return unreachable!(),
Err(shared::Disconnected) => return Err(()),
}
}
- Sync(ref p) => return unsafe { (*p.get()).recv() }
+ Flavor::Sync(ref p) => return unsafe { (*p.get()).recv() }
};
unsafe {
mem::swap(self.inner_mut(), new_port.inner_mut());
fn can_recv(&self) -> bool {
loop {
let new_port = match *unsafe { self.inner() } {
- Oneshot(ref p) => {
+ Flavor::Oneshot(ref p) => {
match unsafe { (*p.get()).can_recv() } {
Ok(ret) => return ret,
Err(upgrade) => upgrade,
}
}
- Stream(ref p) => {
+ Flavor::Stream(ref p) => {
match unsafe { (*p.get()).can_recv() } {
Ok(ret) => return ret,
Err(upgrade) => upgrade,
}
}
- Shared(ref p) => {
+ Flavor::Shared(ref p) => {
return unsafe { (*p.get()).can_recv() };
}
- Sync(ref p) => {
+ Flavor::Sync(ref p) => {
return unsafe { (*p.get()).can_recv() };
}
};
fn start_selection(&self, mut token: SignalToken) -> StartResult {
loop {
let (t, new_port) = match *unsafe { self.inner() } {
- Oneshot(ref p) => {
+ Flavor::Oneshot(ref p) => {
match unsafe { (*p.get()).start_selection(token) } {
oneshot::SelSuccess => return Installed,
oneshot::SelCanceled => return Abort,
oneshot::SelUpgraded(t, rx) => (t, rx),
}
}
- Stream(ref p) => {
+ Flavor::Stream(ref p) => {
match unsafe { (*p.get()).start_selection(token) } {
stream::SelSuccess => return Installed,
stream::SelCanceled => return Abort,
stream::SelUpgraded(t, rx) => (t, rx),
}
}
- Shared(ref p) => {
+ Flavor::Shared(ref p) => {
return unsafe { (*p.get()).start_selection(token) };
}
- Sync(ref p) => {
+ Flavor::Sync(ref p) => {
return unsafe { (*p.get()).start_selection(token) };
}
};
let mut was_upgrade = false;
loop {
let result = match *unsafe { self.inner() } {
- Oneshot(ref p) => unsafe { (*p.get()).abort_selection() },
- Stream(ref p) => unsafe {
+ Flavor::Oneshot(ref p) => unsafe { (*p.get()).abort_selection() },
+ Flavor::Stream(ref p) => unsafe {
(*p.get()).abort_selection(was_upgrade)
},
- Shared(ref p) => return unsafe {
+ Flavor::Shared(ref p) => return unsafe {
(*p.get()).abort_selection(was_upgrade)
},
- Sync(ref p) => return unsafe {
+ Flavor::Sync(ref p) => return unsafe {
(*p.get()).abort_selection()
},
};
impl<T: Send> Drop for Receiver<T> {
fn drop(&mut self) {
match *unsafe { self.inner_mut() } {
- Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); },
- Stream(ref mut p) => unsafe { (*p.get()).drop_port(); },
- Shared(ref mut p) => unsafe { (*p.get()).drop_port(); },
- Sync(ref mut p) => unsafe { (*p.get()).drop_port(); },
+ Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); },
+ Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_port(); },
+ Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_port(); },
+ Flavor::Sync(ref mut p) => unsafe { (*p.get()).drop_port(); },
}
}
}
#[cfg(test)]
mod test {
use super::*;
- use prelude::*;
+ use prelude::{spawn, range, Some, None, from_str, Clone, Str};
use os;
pub fn stress_factor() -> uint {
// and that could cause problems on platforms where it is
// represented by opaque data structure
pub fn postinit_lock(&self) -> MutexGuard<()> {
- self.select_lock.lock()
+ self.select_lock.lock().unwrap()
}
// This function is used at the creation of a shared packet to inherit a
// about looking at and dealing with to_wake. Once we have acquired the
// lock, we are guaranteed that inherit_blocker is done.
{
- let _guard = self.select_lock.lock();
+ let _guard = self.select_lock.lock().unwrap();
}
// Like the stream implementation, we want to make sure that the count
NoneBlocked => {}
_ => unreachable!(),
}
- drop(guard); // unlock
- wait_token.wait(); // block
- lock.lock() // relock
+ drop(guard); // unlock
+ wait_token.wait(); // block
+ lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: 0 as *mut Node };
loop {
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::RecvDisconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
}
pub fn try_recv(&self) -> Result<T, Failure> {
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
}
// Not much to do other than wake up a receiver if one's there
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
}
pub fn drop_port(&self) {
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
- let guard = self.lock.lock();
+ let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else {
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(atomic::SeqCst), 0);
- let mut guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
use prelude::*;
use str::Utf8Error;
+use string::{FromUtf8Error, FromUtf16Error};
/// Base functionality for all errors in Rust.
pub trait Error: Send {
fn detail(&self) -> Option<String> { Some(self.to_string()) }
}
+
+impl Error for FromUtf8Error {
+ fn description(&self) -> &str { "invalid utf-8" }
+ fn detail(&self) -> Option<String> { Some(self.to_string()) }
+}
+
+impl Error for FromUtf16Error {
+ fn description(&self) -> &str { "invalid utf-16" }
+}
/// Construct a new `RandomSipHasher` that is initialized with random keys.
#[inline]
pub fn new() -> RandomSipHasher {
- let mut r = rand::task_rng();
+ let mut r = rand::thread_rng();
let r0 = r.gen();
let r1 = r.gen();
RandomSipHasher {
use ops::FnOnce;
use option::Option;
use option::Option::{Some, None};
-use ptr::RawPtr;
+use ptr::PtrExt;
use result::Result::{Ok, Err};
use slice::{SliceExt, AsSlice};
check!(rmdir_recursive(dir));
}
+ #[test]
+ fn mkdir_path_already_exists_error() {
+ use io::{IoError, PathAlreadyExists};
+
+ let tmpdir = tmpdir();
+ let dir = &tmpdir.join("mkdir_error_twice");
+ check!(mkdir(dir, io::USER_RWX));
+ match mkdir(dir, io::USER_RWX) {
+ Err(IoError{kind:PathAlreadyExists,..}) => (),
+ _ => assert!(false)
+ };
+ }
+
#[test]
fn recursive_mkdir() {
let tmpdir = tmpdir();
mod test {
extern crate "test" as test_crate;
use super::*;
- use io::*;
- use prelude::*;
+ use io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek};
+ use prelude::{Ok, Err, range, Vec, Buffer, AsSlice, SliceExt, IteratorExt, CloneSliceExt};
use io;
use self::test_crate::Bencher;
// API yet. If so, it should be a method on Vec.
unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
use raw::Slice;
- use ptr::RawPtr;
+ use ptr::PtrExt;
assert!(start <= end);
assert!(end <= v.capacity());
/// A mode specifies how a file should be opened or created. These modes are
/// passed to `File::open_mode` and are used to control where the file is
/// positioned when it is initially opened.
-#[deriving(Copy)]
+#[deriving(Copy, Clone, PartialEq, Eq)]
pub enum FileMode {
/// Opens a file positioned at the beginning.
Open,
/// Access permissions with which the file should be opened. `File`s
/// opened with `Read` will return an error if written to.
-#[deriving(Copy)]
+#[deriving(Copy, Clone, PartialEq, Eq)]
pub enum FileAccess {
/// Read-only access, requests to write will result in an error
Read,
#[cfg(test)]
mod tests {
use self::BadReaderBehavior::*;
- use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput};
- use prelude::*;
+ use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput, Writer};
+ use prelude::{Ok, Vec, Buffer, CloneSliceExt};
use uint;
#[deriving(Clone, PartialEq, Show)]
use super::*;
use io::*;
use io::test::*;
- use prelude::*;
+ use prelude::{Ok, Err, spawn, range, drop, Some, None, channel, Send, FnOnce, Clone};
use io::fs::PathExtensions;
use time::Duration;
mod test {
use io::net::tcp::*;
use io::net::ip::*;
- use io::*;
+ use io::{EndOfFile, TimedOut, IoError, ShortWrite, OtherIoError, ConnectionAborted};
+ use io::{ConnectionRefused, ConnectionReset, BrokenPipe, NotConnected};
+ use io::{PermissionDenied, Listener, Acceptor};
use io::test::*;
- use prelude::*;
+ use prelude::{Ok, Err, spawn, range, drop, Some, None, channel, Clone};
+ use prelude::{Reader, Writer, IteratorExt};
// FIXME #11530 this fails on android because tests are run as root
#[cfg_attr(any(windows, target_os = "android"), ignore)]
mod test {
use super::*;
use io::net::ip::*;
- use io::*;
+ use io::{ShortWrite, IoError, TimedOut, PermissionDenied};
use io::test::*;
- use prelude::*;
+ use prelude::{Ok, Err, spawn, range, drop, Some, None, channel, Clone, Reader, Writer};
// FIXME #11530 this fails on android because tests are run as root
#[cfg_attr(any(windows, target_os = "android"), ignore)]
use super::*;
use io::timer::*;
- use io::*;
- use prelude::*;
+ use io::{Truncate, Write, TimedOut, timer, process, FileNotFound};
+ use prelude::{Ok, Err, spawn, range, drop, Box, Some, None, Option, Vec, Buffer};
+ use prelude::{from_str, Path, String, channel, Reader, Writer, Clone, Slice};
+ use prelude::{SliceExt, Str, StrExt, AsSlice, ToString, GenericPath};
use io::fs::PathExtensions;
use time::Duration;
use str;
#[test]
#[cfg(windows)]
fn env_map_keys_ci() {
+ use c_str::ToCStr;
use super::EnvKey;
let mut cmd = Command::new("");
cmd.env("path", "foo");
/// ```
pub fn lock<'a>(&'a mut self) -> StdinReaderGuard<'a> {
StdinReaderGuard {
- inner: self.inner.lock()
+ inner: self.inner.lock().unwrap()
}
}
/// The read is performed atomically - concurrent read calls in other
/// threads will not interleave with this one.
pub fn read_line(&mut self) -> IoResult<String> {
- self.inner.lock().0.read_line()
+ self.inner.lock().unwrap().0.read_line()
}
/// Like `Buffer::read_until`.
/// The read is performed atomically - concurrent read calls in other
/// threads will not interleave with this one.
pub fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
- self.inner.lock().0.read_until(byte)
+ self.inner.lock().unwrap().0.read_until(byte)
}
/// Like `Buffer::read_char`.
/// The read is performed atomically - concurrent read calls in other
/// threads will not interleave with this one.
pub fn read_char(&mut self) -> IoResult<char> {
- self.inner.lock().0.read_char()
+ self.inner.lock().unwrap().0.read_char()
}
}
impl Reader for StdinReader {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
- self.inner.lock().0.read(buf)
+ self.inner.lock().unwrap().0.read(buf)
}
// We have to manually delegate all of these because the default impls call
// incur the costs of repeated locking).
fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
- self.inner.lock().0.read_at_least(min, buf)
+ self.inner.lock().unwrap().0.read_at_least(min, buf)
}
fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
- self.inner.lock().0.push_at_least(min, len, buf)
+ self.inner.lock().unwrap().0.push_at_least(min, len, buf)
}
fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
- self.inner.lock().0.read_to_end()
+ self.inner.lock().unwrap().0.read_to_end()
}
fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
- self.inner.lock().0.read_le_uint_n(nbytes)
+ self.inner.lock().unwrap().0.read_le_uint_n(nbytes)
}
fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
- self.inner.lock().0.read_be_uint_n(nbytes)
+ self.inner.lock().unwrap().0.read_be_uint_n(nbytes)
}
}
use io;
use boxed::Box;
use super::*;
- use prelude::*;
+ use prelude::{Ok, range, Vec, Buffer, Writer, Reader, ToString, AsSlice};
#[test]
fn test_limit_reader_unlimited() {
#[cfg(test)]
mod tests {
- use prelude::*;
- use super::*;
+ use prelude::{range, Some, None, Option, IteratorExt};
+ use super::{from_int, from_uint, from_i32, from_i64, from_u64, from_u32};
+ use super::{from_f64, from_f32, from_u16, from_i16, from_u8, from_i8, Int};
+ use super::{cast, NumCast, ToPrimitive, FromPrimitive, UnsignedInt};
use i8;
use i16;
use i32;
use option::Option::{Some, None};
use path::{Path, GenericPath, BytesContainer};
use sys;
-use ptr::RawPtr;
+use sys::os as os_imp;
+use ptr::PtrExt;
use ptr;
use result::Result;
use result::Result::{Err, Ok};
let ptr = ptr as *const u16;
let buf = slice::from_raw_buf(&ptr, len);
let opt_s = String::from_utf16(sys::os::truncate_utf16_at_nul(buf));
- opt_s.expect("CommandLineToArgvW returned invalid UTF-16")
+ opt_s.ok().expect("CommandLineToArgvW returned invalid UTF-16")
});
unsafe {
}
fn make_rand_name() -> String {
- let mut rng = rand::task_rng();
+ let mut rng = rand::thread_rng();
let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
.collect::<String>());
assert!(getenv(n.as_slice()).is_none());
extern crate test;
use self::test::Bencher;
use super::*;
- use prelude::*;
+ use prelude::{Clone, GenericPath};
#[bench]
fn join_home_dir(b: &mut Bencher) {
use hash;
use io::Writer;
use iter::{AdditiveIterator, DoubleEndedIteratorExt, Extend};
-use iter::{Iterator, IteratorExt, Map};
+use iter::{Iterator, IteratorExt, Map, repeat};
use mem;
use option::Option;
use option::Option::{Some, None};
}
}
} else if is_abs && comps.is_empty() {
- Some(String::from_char(1, SEP))
+ Some(repeat(SEP).take(1).collect())
} else {
let prefix_ = s[0..prefix_len(prefix)];
let n = prefix_.len() +
#[doc(no_inline)] pub use option::Option;
#[doc(no_inline)] pub use option::Option::{Some, None};
#[doc(no_inline)] pub use path::{GenericPath, Path, PosixPath, WindowsPath};
-#[doc(no_inline)] pub use ptr::{RawPtr, RawMutPtr};
+#[doc(no_inline)] pub use ptr::{PtrExt, MutPtrExt};
#[doc(no_inline)] pub use result::Result;
#[doc(no_inline)] pub use result::Result::{Ok, Err};
#[doc(no_inline)] pub use io::{Buffer, Writer, Reader, Seek, BufferPrelude};
//! See the `distributions` submodule for sampling random numbers from
//! distributions like normal and exponential.
//!
-//! # Task-local RNG
+//! # Thread-local RNG
//!
-//! There is built-in support for a RNG associated with each task stored
-//! in task-local storage. This RNG can be accessed via `task_rng`, or
+//! There is built-in support for a RNG associated with each thread stored
+//! in thread-local storage. This RNG can be accessed via `thread_rng`, or
//! used implicitly via `random`. This RNG is normally randomly seeded
//! from an operating-system source of randomness, e.g. `/dev/urandom` on
//! Unix systems, and will automatically reseed itself from this source
//! use std::rand;
//! use std::rand::Rng;
//!
-//! let mut rng = rand::task_rng();
+//! let mut rng = rand::thread_rng();
//! if rng.gen() { // random bool
//! println!("int: {}, uint: {}", rng.gen::<int>(), rng.gen::<uint>())
//! }
//!
//! fn main() {
//! let between = Range::new(-1f64, 1.);
-//! let mut rng = rand::task_rng();
+//! let mut rng = rand::thread_rng();
//!
//! let total = 1_000_000u;
//! let mut in_circle = 0u;
//! // The estimation will be more accurate with more simulations
//! let num_simulations = 10000u;
//!
-//! let mut rng = rand::task_rng();
+//! let mut rng = rand::thread_rng();
//! let random_door = Range::new(0u, 3);
//!
//! let (mut switch_wins, mut switch_losses) = (0u, 0u);
/// randomness from the operating system and use this in an
/// expensive seeding operation. If one is only generating a small
/// number of random numbers, or doesn't need the utmost speed for
- /// generating each number, `task_rng` and/or `random` may be more
+ /// generating each number, `thread_rng` and/or `random` may be more
/// appropriate.
///
/// Reading the randomness from the OS may fail, and any error is
}
}
-/// Controls how the task-local RNG is reseeded.
-struct TaskRngReseeder;
+/// Controls how the thread-local RNG is reseeded.
+struct ThreadRngReseeder;
-impl reseeding::Reseeder<StdRng> for TaskRngReseeder {
+impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
fn reseed(&mut self, rng: &mut StdRng) {
*rng = match StdRng::new() {
Ok(r) => r,
- Err(e) => panic!("could not reseed task_rng: {}", e)
+ Err(e) => panic!("could not reseed thread_rng: {}", e)
}
}
}
-static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
-type TaskRngInner = reseeding::ReseedingRng<StdRng, TaskRngReseeder>;
+static THREAD_RNG_RESEED_THRESHOLD: uint = 32_768;
+type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
-/// The task-local RNG.
-pub struct TaskRng {
- rng: Rc<RefCell<TaskRngInner>>,
+/// The thread-local RNG.
+pub struct ThreadRng {
+ rng: Rc<RefCell<ThreadRngInner>>,
}
-/// Retrieve the lazily-initialized task-local random number
+/// Retrieve the lazily-initialized thread-local random number
/// generator, seeded by the system. Intended to be used in method
-/// chaining style, e.g. `task_rng().gen::<int>()`.
+/// chaining style, e.g. `thread_rng().gen::<int>()`.
///
/// The RNG provided will reseed itself from the operating system
/// after generating a certain amount of randomness.
/// if the operating system random number generator is rigged to give
/// the same sequence always. If absolute consistency is required,
/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
-pub fn task_rng() -> TaskRng {
+pub fn thread_rng() -> ThreadRng {
// used to make space in TLS for a random number generator
- thread_local!(static TASK_RNG_KEY: Rc<RefCell<TaskRngInner>> = {
+ thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
let r = match StdRng::new() {
Ok(r) => r,
- Err(e) => panic!("could not initialize task_rng: {}", e)
+ Err(e) => panic!("could not initialize thread_rng: {}", e)
};
let rng = reseeding::ReseedingRng::new(r,
- TASK_RNG_RESEED_THRESHOLD,
- TaskRngReseeder);
+ THREAD_RNG_RESEED_THRESHOLD,
+ ThreadRngReseeder);
Rc::new(RefCell::new(rng))
});
- TaskRng { rng: TASK_RNG_KEY.with(|t| t.clone()) }
+ ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
}
-impl Rng for TaskRng {
+impl Rng for ThreadRng {
fn next_u32(&mut self) -> u32 {
self.rng.borrow_mut().next_u32()
}
}
}
-/// Generates a random value using the task-local random number generator.
+/// Generates a random value using the thread-local random number generator.
///
/// `random()` can generate various types of random things, and so may require
/// type hinting to generate the specific type you want.
/// ```
#[inline]
pub fn random<T: Rand>() -> T {
- task_rng().gen()
+ thread_rng().gen()
}
/// Randomly sample up to `amount` elements from an iterator.
/// # Example
///
/// ```rust
-/// use std::rand::{task_rng, sample};
+/// use std::rand::{thread_rng, sample};
///
-/// let mut rng = task_rng();
+/// let mut rng = thread_rng();
/// let sample = sample(&mut rng, range(1i, 100), 5);
/// println!("{}", sample);
/// ```
#[cfg(test)]
mod test {
use prelude::*;
- use super::{Rng, task_rng, random, SeedableRng, StdRng, sample};
+ use super::{Rng, thread_rng, random, SeedableRng, StdRng, sample};
use iter::order;
struct ConstRng { i: u64 }
#[test]
fn test_gen_range() {
- let mut r = task_rng();
+ let mut r = thread_rng();
for _ in range(0u, 1000) {
let a = r.gen_range(-3i, 42);
assert!(a >= -3 && a < 42);
#[test]
#[should_fail]
fn test_gen_range_panic_int() {
- let mut r = task_rng();
+ let mut r = thread_rng();
r.gen_range(5i, -2);
}
#[test]
#[should_fail]
fn test_gen_range_panic_uint() {
- let mut r = task_rng();
+ let mut r = thread_rng();
r.gen_range(5u, 2u);
}
#[test]
fn test_gen_f64() {
- let mut r = task_rng();
+ let mut r = thread_rng();
let a = r.gen::<f64>();
let b = r.gen::<f64>();
debug!("{}", (a, b));
#[test]
fn test_gen_weighted_bool() {
- let mut r = task_rng();
+ let mut r = thread_rng();
assert_eq!(r.gen_weighted_bool(0u), true);
assert_eq!(r.gen_weighted_bool(1u), true);
}
#[test]
fn test_gen_ascii_str() {
- let mut r = task_rng();
+ let mut r = thread_rng();
assert_eq!(r.gen_ascii_chars().take(0).count(), 0u);
assert_eq!(r.gen_ascii_chars().take(10).count(), 10u);
assert_eq!(r.gen_ascii_chars().take(16).count(), 16u);
#[test]
fn test_gen_vec() {
- let mut r = task_rng();
+ let mut r = thread_rng();
assert_eq!(r.gen_iter::<u8>().take(0).count(), 0u);
assert_eq!(r.gen_iter::<u8>().take(10).count(), 10u);
assert_eq!(r.gen_iter::<f64>().take(16).count(), 16u);
#[test]
fn test_choose() {
- let mut r = task_rng();
+ let mut r = thread_rng();
assert_eq!(r.choose(&[1i, 1, 1]).map(|&x|x), Some(1));
let v: &[int] = &[];
#[test]
fn test_shuffle() {
- let mut r = task_rng();
+ let mut r = thread_rng();
let empty: &mut [int] = &mut [];
r.shuffle(empty);
let mut one = [1i];
}
#[test]
- fn test_task_rng() {
- let mut r = task_rng();
+ fn test_thread_rng() {
+ let mut r = thread_rng();
r.gen::<int>();
let mut v = [1i, 1, 1];
r.shuffle(&mut v);
let min_val = 1i;
let max_val = 100i;
- let mut r = task_rng();
+ let mut r = thread_rng();
let vals = range(min_val, max_val).collect::<Vec<int>>();
let small_sample = sample(&mut r, vals.iter(), 5);
let large_sample = sample(&mut r, vals.iter(), vals.len() + 5);
#[test]
fn test_std_rng_seeded() {
- let s = task_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
+ let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
let mut ra: StdRng = SeedableRng::from_seed(s.as_slice());
let mut rb: StdRng = SeedableRng::from_seed(s.as_slice());
assert!(order::equals(ra.gen_ascii_chars().take(100),
#[test]
fn test_std_rng_reseed() {
- let s = task_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
+ let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
let string1 = r.gen_ascii_chars().take(100).collect::<String>();
t!("_ZN4$UP$E", "Box");
t!("_ZN8$UP$testE", "Boxtest");
t!("_ZN8$UP$test4foobE", "Boxtest::foob");
- t!("_ZN8$x20test4foobE", " test::foob");
+ t!("_ZN10$u{20}test4foobE", " test::foob");
}
#[test]
fn demangle_many_dollars() {
- t!("_ZN12test$x20test4foobE", "test test::foob");
+ t!("_ZN14test$u{20}test4foobE", "test test::foob");
t!("_ZN12test$UP$test4foobE", "testBoxtest::foob");
}
#[test]
fn demangle_windows() {
t!("ZN4testE", "test");
- t!("ZN12test$x20test4foobE", "test test::foob");
+ t!("ZN14test$u{20}test4foobE", "test test::foob");
t!("ZN12test$UP$test4foobE", "testBoxtest::foob");
}
}
mod at_exit_imp;
mod libunwind;
-/// The default error code of the rust runtime if the main task panics instead
+/// The default error code of the rust runtime if the main thread panics instead
/// of exiting cleanly.
pub const DEFAULT_ERROR_CODE: int = 101;
///
/// The procedure passed to this function will be executed as part of the
/// runtime cleanup phase. For normal rust programs, this means that it will run
-/// after all other tasks have exited.
+/// after all other threads have exited.
///
-/// The procedure is *not* executed with a local `Task` available to it, so
+/// The procedure is *not* executed with a local `Thread` available to it, so
/// primitives like logging, I/O, channels, spawning, etc, are *not* available.
/// This is meant for "bare bones" usage to clean up runtime details, this is
/// not meant as a general-purpose "let's clean everything up" function.
use rt::unwind;
use rt::unwind::Unwinder;
-/// State associated with Rust tasks.
+/// State associated with Rust threads
///
/// This structure is currently undergoing major changes, and is
/// likely to be move/be merged with a `Thread` structure.
awoken: bool, // used to prevent spurious wakeups
// This field holds the known bounds of the stack in (lo, hi) form. Not all
- // native tasks necessarily know their precise bounds, hence this is
+ // native threads necessarily know their precise bounds, hence this is
// optional.
stack_bounds: (uint, uint),
stack_guard: uint
}
-// Once a task has entered the `Armed` state it must be destroyed via `drop`,
+// Once a thread has entered the `Armed` state it must be destroyed via `drop`,
// and no other method. This state is used to track this transition.
#[deriving(PartialEq)]
enum TaskState {
}
pub struct TaskOpts {
- /// Invoke this procedure with the result of the task when it finishes.
+ /// Invoke this procedure with the result of the thread when it finishes.
pub on_exit: Option<Thunk<Result>>,
- /// A name for the task-to-be, for identification in panic messages
+ /// A name for the thread-to-be, for identification in panic messages
pub name: Option<SendStr>,
- /// The size of the stack for the spawned task
+ /// The size of the stack for the spawned thread
pub stack_size: Option<uint>,
}
-/// Indicates the manner in which a task exited.
+/// Indicates the manner in which a thread exited.
///
-/// A task that completes without panicking is considered to exit successfully.
+/// A thread that completes without panicking is considered to exit successfully.
///
/// If you wish for this result's delivery to block until all
-/// children tasks complete, recommend using a result future.
+/// children threads complete, recommend using a result future.
pub type Result = ::core::result::Result<(), Box<Any + Send>>;
-/// A handle to a blocked task. Usually this means having the Box<Task>
-/// pointer by ownership, but if the task is killable, a killer can steal it
+/// A handle to a blocked thread. Usually this means having the Box<Task>
+/// pointer by ownership, but if the thread is killable, a killer can steal it
/// at any time.
pub enum BlockedTask {
Owned(Box<Task>),
Shared(Arc<AtomicUint>),
}
-/// Per-task state related to task death, killing, panic, etc.
+/// Per-thread state related to thread death, killing, panic, etc.
pub struct Death {
pub on_exit: Option<Thunk<Result>>,
}
}
impl Task {
- /// Creates a new uninitialized task.
+ /// Creates a new uninitialized thread.
pub fn new(stack_bounds: Option<(uint, uint)>, stack_guard: Option<uint>) -> Task {
Task {
unwinder: Unwinder::new(),
})
}
- /// Consumes ownership of a task, runs some code, and returns the task back.
+ /// Consumes ownership of a thread, runs some code, and returns the thread back.
///
/// This function can be used as an emulated "try/catch" to interoperate
/// with the rust runtime at the outermost boundary. It is not possible to
/// use this function in a nested fashion (a try/catch inside of another
/// try/catch). Invoking this function is quite cheap.
///
- /// If the closure `f` succeeds, then the returned task can be used again
+ /// If the closure `f` succeeds, then the returned thread can be used again
/// for another invocation of `run`. If the closure `f` panics then `self`
/// will be internally destroyed along with all of the other associated
- /// resources of this task. The `on_exit` callback is invoked with the
+ /// resources of this thread. The `on_exit` callback is invoked with the
/// cause of panic (not returned here). This can be discovered by querying
/// `is_destroyed()`.
///
/// guaranteed to return if it panicks. Care should be taken to ensure that
/// stack references made by `f` are handled appropriately.
///
- /// It is invalid to call this function with a task that has been previously
+ /// It is invalid to call this function with a thread that has been previously
/// destroyed via a failed call to `run`.
pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> {
- assert!(!self.is_destroyed(), "cannot re-use a destroyed task");
+ assert!(!self.is_destroyed(), "cannot re-use a destroyed thread");
// First, make sure that no one else is in TLS. This does not allow
// recursive invocations of run(). If there's no one else, then
// relinquish ownership of ourselves back into TLS.
if Local::exists(None::<Task>) {
- panic!("cannot run a task recursively inside another");
+ panic!("cannot run a thread recursively inside another");
}
self.state = Armed;
Local::put(self);
// There are two primary reasons that general try/catch is unsafe. The
// first is that we do not support nested try/catch. The above check for
- // an existing task in TLS is sufficient for this invariant to be
+ // an existing thread in TLS is sufficient for this invariant to be
// upheld. The second is that unwinding while unwinding is not defined.
- // We take care of that by having an 'unwinding' flag in the task
+ // We take care of that by having an 'unwinding' flag in the thread
// itself. For these reasons, this unsafety should be ok.
let result = unsafe { unwind::try(f) };
- // After running the closure given return the task back out if it ran
- // successfully, or clean up the task if it panicked.
+ // After running the closure given return the thread back out if it ran
+ // successfully, or clean up the thread if it panicked.
let task: Box<Task> = Local::take();
match result {
Ok(()) => task,
}
}
- /// Destroy all associated resources of this task.
+ /// Destroy all associated resources of this thread.
///
- /// This function will perform any necessary clean up to prepare the task
+ /// This function will perform any necessary clean up to prepare the thread
/// for destruction. It is required that this is called before a `Task`
/// falls out of scope.
///
- /// The returned task cannot be used for running any more code, but it may
+ /// The returned thread cannot be used for running any more code, but it may
/// be used to extract the runtime as necessary.
pub fn destroy(self: Box<Task>) -> Box<Task> {
if self.is_destroyed() {
}
}
- /// Cleans up a task, processing the result of the task as appropriate.
+ /// Cleans up a thread, processing the result of the thread as appropriate.
///
- /// This function consumes ownership of the task, deallocating it once it's
+ /// This function consumes ownership of the thread, deallocating it once it's
/// done being processed. It is assumed that TLD and the local heap have
/// already been destroyed and/or annihilated.
fn cleanup(mut self: Box<Task>, result: Result) -> Box<Task> {
// After taking care of the data above, we need to transmit the result
- // of this task.
+ // of this thread.
let what_to_do = self.death.on_exit.take();
Local::put(self);
// if this panics, this will also likely abort the runtime.
//
// This closure is currently limited to a channel send via the
- // standard library's task interface, but this needs
+ // standard library's thread interface, but this needs
// reconsideration to whether it's a reasonable thing to let a
- // task to do or not.
+ // thread to do or not.
match what_to_do {
Some(f) => { f.invoke(result) }
None => { drop(result) }
}
- // Now that we're done, we remove the task from TLS and flag it for
+ // Now that we're done, we remove the thread from TLS and flag it for
// destruction.
let mut task: Box<Task> = Local::take();
task.state = Destroyed;
/// Queries whether this can be destroyed or not.
pub fn is_destroyed(&self) -> bool { self.state == Destroyed }
- /// Deschedules the current task, invoking `f` `amt` times. It is not
+ /// Deschedules the current thread, invoking `f` `amt` times. It is not
/// recommended to use this function directly, but rather communication
/// primitives in `std::comm` should be used.
//
// shared state. Additionally, all of the violations are protected with a
// mutex, so in theory there are no races.
//
- // The first thing we need to do is to get a pointer to the task's internal
- // mutex. This address will not be changing (because the task is allocated
- // on the heap). We must have this handle separately because the task will
+ // The first thing we need to do is to get a pointer to the thread's internal
+ // mutex. This address will not be changing (because the thread is allocated
+ // on the heap). We must have this handle separately because the thread will
// have its ownership transferred to the given closure. We're guaranteed,
// however, that this memory will remain valid because *this* is the current
- // task's execution thread.
+ // thread's execution thread.
//
- // The next weird part is where ownership of the task actually goes. We
+ // The next weird part is where ownership of the thread actually goes. We
// relinquish it to the `f` blocking function, but upon returning this
- // function needs to replace the task back in TLS. There is no communication
- // from the wakeup thread back to this thread about the task pointer, and
- // there's really no need to. In order to get around this, we cast the task
+ // function needs to replace the thread back in TLS. There is no communication
+ // from the wakeup thread back to this thread about the thread pointer, and
+ // there's really no need to. In order to get around this, we cast the thread
// to a `uint` which is then used at the end of this function to cast back
// to a `Box<Task>` object. Naturally, this looks like it violates
// ownership semantics in that there may be two `Box<Task>` objects.
//
// The fun part is that the wakeup half of this implementation knows to
- // "forget" the task on the other end. This means that the awakening half of
+ // "forget" the thread on the other end. This means that the awakening half of
// things silently relinquishes ownership back to this thread, but not in a
- // way that the compiler can understand. The task's memory is always valid
- // for both tasks because these operations are all done inside of a mutex.
+ // way that the compiler can understand. The thread's memory is always valid
+ // for both threads because these operations are all done inside of a mutex.
//
// You'll also find that if blocking fails (the `f` function hands the
// BlockedTask back to us), we will `mem::forget` the handles. The
- // reasoning for this is the same logic as above in that the task silently
+ // reasoning for this is the same logic as above in that the thread silently
// transfers ownership via the `uint`, not through normal compiler
// semantics.
//
let guard = (*me).lock.lock();
(*me).awoken = false;
- // Apply the given closure to all of the "selectable tasks",
+ // Apply the given closure to all of the "selectable threads",
// bailing on the first one that produces an error. Note that
// care must be taken such that when an error is occurred, we
- // may not own the task, so we may still have to wait for the
- // task to become available. In other words, if task.wake()
+ // may not own the thread, so we may still have to wait for the
+ // thread to become available. In other words, if thread.wake()
// returns `None`, then someone else has ownership and we must
// wait for their signal.
match iter.map(f).filter_map(|a| a.err()).next() {
guard.wait();
}
}
- // put the task back in TLS, and everything is as it once was.
+ // put the thread back in TLS, and everything is as it once was.
Local::put(mem::transmute(me));
}
}
- /// Wakes up a previously blocked task. This function can only be
- /// called on tasks that were previously blocked in `deschedule`.
+ /// Wakes up a previously blocked thread. This function can only be
+ /// called on threads that were previously blocked in `deschedule`.
//
- // See the comments on `deschedule` for why the task is forgotten here, and
+ // See the comments on `deschedule` for why the thread is forgotten here, and
// why it's valid to do so.
pub fn reawaken(mut self: Box<Task>) {
unsafe {
}
}
- /// Yields control of this task to another task. This function will
+ /// Yields control of this thread to another thread. This function will
/// eventually return, but possibly not immediately. This is used as an
- /// opportunity to allow other tasks a chance to run.
+ /// opportunity to allow other threads a chance to run.
pub fn yield_now() {
Thread::yield_now();
}
- /// Returns the stack bounds for this task in (lo, hi) format. The stack
- /// bounds may not be known for all tasks, so the return value may be
+ /// Returns the stack bounds for this thread in (lo, hi) format. The stack
+ /// bounds may not be known for all threads, so the return value may be
/// `None`.
pub fn stack_bounds(&self) -> (uint, uint) {
self.stack_bounds
}
- /// Returns the stack guard for this task, if known.
+ /// Returns the stack guard for this thread, if known.
pub fn stack_guard(&self) -> Option<uint> {
if self.stack_guard != 0 {
Some(self.stack_guard)
}
}
- /// Consume this task, flagging it as a candidate for destruction.
+ /// Consume this thread, flagging it as a candidate for destruction.
///
- /// This function is required to be invoked to destroy a task. A task
+ /// This function is required to be invoked to destroy a thread. A thread
/// destroyed through a normal drop will abort.
pub fn drop(mut self) {
self.state = Destroyed;
impl Drop for Task {
fn drop(&mut self) {
- rtdebug!("called drop for a task: {}", self as *mut Task as uint);
+ rtdebug!("called drop for a thread: {}", self as *mut Task as uint);
rtassert!(self.state != Armed);
}
}
}
impl BlockedTask {
- /// Returns Some if the task was successfully woken; None if already killed.
+ /// Returns Some if the thread was successfully woken; None if already killed.
pub fn wake(self) -> Option<Box<Task>> {
match self {
Owned(task) => Some(task),
}
}
- /// Reawakens this task if ownership is acquired. If finer-grained control
+ /// Reawakens this thread if ownership is acquired. If finer-grained control
/// is desired, use `wake` instead.
pub fn reawaken(self) {
self.wake().map(|t| t.reawaken());
#[cfg(not(test))] pub fn trash(self) { }
#[cfg(test)] pub fn trash(self) { assert!(self.wake().is_none()); }
- /// Create a blocked task, unless the task was already killed.
+ /// Create a blocked thread, unless the thread was already killed.
pub fn block(task: Box<Task>) -> BlockedTask {
Owned(task)
}
- /// Converts one blocked task handle to a list of many handles to the same.
+ /// Converts one blocked thread handle to a list of many handles to the same.
pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> {
let arc = match self {
Owned(task) => {
drop(Task::new(None, None));
}
- // Task blocking tests
+ // Thread blocking tests
#[test]
fn block_and_wake() {
pub type Callback = fn(msg: &(Any + Send), file: &'static str, line: uint);
-// Variables used for invoking callbacks when a task starts to unwind.
+// Variables used for invoking callbacks when a thread starts to unwind.
//
// For more information, see below.
const MAX_CALLBACKS: uint = 16;
///
/// * This is not safe to call in a nested fashion. The unwinding
/// interface for Rust is designed to have at most one try/catch block per
-/// task, not multiple. No runtime checking is currently performed to uphold
+/// thread, not multiple. No runtime checking is currently performed to uphold
/// this invariant, so this function is not safe. A nested try/catch block
/// may result in corruption of the outer try/catch block's state, especially
-/// if this is used within a task itself.
+/// if this is used within a thread itself.
///
-/// * It is not sound to trigger unwinding while already unwinding. Rust tasks
+/// * It is not sound to trigger unwinding while already unwinding. Rust threads
/// have runtime checks in place to ensure this invariant, but it is not
-/// guaranteed that a rust task is in place when invoking this function.
+/// guaranteed that a rust thread is in place when invoking this function.
/// Unwinding twice can lead to resource leaks where some destructors are not
/// run.
pub unsafe fn try<F: FnOnce()>(f: F) -> Result<(), Box<Any + Send>> {
// _URC_INSTALL_CONTEXT (i.e. "invoke cleanup code") in cleanup phase.
//
// This is pretty close to Rust's exception handling approach, except that Rust
-// does have a single "catch-all" handler at the bottom of each task's stack.
+// does have a single "catch-all" handler at the bottom of each thread's stack.
// So we have two versions of the personality routine:
// - rust_eh_personality, used by all cleanup landing pads, which never catches,
// so the behavior of __gcc_personality_v0 is perfectly adequate there, and
// Currently this means that panic!() on OOM will invoke this code path,
// but then again we're not really ready for panic on OOM anyway. If
// we do start doing this, then we should propagate this allocation to
- // be performed in the parent of this task instead of the task that's
+ // be performed in the parent of this thread instead of the thread that's
// panicking.
// see below for why we do the `Any` coercion here.
static INIT: Once = ONCE_INIT;
INIT.doit(|| unsafe { register(failure::on_fail); });
- // First, invoke call the user-defined callbacks triggered on task panic.
+ // First, invoke call the user-defined callbacks triggered on thread panic.
//
// By the time that we see a callback has been registered (by reading
// MAX_CALLBACKS), the actual callback itself may have not been stored yet,
// If a thread panics while it's already unwinding then we
// have limited options. Currently our preference is to
// just abort. In the future we may consider resuming
- // unwinding or otherwise exiting the task cleanly.
+ // unwinding or otherwise exiting the thread cleanly.
rterrln!("thread panicked while panicking. aborting.");
unsafe { intrinsics::abort() }
}
rust_panic(msg);
}
-/// Register a callback to be invoked when a task unwinds.
+/// Register a callback to be invoked when a thread unwinds.
///
/// This is an unsafe and experimental API which allows for an arbitrary
-/// callback to be invoked when a task panics. This callback is invoked on both
+/// callback to be invoked when a thread panics. This callback is invoked on both
/// the initial unwinding and a double unwinding if one occurs. Additionally,
/// the local `Task` will be in place for the duration of the callback, and
/// the callback must ensure that it remains in place once the callback returns.
#[cfg(test)]
mod test {
- use prelude::*;
+ use prelude::{Some, None};
use super::*;
#[test]
/// Barriers are re-usable after all threads have rendezvoused once, and can
/// be used continuously.
pub fn wait(&self) {
- let mut lock = self.lock.lock();
+ let mut lock = self.lock.lock().unwrap();
let local_gen = lock.generation_id;
lock.count += 1;
if lock.count < self.num_threads {
// http://en.wikipedia.org/wiki/Spurious_wakeup
while local_gen == lock.generation_id &&
lock.count < self.num_threads {
- self.cvar.wait(&lock);
+ lock = self.cvar.wait(lock).unwrap();
}
} else {
lock.count = 0;
use prelude::*;
use sync::atomic::{mod, AtomicUint};
-use sync::{mutex, StaticMutexGuard};
+use sync::poison::{mod, LockResult};
use sys_common::condvar as sys;
use sys_common::mutex as sys_mutex;
use time::Duration;
+use sync::{mutex, MutexGuard};
/// A Condition Variable
///
/// // Inside of our lock, spawn a new thread, and then wait for it to start
/// Thread::spawn(move|| {
/// let &(ref lock, ref cvar) = &*pair2;
-/// let mut started = lock.lock();
+/// let mut started = lock.lock().unwrap();
/// *started = true;
/// cvar.notify_one();
/// }).detach();
///
/// // wait for the thread to start up
/// let &(ref lock, ref cvar) = &*pair;
-/// let started = lock.lock();
+/// let mut started = lock.lock().unwrap();
/// while !*started {
-/// cvar.wait(&started);
+/// started = cvar.wait(started).unwrap();
/// }
/// ```
+#[stable]
pub struct Condvar { inner: Box<StaticCondvar> }
unsafe impl Send for Condvar {}
///
/// static CVAR: StaticCondvar = CONDVAR_INIT;
/// ```
+#[unstable = "may be merged with Condvar in the future"]
pub struct StaticCondvar {
inner: sys::Condvar,
mutex: AtomicUint,
unsafe impl Sync for StaticCondvar {}
/// Constant initializer for a statically allocated condition variable.
+#[unstable = "may be merged with Condvar in the future"]
pub const CONDVAR_INIT: StaticCondvar = StaticCondvar {
inner: sys::CONDVAR_INIT,
mutex: atomic::INIT_ATOMIC_UINT,
};
-/// A trait for vaules which can be passed to the waiting methods of condition
-/// variables. This is implemented by the mutex guards in this module.
-///
-/// Note that this trait should likely not be implemented manually unless you
-/// really know what you're doing.
-pub trait AsMutexGuard {
- #[allow(missing_docs)]
- unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard;
-}
-
impl Condvar {
/// Creates a new condition variable which is ready to be waited on and
/// notified.
+ #[stable]
pub fn new() -> Condvar {
Condvar {
inner: box StaticCondvar {
/// notification.
///
/// This function will atomically unlock the mutex specified (represented by
- /// `guard`) and block the current thread. This means that any calls to
- /// `notify_*()` which happen logically after the mutex is unlocked are
+ /// `mutex_guard`) and block the current thread. This means that any calls
+ /// to `notify_*()` which happen logically after the mutex is unlocked are
/// candidates to wake this thread up. When this function call returns, the
/// lock specified will have been re-acquired.
///
/// the predicate must always be checked each time this function returns to
/// protect against spurious wakeups.
///
+ /// # Failure
+ ///
+ /// This function will return an error if the mutex being waited on is
+ /// poisoned when this thread re-acquires the lock. For more information,
+ /// see information about poisoning on the Mutex type.
+ ///
/// # Panics
///
/// This function will `panic!()` if it is used with more than one mutex
/// over time. Each condition variable is dynamically bound to exactly one
/// mutex to ensure defined behavior across platforms. If this functionality
/// is not desired, then unsafe primitives in `sys` are provided.
- pub fn wait<T: AsMutexGuard>(&self, mutex_guard: &T) {
+ #[stable]
+ pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
+ -> LockResult<MutexGuard<'a, T>> {
unsafe {
let me: &'static Condvar = &*(self as *const _);
- me.inner.wait(mutex_guard)
+ me.inner.wait(guard)
}
}
// provide. There are also additional concerns about the unix-specific
// implementation which may need to be addressed.
#[allow(dead_code)]
- fn wait_timeout<T: AsMutexGuard>(&self, mutex_guard: &T,
- dur: Duration) -> bool {
+ fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>, dur: Duration)
+ -> LockResult<(MutexGuard<'a, T>, bool)> {
unsafe {
let me: &'static Condvar = &*(self as *const _);
- me.inner.wait_timeout(mutex_guard, dur)
+ me.inner.wait_timeout(guard, dur)
}
}
/// `notify_one` are not buffered in any way.
///
/// To wake up all threads, see `notify_one()`.
+ #[stable]
pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } }
/// Wake up all blocked threads on this condvar.
/// way.
///
/// To wake up only one thread, see `notify_one()`.
+ #[stable]
pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } }
}
/// notification.
///
/// See `Condvar::wait`.
- pub fn wait<T: AsMutexGuard>(&'static self, mutex_guard: &T) {
- unsafe {
- let lock = mutex_guard.as_mutex_guard();
- let sys = mutex::guard_lock(lock);
- self.verify(sys);
- self.inner.wait(sys);
- (*mutex::guard_poison(lock)).check("mutex");
+ #[unstable = "may be merged with Condvar in the future"]
+ pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
+ -> LockResult<MutexGuard<'a, T>> {
+ let poisoned = unsafe {
+ let lock = mutex::guard_lock(&guard);
+ self.verify(lock);
+ self.inner.wait(lock);
+ mutex::guard_poison(&guard).get()
+ };
+ if poisoned {
+ Err(poison::new_poison_error(guard))
+ } else {
+ Ok(guard)
}
}
///
/// See `Condvar::wait_timeout`.
#[allow(dead_code)] // may want to stabilize this later, see wait_timeout above
- fn wait_timeout<T: AsMutexGuard>(&'static self, mutex_guard: &T,
- dur: Duration) -> bool {
- unsafe {
- let lock = mutex_guard.as_mutex_guard();
- let sys = mutex::guard_lock(lock);
- self.verify(sys);
- let ret = self.inner.wait_timeout(sys, dur);
- (*mutex::guard_poison(lock)).check("mutex");
- return ret;
+ fn wait_timeout<'a, T>(&'static self, guard: MutexGuard<'a, T>, dur: Duration)
+ -> LockResult<(MutexGuard<'a, T>, bool)> {
+ let (poisoned, success) = unsafe {
+ let lock = mutex::guard_lock(&guard);
+ self.verify(lock);
+ let success = self.inner.wait_timeout(lock, dur);
+ (mutex::guard_poison(&guard).get(), success)
+ };
+ if poisoned {
+ Err(poison::new_poison_error((guard, success)))
+ } else {
+ Ok((guard, success))
}
}
/// Wake up one blocked thread on this condvar.
///
/// See `Condvar::notify_one`.
+ #[unstable = "may be merged with Condvar in the future"]
pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
/// Wake up all blocked threads on this condvar.
///
/// See `Condvar::notify_all`.
+ #[unstable = "may be merged with Condvar in the future"]
pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
/// Deallocate all resources associated with this static condvar.
/// active users of the condvar, and this also doesn't prevent any future
/// users of the condvar. This method is required to be called to not leak
/// memory on all platforms.
+ #[unstable = "may be merged with Condvar in the future"]
pub unsafe fn destroy(&'static self) {
self.inner.destroy()
}
static C: StaticCondvar = CONDVAR_INIT;
static M: StaticMutex = MUTEX_INIT;
- let g = M.lock();
+ let g = M.lock().unwrap();
spawn(move|| {
- let _g = M.lock();
+ let _g = M.lock().unwrap();
C.notify_one();
});
- C.wait(&g);
+ let g = C.wait(g).unwrap();
drop(g);
unsafe { C.destroy(); M.destroy(); }
}
let tx = tx.clone();
spawn(move|| {
let &(ref lock, ref cond) = &*data;
- let mut cnt = lock.lock();
+ let mut cnt = lock.lock().unwrap();
*cnt += 1;
if *cnt == N {
tx.send(());
}
while *cnt != 0 {
- cond.wait(&cnt);
+ cnt = cond.wait(cnt).unwrap();
}
tx.send(());
});
let &(ref lock, ref cond) = &*data;
rx.recv();
- let mut cnt = lock.lock();
+ let mut cnt = lock.lock().unwrap();
*cnt = 0;
cond.notify_all();
drop(cnt);
static C: StaticCondvar = CONDVAR_INIT;
static M: StaticMutex = MUTEX_INIT;
- let g = M.lock();
- assert!(!C.wait_timeout(&g, Duration::nanoseconds(1000)));
+ let g = M.lock().unwrap();
+ let (g, success) = C.wait_timeout(g, Duration::nanoseconds(1000)).unwrap();
+ assert!(!success);
spawn(move|| {
- let _g = M.lock();
+ let _g = M.lock().unwrap();
C.notify_one();
});
- assert!(C.wait_timeout(&g, Duration::days(1)));
+ let (g, success) = C.wait_timeout(g, Duration::days(1)).unwrap();
+ assert!(success);
drop(g);
unsafe { C.destroy(); M.destroy(); }
}
static M2: StaticMutex = MUTEX_INIT;
static C: StaticCondvar = CONDVAR_INIT;
- let g = M1.lock();
+ let mut g = M1.lock().unwrap();
spawn(move|| {
- let _g = M1.lock();
+ let _g = M1.lock().unwrap();
C.notify_one();
});
- C.wait(&g);
+ g = C.wait(g).unwrap();
drop(g);
- C.wait(&M2.lock());
+ C.wait(M2.lock().unwrap()).unwrap();
}
}
pub use alloc::arc::{Arc, Weak};
-pub use self::mutex::{Mutex, MutexGuard, StaticMutex, StaticMutexGuard, MUTEX_INIT};
+pub use self::mutex::{Mutex, MutexGuard, StaticMutex};
+pub use self::mutex::MUTEX_INIT;
pub use self::rwlock::{RWLock, StaticRWLock, RWLOCK_INIT};
pub use self::rwlock::{RWLockReadGuard, RWLockWriteGuard};
-pub use self::rwlock::{StaticRWLockReadGuard, StaticRWLockWriteGuard};
-pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT, AsMutexGuard};
+pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT};
pub use self::once::{Once, ONCE_INIT};
pub use self::semaphore::{Semaphore, SemaphoreGuard};
pub use self::barrier::Barrier;
+pub use self::poison::{PoisonError, TryLockError, TryLockResult, LockResult};
pub use self::future::Future;
pub use self::task_pool::TaskPool;
use cell::UnsafeCell;
use kinds::marker;
-use sync::{poison, AsMutexGuard};
+use sync::poison::{mod, TryLockError, TryLockResult, LockResult};
use sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
/// # Poisoning
///
-/// In order to prevent access to otherwise invalid data, each mutex will
-/// propagate any panics which occur while the lock is held. Once a thread has
-/// panicked while holding the lock, then all other threads will immediately
-/// panic as well once they hold the lock.
+/// The mutexes in this module implement a strategy called "poisoning" where a
+/// mutex is considered poisoned whenever a thread panics while holding the
+/// lock. Once a mutex is poisoned, all other tasks are unable to access the
+/// data by default as it is likely tainted (some invariant is not being
+/// upheld).
///
-/// # Example
+/// For a mutex, this means that the `lock` and `try_lock` methods return a
+/// `Result` which indicates whether a mutex has been poisoned or not. Most
+/// usage of a mutex will simply `unwrap()` these results, propagating panics
+/// among threads to ensure that a possibly invalid invariant is not witnessed.
+///
+/// A poisoned mutex, however, does not prevent all access to the underlying
+/// data. The `PoisonError` type has an `into_guard` method which will return
+/// the guard that would have otherwise been returned on a successful lock. This
+/// allows access to the data, despite the lock being poisoned.
+///
+/// # Examples
///
/// ```rust
/// use std::sync::{Arc, Mutex};
/// let (tx, rx) = channel();
/// for _ in range(0u, 10) {
/// let (data, tx) = (data.clone(), tx.clone());
-/// Thread::spawn(move|| {
+/// Thread::spawn(move || {
/// // The shared static can only be accessed once the lock is held.
/// // Our non-atomic increment is safe because we're the only thread
/// // which can access the shared state when the lock is held.
-/// let mut data = data.lock();
+/// //
+/// // We unwrap() the return value to assert that we are not expecting
+/// // tasks to ever fail while holding the lock.
+/// let mut data = data.lock().unwrap();
/// *data += 1;
/// if *data == N {
/// tx.send(());
///
/// rx.recv();
/// ```
+///
+/// To recover from a poisoned mutex:
+///
+/// ```rust
+/// use std::sync::{Arc, Mutex};
+/// use std::thread::Thread;
+///
+/// let lock = Arc::new(Mutex::new(0u));
+/// let lock2 = lock.clone();
+///
+/// let _ = Thread::spawn(move || -> () {
+/// // This thread will acquire the mutex first, unwrapping the result of
+/// // `lock` because the lock has not been poisoned.
+/// let _lock = lock2.lock().unwrap();
+///
+/// // This panic while holding the lock (`_guard` is in scope) will poison
+/// // the mutex.
+/// panic!();
+/// }).join();
+///
+/// // The lock is poisoned by this point, but the returned result can be
+/// // pattern matched on to return the underlying guard on both branches.
+/// let mut guard = match lock.lock() {
+/// Ok(guard) => guard,
+/// Err(poisoned) => poisoned.into_guard(),
+/// };
+///
+/// *guard += 1;
+/// ```
+#[stable]
pub struct Mutex<T> {
// Note that this static mutex is in a *box*, not inlined into the struct
// itself. Once a native mutex has been used once, its address can never
/// static LOCK: StaticMutex = MUTEX_INIT;
///
/// {
-/// let _g = LOCK.lock();
+/// let _g = LOCK.lock().unwrap();
/// // do some productive work
/// }
/// // lock is unlocked here.
/// ```
+#[unstable = "may be merged with Mutex in the future"]
pub struct StaticMutex {
lock: sys::Mutex,
- poison: UnsafeCell<poison::Flag>,
+ poison: poison::Flag,
}
unsafe impl Sync for StaticMutex {}
/// The data protected by the mutex can be access through this guard via its
/// Deref and DerefMut implementations
#[must_use]
+#[stable]
pub struct MutexGuard<'a, T: 'a> {
// funny underscores due to how Deref/DerefMut currently work (they
// disregard field privacy).
- __lock: &'a Mutex<T>,
- __guard: StaticMutexGuard,
-}
-
-/// An RAII implementation of a "scoped lock" of a static mutex. When this
-/// structure is dropped (falls out of scope), the lock will be unlocked.
-#[must_use]
-pub struct StaticMutexGuard {
- lock: &'static sys::Mutex,
- marker: marker::NoSend,
- poison: poison::Guard<'static>,
+ __lock: &'a StaticMutex,
+ __data: &'a UnsafeCell<T>,
+ __poison: poison::Guard,
+ __marker: marker::NoSend,
}
/// Static initialization of a mutex. This constant can be used to initialize
/// other mutex constants.
+#[unstable = "may be merged with Mutex in the future"]
pub const MUTEX_INIT: StaticMutex = StaticMutex {
lock: sys::MUTEX_INIT,
- poison: UnsafeCell { value: poison::Flag { failed: false } },
+ poison: poison::FLAG_INIT,
};
impl<T: Send> Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
+ #[stable]
pub fn new(t: T) -> Mutex<T> {
Mutex {
inner: box MUTEX_INIT,
/// held. An RAII guard is returned to allow scoped unlock of the lock. When
/// the guard goes out of scope, the mutex will be unlocked.
///
- /// # Panics
+ /// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
- /// this call will immediately panic once the mutex is acquired.
- pub fn lock(&self) -> MutexGuard<T> {
- unsafe {
- let lock: &'static StaticMutex = &*(&*self.inner as *const _);
- MutexGuard::new(self, lock.lock())
- }
+ /// this call will return an error once the mutex is acquired.
+ #[stable]
+ pub fn lock(&self) -> LockResult<MutexGuard<T>> {
+ unsafe { self.inner.lock.lock() }
+ MutexGuard::new(&*self.inner, &self.data)
}
/// Attempts to acquire this lock.
///
/// This function does not block.
///
- /// # Panics
+ /// # Failure
///
/// If another user of this mutex panicked while holding the mutex, then
- /// this call will immediately panic if the mutex would otherwise be
+ /// this call will return failure if the mutex would otherwise be
/// acquired.
- pub fn try_lock(&self) -> Option<MutexGuard<T>> {
- unsafe {
- let lock: &'static StaticMutex = &*(&*self.inner as *const _);
- lock.try_lock().map(|guard| {
- MutexGuard::new(self, guard)
- })
+ #[stable]
+ pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
+ if unsafe { self.inner.lock.try_lock() } {
+ Ok(try!(MutexGuard::new(&*self.inner, &self.data)))
+ } else {
+ Err(TryLockError::WouldBlock)
}
}
}
}
}
+struct Dummy(UnsafeCell<()>);
+unsafe impl Sync for Dummy {}
+static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
+
impl StaticMutex {
/// Acquires this lock, see `Mutex::lock`
- pub fn lock(&'static self) -> StaticMutexGuard {
+ #[inline]
+ #[unstable = "may be merged with Mutex in the future"]
+ pub fn lock(&'static self) -> LockResult<MutexGuard<()>> {
unsafe { self.lock.lock() }
- StaticMutexGuard::new(self)
+ MutexGuard::new(self, &DUMMY.0)
}
/// Attempts to grab this lock, see `Mutex::try_lock`
- pub fn try_lock(&'static self) -> Option<StaticMutexGuard> {
+ #[inline]
+ #[unstable = "may be merged with Mutex in the future"]
+ pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> {
if unsafe { self.lock.try_lock() } {
- Some(StaticMutexGuard::new(self))
+ Ok(try!(MutexGuard::new(self, &DUMMY.0)))
} else {
- None
+ Err(TryLockError::WouldBlock)
}
}
/// *all* platforms. It may be the case that some platforms do not leak
/// memory if this method is not called, but this is not guaranteed to be
/// true on all platforms.
+ #[unstable = "may be merged with Mutex in the future"]
pub unsafe fn destroy(&'static self) {
self.lock.destroy()
}
}
impl<'mutex, T> MutexGuard<'mutex, T> {
- fn new(lock: &Mutex<T>, guard: StaticMutexGuard) -> MutexGuard<T> {
- MutexGuard { __lock: lock, __guard: guard }
+ fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>)
+ -> LockResult<MutexGuard<'mutex, T>> {
+ poison::map_result(lock.poison.borrow(), |guard| {
+ MutexGuard {
+ __lock: lock,
+ __data: data,
+ __poison: guard,
+ __marker: marker::NoSend,
+ }
+ })
}
}
-impl<'mutex, T> AsMutexGuard for MutexGuard<'mutex, T> {
- unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { &self.__guard }
-}
-
impl<'mutex, T> Deref<T> for MutexGuard<'mutex, T> {
- fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.__lock.data.get() } }
+ fn deref<'a>(&'a self) -> &'a T {
+ unsafe { &*self.__data.get() }
+ }
}
impl<'mutex, T> DerefMut<T> for MutexGuard<'mutex, T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
- unsafe { &mut *self.__lock.data.get() }
+ unsafe { &mut *self.__data.get() }
}
}
-impl StaticMutexGuard {
- fn new(lock: &'static StaticMutex) -> StaticMutexGuard {
+#[unsafe_destructor]
+impl<'a, T> Drop for MutexGuard<'a, T> {
+ #[inline]
+ fn drop(&mut self) {
unsafe {
- let guard = StaticMutexGuard {
- lock: &lock.lock,
- marker: marker::NoSend,
- poison: (*lock.poison.get()).borrow(),
- };
- guard.poison.check("mutex");
- return guard;
+ self.__lock.poison.done(&self.__poison);
+ self.__lock.lock.unlock();
}
}
}
-pub fn guard_lock(guard: &StaticMutexGuard) -> &sys::Mutex { guard.lock }
-pub fn guard_poison(guard: &StaticMutexGuard) -> &poison::Guard {
- &guard.poison
+pub fn guard_lock<'a, T>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
+ &guard.__lock.lock
}
-impl AsMutexGuard for StaticMutexGuard {
- unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { self }
-}
-
-#[unsafe_destructor]
-impl Drop for StaticMutexGuard {
- fn drop(&mut self) {
- unsafe {
- self.poison.done();
- self.lock.unlock();
- }
- }
+pub fn guard_poison<'a, T>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
+ &guard.__lock.poison
}
#[cfg(test)]
#[test]
fn smoke() {
let m = Mutex::new(());
- drop(m.lock());
- drop(m.lock());
+ drop(m.lock().unwrap());
+ drop(m.lock().unwrap());
}
#[test]
fn smoke_static() {
static M: StaticMutex = MUTEX_INIT;
unsafe {
- drop(M.lock());
- drop(M.lock());
+ drop(M.lock().unwrap());
+ drop(M.lock().unwrap());
M.destroy();
}
}
fn inc() {
for _ in range(0, J) {
unsafe {
- let _g = M.lock();
+ let _g = M.lock().unwrap();
CNT += 1;
}
}
#[test]
fn try_lock() {
let m = Mutex::new(());
- assert!(m.try_lock().is_some());
+ *m.try_lock().unwrap() = ();
}
#[test]
// wait until parent gets in
rx.recv();
let &(ref lock, ref cvar) = &*packet2.0;
- let mut lock = lock.lock();
+ let mut lock = lock.lock().unwrap();
*lock = true;
cvar.notify_one();
});
let &(ref lock, ref cvar) = &*packet.0;
- let lock = lock.lock();
+ let mut lock = lock.lock().unwrap();
tx.send(());
assert!(!*lock);
while !*lock {
- cvar.wait(&lock);
+ lock = cvar.wait(lock).unwrap();
}
}
#[test]
- #[should_fail]
fn test_arc_condvar_poison() {
let packet = Packet(Arc::new((Mutex::new(1i), Condvar::new())));
let packet2 = Packet(packet.0.clone());
spawn(move|| {
rx.recv();
let &(ref lock, ref cvar) = &*packet2.0;
- let _g = lock.lock();
+ let _g = lock.lock().unwrap();
cvar.notify_one();
// Parent should fail when it wakes up.
panic!();
});
let &(ref lock, ref cvar) = &*packet.0;
- let lock = lock.lock();
+ let mut lock = lock.lock().unwrap();
tx.send(());
while *lock == 1 {
- cvar.wait(&lock);
+ match cvar.wait(lock) {
+ Ok(l) => {
+ lock = l;
+ assert_eq!(*lock, 1);
+ }
+ Err(..) => break,
+ }
}
}
#[test]
- #[should_fail]
fn test_mutex_arc_poison() {
let arc = Arc::new(Mutex::new(1i));
let arc2 = arc.clone();
- let _ = Thread::spawn(move|| {
- let lock = arc2.lock();
+ Thread::spawn(move|| {
+ let lock = arc2.lock().unwrap();
assert_eq!(*lock, 2);
}).join();
- let lock = arc.lock();
- assert_eq!(*lock, 1);
+ assert!(arc.lock().is_err());
}
#[test]
let arc2 = Arc::new(Mutex::new(arc));
let (tx, rx) = channel();
spawn(move|| {
- let lock = arc2.lock();
- let lock2 = lock.deref().lock();
+ let lock = arc2.lock().unwrap();
+ let lock2 = lock.deref().lock().unwrap();
assert_eq!(*lock2, 1);
tx.send(());
});
}
impl Drop for Unwinder {
fn drop(&mut self) {
- *self.i.lock() += 1;
+ *self.i.lock().unwrap() += 1;
}
}
let _u = Unwinder { i: arc2 };
panic!();
}).join();
- let lock = arc.lock();
+ let lock = arc.lock().unwrap();
assert_eq!(*lock, 2);
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
+use prelude::*;
+
+use cell::UnsafeCell;
+use error::FromError;
+use fmt;
use thread::Thread;
-pub struct Flag { pub failed: bool }
+pub struct Flag { failed: UnsafeCell<bool> }
+pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } };
impl Flag {
- pub fn borrow(&mut self) -> Guard {
- Guard { flag: &mut self.failed, panicking: Thread::panicking() }
+ #[inline]
+ pub fn borrow(&self) -> LockResult<Guard> {
+ let ret = Guard { panicking: Thread::panicking() };
+ if unsafe { *self.failed.get() } {
+ Err(new_poison_error(ret))
+ } else {
+ Ok(ret)
+ }
+ }
+
+ #[inline]
+ pub fn done(&self, guard: &Guard) {
+ if !guard.panicking && Thread::panicking() {
+ unsafe { *self.failed.get() = true; }
+ }
+ }
+
+ #[inline]
+ pub fn get(&self) -> bool {
+ unsafe { *self.failed.get() }
}
}
-pub struct Guard<'a> {
- flag: &'a mut bool,
+#[allow(missing_copy_implementations)]
+pub struct Guard {
panicking: bool,
}
-impl<'a> Guard<'a> {
- pub fn check(&self, name: &str) {
- if *self.flag {
- panic!("poisoned {} - another task failed inside", name);
- }
+/// A type of error which can be returned whenever a lock is acquired.
+///
+/// Both Mutexes and RWLocks are poisoned whenever a task fails while the lock
+/// is held. The precise semantics for when a lock is poisoned is documented on
+/// each lock, but once a lock is poisoned then all future acquisitions will
+/// return this error.
+#[stable]
+pub struct PoisonError<T> {
+ guard: T,
+}
+
+/// An enumeration of possible errors which can occur while calling the
+/// `try_lock` method.
+#[stable]
+pub enum TryLockError<T> {
+ /// The lock could not be acquired because another task failed while holding
+ /// the lock.
+ #[stable]
+ Poisoned(PoisonError<T>),
+ /// The lock could not be acquired at this time because the operation would
+ /// otherwise block.
+ #[stable]
+ WouldBlock,
+}
+
+/// A type alias for the result of a lock method which can be poisoned.
+///
+/// The `Ok` variant of this result indicates that the primitive was not
+/// poisoned, and the `Guard` is contained within. The `Err` variant indicates
+/// that the primitive was poisoned. Note that the `Err` variant *also* carries
+/// the associated guard, and it can be acquired through the `into_inner`
+/// method.
+#[stable]
+pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
+
+/// A type alias for the result of a nonblocking locking method.
+///
+/// For more information, see `LockResult`. A `TryLockResult` doesn't
+/// necessarily hold the associated guard in the `Err` type as the lock may not
+/// have been acquired for other reasons.
+#[stable]
+pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
+
+impl<T> fmt::Show for PoisonError<T> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ "poisoned lock: another task failed inside".fmt(f)
+ }
+}
+
+impl<T> PoisonError<T> {
+ /// Consumes this error indicating that a lock is poisoned, returning the
+ /// underlying guard to allow access regardless.
+ #[stable]
+ pub fn into_guard(self) -> T { self.guard }
+}
+
+impl<T> FromError<PoisonError<T>> for TryLockError<T> {
+ fn from_error(err: PoisonError<T>) -> TryLockError<T> {
+ TryLockError::Poisoned(err)
}
+}
- pub fn done(&mut self) {
- if !self.panicking && Thread::panicking() {
- *self.flag = true;
+impl<T> fmt::Show for TryLockError<T> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ TryLockError::Poisoned(ref p) => p.fmt(f),
+ TryLockError::WouldBlock => {
+ "try_lock failed because the operation would block".fmt(f)
+ }
}
}
}
+
+pub fn new_poison_error<T>(guard: T) -> PoisonError<T> {
+ PoisonError { guard: guard }
+}
+
+pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
+ -> LockResult<U>
+ where F: FnOnce(T) -> U {
+ match result {
+ Ok(t) => Ok(f(t)),
+ Err(PoisonError { guard }) => Err(new_poison_error(f(guard)))
+ }
+}
use prelude::*;
-use kinds::marker;
use cell::UnsafeCell;
+use kinds::marker;
+use sync::poison::{mod, LockResult, TryLockError, TryLockResult};
use sys_common::rwlock as sys;
-use sync::poison;
/// A reader-writer lock
///
/// locking methods implement `Deref` (and `DerefMut` for the `write` methods)
/// to allow access to the contained of the lock.
///
+/// # Poisoning
+///
/// RWLocks, like Mutexes, will become poisoned on panics. Note, however, that
/// an RWLock may only be poisoned if a panic occurs while it is locked
/// exclusively (write mode). If a panic occurs in any reader, then the lock
/// will not be poisoned.
///
-/// # Example
+/// # Examples
///
/// ```
/// use std::sync::RWLock;
///
/// // many reader locks can be held at once
/// {
-/// let r1 = lock.read();
-/// let r2 = lock.read();
+/// let r1 = lock.read().unwrap();
+/// let r2 = lock.read().unwrap();
/// assert_eq!(*r1, 5);
/// assert_eq!(*r2, 5);
/// } // read locks are dropped at this point
///
/// // only one write lock may be held, however
/// {
-/// let mut w = lock.write();
+/// let mut w = lock.write().unwrap();
/// *w += 1;
/// assert_eq!(*w, 6);
/// } // write lock is dropped here
/// ```
+#[stable]
pub struct RWLock<T> {
inner: Box<StaticRWLock>,
data: UnsafeCell<T>,
/// static LOCK: StaticRWLock = RWLOCK_INIT;
///
/// {
-/// let _g = LOCK.read();
+/// let _g = LOCK.read().unwrap();
/// // ... shared read access
/// }
/// {
-/// let _g = LOCK.write();
+/// let _g = LOCK.write().unwrap();
/// // ... exclusive write access
/// }
/// unsafe { LOCK.destroy() } // free all resources
/// ```
+#[unstable = "may be merged with RWLock in the future"]
pub struct StaticRWLock {
- inner: sys::RWLock,
- poison: UnsafeCell<poison::Flag>,
+ lock: sys::RWLock,
+ poison: poison::Flag,
}
unsafe impl Send for StaticRWLock {}
unsafe impl Sync for StaticRWLock {}
/// Constant initialization for a statically-initialized rwlock.
+#[unstable = "may be merged with RWLock in the future"]
pub const RWLOCK_INIT: StaticRWLock = StaticRWLock {
- inner: sys::RWLOCK_INIT,
- poison: UnsafeCell { value: poison::Flag { failed: false } },
+ lock: sys::RWLOCK_INIT,
+ poison: poison::FLAG_INIT,
};
/// RAII structure used to release the shared read access of a lock when
/// dropped.
#[must_use]
+#[stable]
pub struct RWLockReadGuard<'a, T: 'a> {
- __lock: &'a RWLock<T>,
- __guard: StaticRWLockReadGuard,
+ __lock: &'a StaticRWLock,
+ __data: &'a UnsafeCell<T>,
+ __marker: marker::NoSend,
}
/// RAII structure used to release the exclusive write access of a lock when
/// dropped.
#[must_use]
+#[stable]
pub struct RWLockWriteGuard<'a, T: 'a> {
- __lock: &'a RWLock<T>,
- __guard: StaticRWLockWriteGuard,
-}
-
-/// RAII structure used to release the shared read access of a lock when
-/// dropped.
-#[must_use]
-pub struct StaticRWLockReadGuard {
- lock: &'static sys::RWLock,
- marker: marker::NoSend,
-}
-
-/// RAII structure used to release the exclusive write access of a lock when
-/// dropped.
-#[must_use]
-pub struct StaticRWLockWriteGuard {
- lock: &'static sys::RWLock,
- marker: marker::NoSend,
- poison: poison::Guard<'static>,
+ __lock: &'a StaticRWLock,
+ __data: &'a UnsafeCell<T>,
+ __poison: poison::Guard,
+ __marker: marker::NoSend,
}
impl<T: Send + Sync> RWLock<T> {
/// Creates a new instance of an RWLock which is unlocked and read to go.
+ #[stable]
pub fn new(t: T) -> RWLock<T> {
RWLock { inner: box RWLOCK_INIT, data: UnsafeCell::new(t) }
}
/// Returns an RAII guard which will release this thread's shared access
/// once it is dropped.
///
- /// # Panics
+ /// # Failure
///
- /// This function will panic if the RWLock is poisoned. An RWLock is
- /// poisoned whenever a writer panics while holding an exclusive lock. The
- /// panic will occur immediately after the lock has been acquired.
+ /// This function will return an error if the RWLock is poisoned. An RWLock
+ /// is poisoned whenever a writer panics while holding an exclusive lock.
+ /// The failure will occur immediately after the lock has been acquired.
#[inline]
- pub fn read(&self) -> RWLockReadGuard<T> {
- unsafe {
- let lock: &'static StaticRWLock = &*(&*self.inner as *const _);
- RWLockReadGuard::new(self, lock.read())
- }
+ #[stable]
+ pub fn read(&self) -> LockResult<RWLockReadGuard<T>> {
+ unsafe { self.inner.lock.read() }
+ RWLockReadGuard::new(&*self.inner, &self.data)
}
/// Attempt to acquire this lock with shared read access.
/// guarantees with respect to the ordering of whether contentious readers
/// or writers will acquire the lock first.
///
- /// # Panics
+ /// # Failure
///
- /// This function will panic if the RWLock is poisoned. An RWLock is
- /// poisoned whenever a writer panics while holding an exclusive lock. A
- /// panic will only occur if the lock is acquired.
+ /// This function will return an error if the RWLock is poisoned. An RWLock
+ /// is poisoned whenever a writer panics while holding an exclusive lock. An
+ /// error will only be returned if the lock would have otherwise been
+ /// acquired.
#[inline]
- pub fn try_read(&self) -> Option<RWLockReadGuard<T>> {
- unsafe {
- let lock: &'static StaticRWLock = &*(&*self.inner as *const _);
- lock.try_read().map(|guard| {
- RWLockReadGuard::new(self, guard)
- })
+ #[stable]
+ pub fn try_read(&self) -> TryLockResult<RWLockReadGuard<T>> {
+ if unsafe { self.inner.lock.try_read() } {
+ Ok(try!(RWLockReadGuard::new(&*self.inner, &self.data)))
+ } else {
+ Err(TryLockError::WouldBlock)
}
}
/// Returns an RAII guard which will drop the write access of this rwlock
/// when dropped.
///
- /// # Panics
+ /// # Failure
///
- /// This function will panic if the RWLock is poisoned. An RWLock is
- /// poisoned whenever a writer panics while holding an exclusive lock. The
- /// panic will occur when the lock is acquired.
+ /// This function will return an error if the RWLock is poisoned. An RWLock
+ /// is poisoned whenever a writer panics while holding an exclusive lock.
+ /// An error will be returned when the lock is acquired.
#[inline]
- pub fn write(&self) -> RWLockWriteGuard<T> {
- unsafe {
- let lock: &'static StaticRWLock = &*(&*self.inner as *const _);
- RWLockWriteGuard::new(self, lock.write())
- }
+ #[stable]
+ pub fn write(&self) -> LockResult<RWLockWriteGuard<T>> {
+ unsafe { self.inner.lock.write() }
+ RWLockWriteGuard::new(&*self.inner, &self.data)
}
/// Attempt to lock this rwlock with exclusive write access.
/// to `write` would otherwise block. If successful, an RAII guard is
/// returned.
///
- /// # Panics
+ /// # Failure
///
- /// This function will panic if the RWLock is poisoned. An RWLock is
- /// poisoned whenever a writer panics while holding an exclusive lock. A
- /// panic will only occur if the lock is acquired.
+ /// This function will return an error if the RWLock is poisoned. An RWLock
+ /// is poisoned whenever a writer panics while holding an exclusive lock. An
+ /// error will only be returned if the lock would have otherwise been
+ /// acquired.
#[inline]
- pub fn try_write(&self) -> Option<RWLockWriteGuard<T>> {
- unsafe {
- let lock: &'static StaticRWLock = &*(&*self.inner as *const _);
- lock.try_write().map(|guard| {
- RWLockWriteGuard::new(self, guard)
- })
+ #[stable]
+ pub fn try_write(&self) -> TryLockResult<RWLockWriteGuard<T>> {
+ if unsafe { self.inner.lock.try_read() } {
+ Ok(try!(RWLockWriteGuard::new(&*self.inner, &self.data)))
+ } else {
+ Err(TryLockError::WouldBlock)
}
}
}
#[unsafe_destructor]
impl<T> Drop for RWLock<T> {
fn drop(&mut self) {
- unsafe { self.inner.inner.destroy() }
+ unsafe { self.inner.lock.destroy() }
}
}
+struct Dummy(UnsafeCell<()>);
+unsafe impl Sync for Dummy {}
+static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
+
impl StaticRWLock {
/// Locks this rwlock with shared read access, blocking the current thread
/// until it can be acquired.
///
/// See `RWLock::read`.
#[inline]
- pub fn read(&'static self) -> StaticRWLockReadGuard {
- unsafe { self.inner.read() }
- StaticRWLockReadGuard::new(self)
+ #[unstable = "may be merged with RWLock in the future"]
+ pub fn read(&'static self) -> LockResult<RWLockReadGuard<'static, ()>> {
+ unsafe { self.lock.read() }
+ RWLockReadGuard::new(self, &DUMMY.0)
}
/// Attempt to acquire this lock with shared read access.
///
/// See `RWLock::try_read`.
#[inline]
- pub fn try_read(&'static self) -> Option<StaticRWLockReadGuard> {
- if unsafe { self.inner.try_read() } {
- Some(StaticRWLockReadGuard::new(self))
+ #[unstable = "may be merged with RWLock in the future"]
+ pub fn try_read(&'static self)
+ -> TryLockResult<RWLockReadGuard<'static, ()>> {
+ if unsafe { self.lock.try_read() } {
+ Ok(try!(RWLockReadGuard::new(self, &DUMMY.0)))
} else {
- None
+ Err(TryLockError::WouldBlock)
}
}
///
/// See `RWLock::write`.
#[inline]
- pub fn write(&'static self) -> StaticRWLockWriteGuard {
- unsafe { self.inner.write() }
- StaticRWLockWriteGuard::new(self)
+ #[unstable = "may be merged with RWLock in the future"]
+ pub fn write(&'static self) -> LockResult<RWLockWriteGuard<'static, ()>> {
+ unsafe { self.lock.write() }
+ RWLockWriteGuard::new(self, &DUMMY.0)
}
/// Attempt to lock this rwlock with exclusive write access.
///
/// See `RWLock::try_write`.
#[inline]
- pub fn try_write(&'static self) -> Option<StaticRWLockWriteGuard> {
- if unsafe { self.inner.try_write() } {
- Some(StaticRWLockWriteGuard::new(self))
+ #[unstable = "may be merged with RWLock in the future"]
+ pub fn try_write(&'static self)
+ -> TryLockResult<RWLockWriteGuard<'static, ()>> {
+ if unsafe { self.lock.try_write() } {
+ Ok(try!(RWLockWriteGuard::new(self, &DUMMY.0)))
} else {
- None
+ Err(TryLockError::WouldBlock)
}
}
/// active users of the lock, and this also doesn't prevent any future users
/// of this lock. This method is required to be called to not leak memory on
/// all platforms.
+ #[unstable = "may be merged with RWLock in the future"]
pub unsafe fn destroy(&'static self) {
- self.inner.destroy()
+ self.lock.destroy()
}
}
impl<'rwlock, T> RWLockReadGuard<'rwlock, T> {
- fn new(lock: &RWLock<T>, guard: StaticRWLockReadGuard)
- -> RWLockReadGuard<T> {
- RWLockReadGuard { __lock: lock, __guard: guard }
+ fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell<T>)
+ -> LockResult<RWLockReadGuard<'rwlock, T>> {
+ poison::map_result(lock.poison.borrow(), |_| {
+ RWLockReadGuard {
+ __lock: lock,
+ __data: data,
+ __marker: marker::NoSend,
+ }
+ })
}
}
impl<'rwlock, T> RWLockWriteGuard<'rwlock, T> {
- fn new(lock: &RWLock<T>, guard: StaticRWLockWriteGuard)
- -> RWLockWriteGuard<T> {
- RWLockWriteGuard { __lock: lock, __guard: guard }
+ fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell<T>)
+ -> LockResult<RWLockWriteGuard<'rwlock, T>> {
+ poison::map_result(lock.poison.borrow(), |guard| {
+ RWLockWriteGuard {
+ __lock: lock,
+ __data: data,
+ __poison: guard,
+ __marker: marker::NoSend,
+ }
+ })
}
}
impl<'rwlock, T> Deref<T> for RWLockReadGuard<'rwlock, T> {
- fn deref(&self) -> &T { unsafe { &*self.__lock.data.get() } }
+ fn deref(&self) -> &T { unsafe { &*self.__data.get() } }
}
impl<'rwlock, T> Deref<T> for RWLockWriteGuard<'rwlock, T> {
- fn deref(&self) -> &T { unsafe { &*self.__lock.data.get() } }
+ fn deref(&self) -> &T { unsafe { &*self.__data.get() } }
}
impl<'rwlock, T> DerefMut<T> for RWLockWriteGuard<'rwlock, T> {
- fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.__lock.data.get() } }
-}
-
-impl StaticRWLockReadGuard {
- fn new(lock: &'static StaticRWLock) -> StaticRWLockReadGuard {
- let guard = StaticRWLockReadGuard {
- lock: &lock.inner,
- marker: marker::NoSend,
- };
- unsafe { (*lock.poison.get()).borrow().check("rwlock"); }
- return guard;
- }
-}
-impl StaticRWLockWriteGuard {
- fn new(lock: &'static StaticRWLock) -> StaticRWLockWriteGuard {
- unsafe {
- let guard = StaticRWLockWriteGuard {
- lock: &lock.inner,
- marker: marker::NoSend,
- poison: (*lock.poison.get()).borrow(),
- };
- guard.poison.check("rwlock");
- return guard;
- }
+ fn deref_mut(&mut self) -> &mut T {
+ unsafe { &mut *self.__data.get() }
}
}
#[unsafe_destructor]
-impl Drop for StaticRWLockReadGuard {
+impl<'a, T> Drop for RWLockReadGuard<'a, T> {
fn drop(&mut self) {
- unsafe { self.lock.read_unlock(); }
+ unsafe { self.__lock.lock.read_unlock(); }
}
}
#[unsafe_destructor]
-impl Drop for StaticRWLockWriteGuard {
+impl<'a, T> Drop for RWLockWriteGuard<'a, T> {
fn drop(&mut self) {
- self.poison.done();
- unsafe { self.lock.write_unlock(); }
+ self.__lock.poison.done(&self.__poison);
+ unsafe { self.__lock.lock.write_unlock(); }
}
}
#[test]
fn smoke() {
let l = RWLock::new(());
- drop(l.read());
- drop(l.write());
- drop((l.read(), l.read()));
- drop(l.write());
+ drop(l.read().unwrap());
+ drop(l.write().unwrap());
+ drop((l.read().unwrap(), l.read().unwrap()));
+ drop(l.write().unwrap());
}
#[test]
fn static_smoke() {
static R: StaticRWLock = RWLOCK_INIT;
- drop(R.read());
- drop(R.write());
- drop((R.read(), R.read()));
- drop(R.write());
+ drop(R.read().unwrap());
+ drop(R.write().unwrap());
+ drop((R.read().unwrap(), R.read().unwrap()));
+ drop(R.write().unwrap());
unsafe { R.destroy(); }
}
for _ in range(0, N) {
let tx = tx.clone();
spawn(move|| {
- let mut rng = rand::task_rng();
+ let mut rng = rand::thread_rng();
for _ in range(0, M) {
if rng.gen_weighted_bool(N) {
- drop(R.write());
+ drop(R.write().unwrap());
} else {
- drop(R.read());
+ drop(R.read().unwrap());
}
}
drop(tx);
}
#[test]
- #[should_fail]
fn test_rw_arc_poison_wr() {
let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
- let _ = Thread::spawn(move|| {
- let lock = arc2.write();
- assert_eq!(*lock, 2);
+ let _: Result<uint, _> = Thread::spawn(move|| {
+ let _lock = arc2.write().unwrap();
+ panic!();
}).join();
- let lock = arc.read();
- assert_eq!(*lock, 1);
+ assert!(arc.read().is_err());
}
#[test]
- #[should_fail]
fn test_rw_arc_poison_ww() {
let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
- let _ = Thread::spawn(move|| {
- let lock = arc2.write();
- assert_eq!(*lock, 2);
+ let _: Result<uint, _> = Thread::spawn(move|| {
+ let _lock = arc2.write().unwrap();
+ panic!();
}).join();
- let lock = arc.write();
- assert_eq!(*lock, 1);
+ assert!(arc.write().is_err());
}
#[test]
fn test_rw_arc_no_poison_rr() {
let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
- let _ = Thread::spawn(move|| {
- let lock = arc2.read();
- assert_eq!(*lock, 2);
+ let _: Result<uint, _> = Thread::spawn(move|| {
+ let _lock = arc2.read().unwrap();
+ panic!();
}).join();
- let lock = arc.read();
+ let lock = arc.read().unwrap();
assert_eq!(*lock, 1);
}
#[test]
fn test_rw_arc_no_poison_rw() {
let arc = Arc::new(RWLock::new(1i));
let arc2 = arc.clone();
- let _ = Thread::spawn(move|| {
- let lock = arc2.read();
- assert_eq!(*lock, 2);
+ let _: Result<uint, _> = Thread::spawn(move|| {
+ let _lock = arc2.read().unwrap();
+ panic!()
}).join();
- let lock = arc.write();
+ let lock = arc.write().unwrap();
assert_eq!(*lock, 1);
}
let (tx, rx) = channel();
Thread::spawn(move|| {
- let mut lock = arc2.write();
+ let mut lock = arc2.write().unwrap();
for _ in range(0u, 10) {
let tmp = *lock;
*lock = -1;
for _ in range(0u, 5) {
let arc3 = arc.clone();
children.push(Thread::spawn(move|| {
- let lock = arc3.read();
+ let lock = arc3.read().unwrap();
assert!(*lock >= 0);
}));
}
// Wait for writer to finish
rx.recv();
- let lock = arc.read();
+ let lock = arc.read().unwrap();
assert_eq!(*lock, 10);
}
}
impl Drop for Unwinder {
fn drop(&mut self) {
- let mut lock = self.i.write();
+ let mut lock = self.i.write().unwrap();
*lock += 1;
}
}
let _u = Unwinder { i: arc2 };
panic!();
}).join();
- let lock = arc.read();
+ let lock = arc.read().unwrap();
assert_eq!(*lock, 2);
}
}
/// This method will block until the internal count of the semaphore is at
/// least 1.
pub fn acquire(&self) {
- let mut count = self.lock.lock();
+ let mut count = self.lock.lock().unwrap();
while *count <= 0 {
- self.cvar.wait(&count);
+ count = self.cvar.wait(count).unwrap();
}
*count -= 1;
}
/// This will increment the number of resources in this semaphore by 1 and
/// will notify any pending waiters in `acquire` or `access` if necessary.
pub fn release(&self) {
- *self.lock.lock() += 1;
+ *self.lock.lock().unwrap() += 1;
self.cvar.notify_one();
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Abstraction of a task pool for basic parallelism.
+//! Abstraction of a thread pool for basic parallelism.
use core::prelude::*;
}
}
-/// A task pool used to execute functions in parallel.
+/// A thread pool used to execute functions in parallel.
///
-/// Spawns `n` worker tasks and replenishes the pool if any worker tasks
+/// Spawns `n` worker threads and replenishes the pool if any worker threads
/// panic.
///
/// # Example
/// assert_eq!(rx.iter().take(8u).sum(), 8u);
/// ```
pub struct TaskPool {
- // How the taskpool communicates with subtasks.
+ // How the threadpool communicates with subthreads.
//
- // This is the only such Sender, so when it is dropped all subtasks will
+ // This is the only such Sender, so when it is dropped all subthreads will
// quit.
jobs: Sender<Thunk>
}
impl TaskPool {
- /// Spawns a new task pool with `tasks` tasks.
+ /// Spawns a new thread pool with `threads` threads.
///
/// # Panics
///
- /// This function will panic if `tasks` is 0.
- pub fn new(tasks: uint) -> TaskPool {
- assert!(tasks >= 1);
+ /// This function will panic if `threads` is 0.
+ pub fn new(threads: uint) -> TaskPool {
+ assert!(threads >= 1);
let (tx, rx) = channel::<Thunk>();
let rx = Arc::new(Mutex::new(rx));
- // Taskpool tasks.
- for _ in range(0, tasks) {
+ // Threadpool threads
+ for _ in range(0, threads) {
spawn_in_pool(rx.clone());
}
TaskPool { jobs: tx }
}
- /// Executes the function `job` on a task in the pool.
+ /// Executes the function `job` on a thread in the pool.
pub fn execute<F>(&self, job: F)
where F : FnOnce(), F : Send
{
fn spawn_in_pool(jobs: Arc<Mutex<Receiver<Thunk>>>) {
Thread::spawn(move |:| {
- // Will spawn a new task on panic unless it is cancelled.
+ // Will spawn a new thread on panic unless it is cancelled.
let sentinel = Sentinel::new(&jobs);
loop {
let message = {
// Only lock jobs for the time it takes
// to get a job, not run it.
- let lock = jobs.lock();
+ let lock = jobs.lock().unwrap();
lock.recv_opt()
};
let pool = TaskPool::new(TEST_TASKS);
- // Panic all the existing tasks.
+ // Panic all the existing threads.
for _ in range(0, TEST_TASKS) {
pool.execute(move|| -> () { panic!() });
}
- // Ensure new tasks were spawned to compensate.
+ // Ensure new threads were spawned to compensate.
let (tx, rx) = channel();
for _ in range(0, TEST_TASKS) {
let tx = tx.clone();
let pool = TaskPool::new(TEST_TASKS);
let waiter = Arc::new(Barrier::new(TEST_TASKS + 1));
- // Panic all the existing tasks in a bit.
+ // Panic all the existing threads in a bit.
for _ in range(0, TEST_TASKS) {
let waiter = waiter.clone();
pool.execute(move|| {
// in theory we can demangle any Unicode code point, but
// for simplicity we just catch the common ones.
- "$x20" => " ",
- "$x27" => "'",
- "$x5b" => "[",
- "$x5d" => "]"
+ "$u{20}" => " ",
+ "$u{27}" => "'",
+ "$u{5b}" => "[",
+ "$u{5d}" => "]"
)
} else {
let idx = match rest.find('$') {
F: FnOnce() -> T,
{
unsafe {
- let _guard = self.lock.lock();
+ let _guard = self.lock.lock().unwrap();
if !*self.initialized.get() {
let (tx, rx) = channel();
*self.chan.get() = mem::transmute(box tx);
let t = f();
Thread::spawn(move |:| {
helper(receive.0, rx, t);
- let _g = self.lock.lock();
+ let _g = self.lock.lock().unwrap();
*self.shutdown.get() = true;
self.cond.notify_one()
}).detach();
/// This is only valid if the worker thread has previously booted
pub fn send(&'static self, msg: M) {
unsafe {
- let _guard = self.lock.lock();
+ let _guard = self.lock.lock().unwrap();
// Must send and *then* signal to ensure that the child receives the
// message. Otherwise it could wake up and go to sleep before we
// Shut down, but make sure this is done inside our lock to ensure
// that we'll always receive the exit signal when the thread
// returns.
- let guard = self.lock.lock();
+ let mut guard = self.lock.lock().unwrap();
// Close the channel by destroying it
let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
// Wait for the child to exit
while !*self.shutdown.get() {
- self.cond.wait(&guard);
+ guard = self.cond.wait(guard).unwrap();
}
drop(guard);
// Collect all the results we found
let mut addrs = Vec::new();
let mut rp = res;
- while rp.is_not_null() {
+ while !rp.is_null() {
unsafe {
let addr = try!(sockaddr_to_addr(mem::transmute((*rp).ai_addr),
(*rp).ai_addrlen as uint));
fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
let ret = Guard {
fd: self.fd(),
- guard: self.inner.lock.lock(),
+ guard: self.inner.lock.lock().unwrap(),
};
assert!(set_nonblocking(self.fd(), true).is_ok());
ret
fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
let ret = Guard {
fd: self.fd(),
- guard: self.inner.lock.lock(),
+ guard: self.inner.lock.lock().unwrap(),
};
assert!(set_nonblocking(self.fd(), true).is_ok());
ret
use iter::{Iterator, IteratorExt};
use os;
use path::GenericPath;
- use ptr::RawPtr;
+ use ptr::PtrExt;
use ptr;
use slice::SliceExt;
"file descriptor is not a TTY"),
libc::ETIMEDOUT => (io::TimedOut, "operation timed out"),
libc::ECANCELED => (io::TimedOut, "operation aborted"),
+ libc::consts::os::posix88::EEXIST =>
+ (io::PathAlreadyExists, "path already exists"),
// These two constants can have the same value on some systems,
// but different values on others, so we can't use a match
fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
let ret = Guard {
fd: self.fd(),
- guard: unsafe { self.inner.lock.lock() },
+ guard: unsafe { self.inner.lock.lock().unwrap() },
};
assert!(set_nonblocking(self.fd(), true).is_ok());
ret
pub mod compat {
use intrinsics::{atomic_store_relaxed, transmute};
- use iter::IteratorExt;
use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID};
use prelude::*;
{
let filename = os::truncate_utf16_at_nul(&wfd.cFileName);
match String::from_utf16(filename) {
- Some(filename) => paths.push(Path::new(filename)),
- None => {
+ Ok(filename) => paths.push(Path::new(filename)),
+ Err(..) => {
assert!(libc::FindClose(find_handle) != 0);
return Err(IoError {
kind: io::InvalidInput,
"invalid handle provided to function"),
libc::ERROR_NOTHING_TO_TERMINATE =>
(io::InvalidInput, "no process to kill"),
+ libc::ERROR_ALREADY_EXISTS =>
+ (io::PathAlreadyExists, "path already exists"),
// libuv maps this error code to EISDIR. we do too. if it is found
// to be incorrect, we can add in some more machinery to only
let msg = String::from_utf16(truncate_utf16_at_nul(&buf));
match msg {
- Some(msg) => format!("OS Error {}: {}", errnum, msg),
- None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
+ Ok(msg) => format!("OS Error {}: {}", errnum, msg),
+ Err(..) => format!("OS Error {} (FormatMessageW() returned \
+ invalid UTF-16)", errnum),
}
}
}
// We want to explicitly catch the case when the
// closure returned invalid UTF-16, rather than
// set `res` to None and continue.
- let s = String::from_utf16(sub)
+ let s = String::from_utf16(sub).ok()
.expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
res = Some(s)
}
}
match String::from_utf16(truncate_utf16_at_nul(&buf)) {
- Some(ref cwd) => Ok(Path::new(cwd)),
- None => Err(IoError {
+ Ok(ref cwd) => Ok(Path::new(cwd)),
+ Err(..) => Err(IoError {
kind: OtherIoError,
desc: "GetCurrentDirectoryW returned invalid UTF-16",
detail: None,
};
utf16.truncate(num as uint);
let utf8 = match String::from_utf16(utf16.as_slice()) {
- Some(utf8) => utf8.into_bytes(),
- None => return Err(invalid_encoding()),
+ Ok(utf8) => utf8.into_bytes(),
+ Err(..) => return Err(invalid_encoding()),
};
self.utf8 = MemReader::new(utf8);
}
/// Spawn a new joinable thread, returning a `JoinGuard` for it.
///
- /// The join guard can be used to explicitly join the child thead (via
+ /// 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. To detach the child, allowing it to outlive the
/// current thread, use `detach`. See the module documentation for additional details.
}
/// Determines whether the current thread is panicking.
+ #[inline]
pub fn panicking() -> bool {
unwind::panicking()
}
// or futuxes, and in either case may allow spurious wakeups.
pub fn park() {
let thread = Thread::current();
- let mut guard = thread.inner.lock.lock();
+ let mut guard = thread.inner.lock.lock().unwrap();
while !*guard {
- thread.inner.cvar.wait(&guard);
+ guard = thread.inner.cvar.wait(guard).unwrap();
}
*guard = false;
}
///
/// See the module doc for more detail.
pub fn unpark(&self) {
- let mut guard = self.inner.lock.lock();
+ let mut guard = self.inner.lock.lock().unwrap();
if !*guard {
*guard = true;
self.inner.cvar.notify_one();
unsafe {
let slot = slot.get().expect("cannot access a TLS value during or \
after it is destroyed");
- if (*slot.get()).is_none() {
- *slot.get() = Some((self.init)());
- }
- f((*slot.get()).as_ref().unwrap())
+ f(match *slot.get() {
+ Some(ref inner) => inner,
+ None => self.init(slot),
+ })
}
}
+ unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
+ *slot.get() = Some((self.init)());
+ (*slot.get()).as_ref().unwrap()
+ }
+
/// Test this TLS key to determine whether its value has been destroyed for
/// the current thread or not.
///
#[macro_export]
macro_rules! scoped_thread_local {
(static $name:ident: $t:ty) => (
- __scoped_thread_local_inner!(static $name: $t)
+ __scoped_thread_local_inner!(static $name: $t);
);
(pub static $name:ident: $t:ty) => (
- __scoped_thread_local_inner!(pub static $name: $t)
+ __scoped_thread_local_inner!(pub static $name: $t);
);
}
use cell::Cell;
use prelude::*;
+ scoped_thread_local!(static FOO: uint);
+
#[test]
fn smoke() {
scoped_thread_local!(static BAR: uint);
});
});
}
+
+ #[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());
+ }
}
/// detects Copy, Send and Sync.
#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub enum TyParamBound {
- TraitTyParamBound(PolyTraitRef),
+ TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
RegionTyParamBound(Lifetime)
}
+/// A modifier on a bound, currently this is only used for `?Sized`, where the
+/// modifier is `Maybe`. Negative bounds should also be handled here.
+#[deriving(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+pub enum TraitBoundModifier {
+ None,
+ Maybe,
+}
+
pub type TyParamBounds = OwnedSlice<TyParamBound>;
#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
pub ident: Ident,
pub id: NodeId,
pub bounds: TyParamBounds,
- pub unbound: Option<TraitRef>,
pub default: Option<P<Ty>>,
pub span: Span
}
pub bound_lifetimes: Vec<LifetimeDef>,
/// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
- pub trait_ref: TraitRef
+ pub trait_ref: TraitRef,
}
#[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
/// Represents a Trait Declaration
ItemTrait(Unsafety,
Generics,
- Option<TraitRef>, // (optional) default bound not required for Self.
- // Currently, only Sized makes sense here.
TyParamBounds,
Vec<TraitItem>),
ItemImpl(Unsafety,
None => {}
}
}
- ItemTrait(_, _, _, ref bounds, ref trait_items) => {
+ ItemTrait(_, _, ref bounds, ref trait_items) => {
for b in bounds.iter() {
- if let TraitTyParamBound(ref t) = *b {
+ if let TraitTyParamBound(ref t, TraitBoundModifier::None) = *b {
self.insert(t.trait_ref.ref_id, NodeItem(i));
}
}
.collect();
ast::ItemImpl(u, a, b, c, impl_items)
}
- ast::ItemTrait(u, a, b, c, methods) => {
+ ast::ItemTrait(u, a, b, methods) => {
let methods = methods.into_iter()
.filter(|m| trait_method_in_cfg(cx, m))
.collect();
- ast::ItemTrait(u, a, b, c, methods)
+ ast::ItemTrait(u, a, b, methods)
}
ast::ItemStruct(def, generics) => {
ast::ItemStruct(fold_struct(cx, def), generics)
span: Span,
id: ast::Ident,
bounds: OwnedSlice<ast::TyParamBound>,
- unbound: Option<ast::TraitRef>,
default: Option<P<ast::Ty>>) -> ast::TyParam;
fn trait_ref(&self, path: ast::Path) -> ast::TraitRef;
span: Span,
id: ast::Ident,
bounds: OwnedSlice<ast::TyParamBound>,
- unbound: Option<ast::TraitRef>,
default: Option<P<ast::Ty>>) -> ast::TyParam {
ast::TyParam {
ident: id,
id: ast::DUMMY_NODE_ID,
bounds: bounds,
- unbound: unbound,
default: default,
span: span
}
}
fn typarambound(&self, path: ast::Path) -> ast::TyParamBound {
- ast::TraitTyParamBound(self.poly_trait_ref(path))
+ ast::TraitTyParamBound(self.poly_trait_ref(path), ast::TraitBoundModifier::None)
}
fn lifetime(&self, span: Span, name: ast::Name) -> ast::Lifetime {
additional_bounds: Vec::new(),
generics: LifetimeBounds {
lifetimes: Vec::new(),
- bounds: vec!(("__D", None, vec!(Path::new_(
+ bounds: vec!(("__D", vec!(Path::new_(
vec!(krate, "Decoder"), None,
vec!(box Literal(Path::new_local("__E"))), true))),
- ("__E", None, vec!()))
+ ("__E", vec!()))
},
methods: vec!(
MethodDef {
additional_bounds: Vec::new(),
generics: LifetimeBounds {
lifetimes: Vec::new(),
- bounds: vec!(("__S", None, vec!(Path::new_(
+ bounds: vec!(("__S", vec!(Path::new_(
vec!(krate, "Encoder"), None,
vec!(box Literal(Path::new_local("__E"))), true))),
- ("__E", None, vec!()))
+ ("__E", vec!()))
},
methods: vec!(
MethodDef {
cx.typaram(self.span,
ty_param.ident,
OwnedSlice::from_vec(bounds),
- ty_param.unbound.clone(),
None)
}));
}
-fn mk_ty_param(cx: &ExtCtxt, span: Span, name: &str,
- bounds: &[Path], unbound: Option<ast::TraitRef>,
- self_ident: Ident, self_generics: &Generics) -> ast::TyParam {
+fn mk_ty_param(cx: &ExtCtxt,
+ span: Span,
+ name: &str,
+ bounds: &[Path],
+ self_ident: Ident,
+ self_generics: &Generics)
+ -> ast::TyParam {
let bounds =
bounds.iter().map(|b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
}).collect();
- cx.typaram(span, cx.ident_of(name), bounds, unbound, None)
+ cx.typaram(span, cx.ident_of(name), bounds, None)
}
fn mk_generics(lifetimes: Vec<ast::LifetimeDef>, ty_params: Vec<ast::TyParam>)
#[deriving(Clone)]
pub struct LifetimeBounds<'a> {
pub lifetimes: Vec<(&'a str, Vec<&'a str>)>,
- pub bounds: Vec<(&'a str, Option<ast::TraitRef>, Vec<Path<'a>>)>,
+ pub bounds: Vec<(&'a str, Vec<Path<'a>>)>,
}
impl<'a> LifetimeBounds<'a> {
}).collect();
let ty_params = self.bounds.iter().map(|t| {
match t {
- &(ref name, ref unbound, ref bounds) => {
+ &(ref name, ref bounds) => {
mk_ty_param(cx,
span,
*name,
bounds.as_slice(),
- unbound.clone(),
self_ty,
self_generics)
}
vec!(box Literal(Path::new_local("__S"))), true),
LifetimeBounds {
lifetimes: Vec::new(),
- bounds: vec!(("__S", None,
+ bounds: vec!(("__S",
vec!(Path::new(vec!("std", "hash", "Writer"))))),
},
Path::new_local("__S"))
generics: LifetimeBounds {
lifetimes: Vec::new(),
bounds: vec!(("R",
- None,
vec!( Path::new(vec!("std", "rand", "Rng")) )))
},
explicit_self: None,
-> TyParamBound
where T: Folder {
match tpb {
- TraitTyParamBound(ty) => TraitTyParamBound(fld.fold_poly_trait_ref(ty)),
+ TraitTyParamBound(ty, modifier) => TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier),
RegionTyParamBound(lifetime) => RegionTyParamBound(fld.fold_lifetime(lifetime)),
}
}
pub fn noop_fold_ty_param<T: Folder>(tp: TyParam, fld: &mut T) -> TyParam {
- let TyParam {id, ident, bounds, unbound, default, span} = tp;
+ let TyParam {id, ident, bounds, default, span} = tp;
TyParam {
id: fld.new_id(id),
ident: ident,
bounds: fld.fold_bounds(bounds),
- unbound: unbound.map(|x| fld.fold_trait_ref(x)),
default: default.map(|x| fld.fold_ty(x)),
span: span
}
folder.fold_ty(ty),
new_impl_items)
}
- ItemTrait(unsafety, generics, unbound, bounds, methods) => {
+ ItemTrait(unsafety, generics, bounds, methods) => {
let bounds = folder.fold_bounds(bounds);
let methods = methods.into_iter().flat_map(|method| {
let r = match method {
}).collect();
ItemTrait(unsafety,
folder.fold_generics(generics),
- unbound,
bounds,
methods)
}
use abi;
use ast::{AssociatedType, BareFnTy, ClosureTy};
-use ast::{RegionTyParamBound, TraitTyParamBound};
+use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
use ast::{ProvidedMethod, Public, Unsafety};
use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, Block};
LifetimeAndTypesWithColons,
}
+/// How to parse a bound, whether to allow bound modifiers such as `?`.
+#[deriving(Copy, PartialEq)]
+pub enum BoundParsingMode {
+ Bare,
+ Modified,
+}
+
enum ItemOrViewItem {
/// Indicates a failure to parse any kind of item. The attributes are
/// returned.
let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
trait_ref: trait_ref };
let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
- self.parse_ty_param_bounds()
+ self.parse_ty_param_bounds(BoundParsingMode::Bare)
} else {
OwnedSlice::empty()
};
let all_bounds =
- Some(TraitTyParamBound(poly_trait_ref)).into_iter()
+ Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
.chain(other_bounds.into_vec().into_iter())
.collect();
ast::TyPolyTraitRef(all_bounds)
// To be helpful, parse the proc as ever
let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
let _ = self.parse_fn_args(false, false);
- let _ = self.parse_colon_then_ty_param_bounds();
+ let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
let _ = self.parse_ret_ty();
self.obsolete(proc_span, ObsoleteProcType);
inputs
};
- let bounds = self.parse_colon_then_ty_param_bounds();
+ let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
let output = self.parse_ret_ty();
let decl = P(FnDecl {
return lhs;
}
- let bounds = self.parse_ty_param_bounds();
+ let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
// In type grammar, `+` is treated like a binary operator,
// and hence both L and R side are required.
// Parses a sequence of bounds if a `:` is found,
// otherwise returns empty list.
- fn parse_colon_then_ty_param_bounds(&mut self)
+ fn parse_colon_then_ty_param_bounds(&mut self,
+ mode: BoundParsingMode)
-> OwnedSlice<TyParamBound>
{
if !self.eat(&token::Colon) {
OwnedSlice::empty()
} else {
- self.parse_ty_param_bounds()
+ self.parse_ty_param_bounds(mode)
}
}
// where boundseq = ( polybound + boundseq ) | polybound
// and polybound = ( 'for' '<' 'region '>' )? bound
// and bound = 'region | trait_ref
- // NB: The None/Some distinction is important for issue #7264.
- fn parse_ty_param_bounds(&mut self)
+ fn parse_ty_param_bounds(&mut self,
+ mode: BoundParsingMode)
-> OwnedSlice<TyParamBound>
{
let mut result = vec!();
loop {
+ let question_span = self.span;
+ let ate_question = self.eat(&token::Question);
match self.token {
token::Lifetime(lifetime) => {
+ if ate_question {
+ self.span_err(question_span,
+ "`?` may only modify trait bounds, not lifetime bounds");
+ }
result.push(RegionTyParamBound(ast::Lifetime {
id: ast::DUMMY_NODE_ID,
span: self.span,
}
token::ModSep | token::Ident(..) => {
let poly_trait_ref = self.parse_poly_trait_ref();
- result.push(TraitTyParamBound(poly_trait_ref))
+ let modifier = if ate_question {
+ if mode == BoundParsingMode::Modified {
+ TraitBoundModifier::Maybe
+ } else {
+ self.span_err(question_span,
+ "unexpected `?`");
+ TraitBoundModifier::None
+ }
+ } else {
+ TraitBoundModifier::None
+ };
+ result.push(TraitTyParamBound(poly_trait_ref, modifier))
}
_ => break,
}
}
}
- /// Matches typaram = (unbound`?`)? IDENT optbounds ( EQ ty )?
+ /// Matches typaram = (unbound `?`)? 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.
+ // type param. Even worse, for now, 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;
ident = self.parse_ident();
}
- let bounds = self.parse_colon_then_ty_param_bounds();
+ 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 },
+ TraitBoundModifier::Maybe));
+ bounds = OwnedSlice::from_vec(bounds_as_vec);
+ };
let default = if self.check(&token::Eq) {
self.bump();
ident: ident,
id: ast::DUMMY_NODE_ID,
bounds: bounds,
- unbound: unbound,
default: default,
span: span,
}
let bounded_ty = self.parse_ty();
if self.eat(&token::Colon) {
- let bounds = self.parse_ty_param_bounds();
+ let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
let hi = self.span.hi;
let span = mk_sp(lo, hi);
fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
let ident = self.parse_ident();
let mut tps = self.parse_generics();
- let sized = self.parse_for_sized();
+ let unbound = self.parse_for_sized();
// Parse supertrait bounds.
- let bounds = self.parse_colon_then_ty_param_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 },
+ TraitBoundModifier::Maybe));
+ bounds = OwnedSlice::from_vec(bounds_as_vec);
+ };
self.parse_where_clause(&mut tps);
let meths = self.parse_trait_items();
- (ident, ItemTrait(unsafety, tps, sized, bounds, meths), None)
+ (ident, ItemTrait(unsafety, tps, bounds, meths), None)
}
fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
}
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 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");
+ "expected `?Sized` after `for` in trait item");
return None;
}
let tref = Parser::trait_ref_from_ident(ident, span);
}
- /// Matches view_path : MOD? IDENT EQ non_global_path
+ /// Matches view_path : MOD? non_global_path as IDENT
/// | MOD? non_global_path MOD_SEP LBRACE RBRACE
/// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
/// | MOD? non_global_path MOD_SEP STAR
}
let mut rename_to = path[path.len() - 1u];
let path = ast::Path {
- span: mk_sp(lo, self.span.hi),
+ span: mk_sp(lo, self.last_span.hi),
global: false,
segments: path.into_iter().map(|identifier| {
ast::PathSegment {
if self.eat_keyword(keywords::As) {
rename_to = self.parse_ident()
}
- P(spanned(lo, self.last_span.hi,
+ P(spanned(lo,
+ self.last_span.hi,
ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID)))
}
// following: debug version. Could work in final except that it's incompatible with
// good error messages and uses of struct names in ambiguous could-be-binding
// locations. Also definitely destroys the guarantee given above about ptr_eq.
- /*let num = rand::task_rng().gen_uint_range(0,0xffff);
+ /*let num = rand::thread_rng().gen_uint_range(0,0xffff);
gensym(format!("{}_{}",ident_to_string(src),num))*/
}
use abi;
use ast::{mod, FnUnboxedClosureKind, FnMutUnboxedClosureKind};
use ast::{FnOnceUnboxedClosureKind};
-use ast::{MethodImplItem, RegionTyParamBound, TraitTyParamBound};
+use ast::{MethodImplItem, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
use ast::{RequiredMethod, ProvidedMethod, TypeImplItem, TypeTraitItem};
use ast::{UnboxedClosureKind};
use ast_util;
}
try!(self.bclose(item.span));
}
- ast::ItemTrait(unsafety, ref generics, ref unbound, ref bounds, ref methods) => {
+ ast::ItemTrait(unsafety, ref generics, ref bounds, ref methods) => {
try!(self.head(""));
try!(self.print_visibility(item.vis));
try!(self.print_unsafety(unsafety));
try!(self.word_nbsp("trait"));
try!(self.print_ident(item.ident));
try!(self.print_generics(generics));
- if let &Some(ref tref) = unbound {
- try!(space(&mut self.s));
- try!(self.word_space("for"));
- try!(self.print_trait_ref(tref));
- try!(word(&mut self.s, "?"));
+ let bounds: Vec<_> = bounds.iter().map(|b| b.clone()).collect();
+ let mut real_bounds = Vec::with_capacity(bounds.len());
+ for b in bounds.into_iter() {
+ if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = b {
+ try!(space(&mut self.s));
+ try!(self.word_space("for ?"));
+ try!(self.print_trait_ref(&ptr.trait_ref));
+ } else {
+ real_bounds.push(b);
+ }
}
- try!(self.print_bounds(":", bounds[]));
+ try!(self.print_bounds(":", real_bounds[]));
try!(self.print_where_clause(generics));
try!(word(&mut self.s, " "));
try!(self.bopen());
}
try!(match *bound {
- TraitTyParamBound(ref tref) => {
+ TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
+ self.print_poly_trait_ref(tref)
+ }
+ TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
+ try!(word(&mut self.s, "?"));
self.print_poly_trait_ref(tref)
}
RegionTyParamBound(ref lt) => {
}
pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
- if let Some(ref tref) = param.unbound {
- try!(self.print_trait_ref(tref));
- try!(self.word_space("?"));
- }
try!(self.print_ident(param.ident));
try!(self.print_bounds(":", param.bounds[]));
match param.default {
fn visit_ty_param_bound(&mut self, bounds: &'v TyParamBound) {
walk_ty_param_bound(self, bounds)
}
- fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef) {
- walk_poly_trait_ref(self, t)
+ fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: &'v TraitBoundModifier) {
+ walk_poly_trait_ref(self, t, m)
}
fn visit_struct_def(&mut self, s: &'v StructDef, _: Ident, _: &'v Generics, _: NodeId) {
walk_struct_def(self, s)
/// Like with walk_method_helper this doesn't correspond to a method
/// in Visitor, and so it gets a _helper suffix.
pub fn walk_poly_trait_ref<'v, V>(visitor: &mut V,
- trait_ref: &'v PolyTraitRef)
+ trait_ref: &'v PolyTraitRef,
+ _modifier: &'v TraitBoundModifier)
where V: Visitor<'v>
{
walk_lifetime_decls_helper(visitor, &trait_ref.bound_lifetimes);
generics,
item.id)
}
- ItemTrait(_, ref generics, _, ref bounds, ref methods) => {
+ ItemTrait(_, ref generics, ref bounds, ref methods) => {
visitor.visit_generics(generics);
walk_ty_param_bounds_helper(visitor, bounds);
for method in methods.iter() {
pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V,
bound: &'v TyParamBound) {
match *bound {
- TraitTyParamBound(ref typ) => {
- visitor.visit_poly_trait_ref(typ);
+ TraitTyParamBound(ref typ, ref modifier) => {
+ visitor.visit_poly_trait_ref(typ, modifier);
}
RegionTyParamBound(ref lifetime) => {
visitor.visit_lifetime_bound(lifetime);
//! [ti]: https://en.wikipedia.org/wiki/Terminfo
#![crate_name = "term"]
-#![experimental]
+#![experimental = "use the crates.io `term` library instead"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-Subproject commit aed73472416064642911af790b25d57c9390b6c7
+Subproject commit 3a37981744a5af2433fed551f742465c78c9af7f
}
fn vec_plus() {
- let mut r = rand::task_rng();
+ let mut r = rand::thread_rng();
let mut v = Vec::new();
let mut i = 0;
}
fn vec_append() {
- let mut r = rand::task_rng();
+ let mut r = rand::thread_rng();
let mut v = Vec::new();
let mut i = 0;
}
fn vec_push_all() {
- let mut r = rand::task_rng();
+ let mut r = rand::thread_rng();
let mut v = Vec::new();
for i in range(0u, 1500) {
fn send(p: &pipe, msg: uint) {
let &(ref lock, ref cond) = &**p;
- let mut arr = lock.lock();
+ let mut arr = lock.lock().unwrap();
arr.push(msg);
cond.notify_one();
}
fn recv(p: &pipe) -> uint {
let &(ref lock, ref cond) = &**p;
- let mut arr = lock.lock();
+ let mut arr = lock.lock().unwrap();
while arr.is_empty() {
- cond.wait(&arr);
+ arr = cond.wait(arr).unwrap();
}
arr.pop().unwrap()
}
--- /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.
+
+mod foo {
+ pub use self::bar::X;
+ use self::bar::X;
+ //~^ ERROR a value named `X` has already been imported in this module
+ //~| ERROR a type named `X` has already been imported in this module
+
+ mod bar {
+ pub struct X;
+ }
+}
+
+fn main() {
+ let _ = foo::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.
+
+trait Foo {}
+
+fn foo<T: Foo + Foo>() {} //~ ERROR `Foo` already appears in the list of bounds
+
+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.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::*;
+use bar::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+ pub type Baz = int;
+}
+
+mod bar {
+ pub type Baz = int;
+}
+
+mod qux {
+ pub use bar::Baz;
+}
+
+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.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::*;
+use foo::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+ pub type Baz = int;
+}
+
+mod bar {
+ pub type Baz = int;
+}
+
+mod qux {
+ pub use bar::Baz;
+}
+
+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.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::Baz;
+use bar::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+ pub type Baz = int;
+}
+
+mod bar {
+ pub type Baz = int;
+}
+
+mod qux {
+ pub use bar::Baz;
+}
+
+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.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::*;
+use bar::Baz; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+ pub type Baz = int;
+}
+
+mod bar {
+ pub type Baz = int;
+}
+
+mod qux {
+ pub use bar::Baz;
+}
+
+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.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::Baz;
+use bar::Baz; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+ pub type Baz = int;
+}
+
+mod bar {
+ pub type Baz = int;
+}
+
+mod qux {
+ pub use bar::Baz;
+}
+
+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.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use qux::*;
+use foo::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+ pub type Baz = int;
+}
+
+mod bar {
+ pub type Baz = int;
+}
+
+mod qux {
+ pub use bar::Baz;
+}
+
+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.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::*;
+use qux::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+ pub type Baz = int;
+}
+
+mod bar {
+ pub type Baz = int;
+}
+
+mod qux {
+ pub use bar::Baz;
+}
+
+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 FromStructReader<'a> { }
+trait ResponseHook {
+ fn get<'a, T: FromStructReader<'a>>(&'a self);
+}
+fn foo(res : Box<ResponseHook>) { res.get } //~ ERROR attempted to take value of method
+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.
+
+#![crate_type = "lib"]
+
+enum NodeContents<'a> {
+ Children(Vec<Node<'a>>),
+}
+
+impl<'a> Drop for NodeContents<'a> {
+ //~^ ERROR cannot implement a destructor on a structure with type parameters
+ fn drop( &mut self ) {
+ }
+}
+
+struct Node<'a> {
+ contents: NodeContents<'a>,
+}
+
+impl<'a> Node<'a> {
+ fn noName(contents: NodeContents<'a>) -> Node<'a> {
+ Node{ contents: contents,}
+ }
+}
+
+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.
+
+struct AutoBuilder<'a> {
+ context: &'a int
+}
+
+impl<'a> Drop for AutoBuilder<'a> {
+ //~^ ERROR cannot implement a destructor on a structure with type parameters
+ fn drop(&mut self) {
+ }
+}
+
+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 Deserializer<'a> { }
+
+trait Deserializable {
+ fn deserialize_token<'a, D: Deserializer<'a>>(D, &'a str) -> Self;
+}
+
+impl<'a, T: Deserializable> Deserializable for &'a str {
+ //~^ ERROR unable to infer enough type information
+ fn deserialize_token<D: Deserializer<'a>>(_x: D, _y: &'a str) -> &'a str {
+ }
+}
+
+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 Node {
+ fn zomg();
+}
+
+trait Graph<N: Node> {
+ fn nodes<'a, I: Iterator<&'a N>>(&'a self) -> I;
+}
+
+impl<N: Node> Graph<N> for Vec<N> {
+ fn nodes<'a, I: Iterator<&'a N>>(&self) -> I {
+ self.iter() //~ ERROR mismatched types
+ }
+}
+
+struct Stuff;
+
+impl Node for Stuff {
+ fn zomg() {
+ println!("zomg");
+ }
+}
+
+fn iterate<N: Node, G: Graph<N>>(graph: &G) {
+ for node in graph.iter() { //~ ERROR does not implement any method in scope named
+ node.zomg();
+ }
+}
+
+pub fn main() {
+ let graph = Vec::new();
+
+ graph.push(Stuff);
+
+ iterate(graph); //~ ERROR mismatched types
+}
--- /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.
+
+extern {
+ pub static symbol: ();
+}
+static CRASH: () = symbol; //~ cannot refer to other statics by value
+
+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.
+
+pub struct Lexer<'a> {
+ input: &'a str,
+}
+
+impl<'a> Lexer<'a> {
+ pub fn new(input: &'a str) -> Lexer<'a> {
+ Lexer { input: input }
+ }
+}
+
+struct Parser<'a> {
+ lexer: &'a mut Lexer<'a>,
+}
+
+impl<'a> Parser<'a> {
+ pub fn new(lexer: &'a mut Lexer) -> Parser<'a> {
+ Parser { lexer: lexer }
+ //~^ ERROR cannot infer an appropriate lifetime for lifetime parameter
+ }
+}
+
+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.
+
+mod Y {
+ type X = uint;
+ extern {
+ static x: *const uint;
+ }
+ fn foo(value: *const X) -> *const X {
+ value
+ }
+}
+
+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::kinds::Sync` is not implemented for the type
+
+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.
+
+use std::fmt::{Show, Formatter, Error};
+use std::collections::HashMap;
+
+trait HasInventory {
+ fn getInventory<'s>(&'s self) -> &'s mut Inventory;
+ fn addToInventory(&self, item: &Item);
+ fn removeFromInventory(&self, itemName: &str) -> bool;
+}
+
+trait TraversesWorld {
+ fn attemptTraverse(&self, room: &Room, directionStr: &str) -> Result<&Room, &str> {
+ let direction = str_to_direction(directionStr);
+ let maybe_room = room.direction_to_room.find(&direction);
+ //~^ ERROR cannot infer an appropriate lifetime for autoref due to conflicting requirements
+ match maybe_room {
+ Some(entry) => Ok(entry),
+ _ => Err("Direction does not exist in room.")
+ }
+ }
+}
+
+
+#[deriving(Show, Eq, PartialEq, Hash)]
+enum RoomDirection {
+ West,
+ East,
+ North,
+ South,
+ Up,
+ Down,
+ In,
+ Out,
+
+ None
+}
+
+struct Room {
+ description: String,
+ items: Vec<Item>,
+ direction_to_room: HashMap<RoomDirection, Room>,
+}
+
+impl Room {
+ fn new(description: &'static str) -> Room {
+ Room {
+ description: description.to_string(),
+ items: Vec::new(),
+ direction_to_room: HashMap::new()
+ }
+ }
+
+ fn add_direction(&mut self, direction: RoomDirection, room: Room) {
+ self.direction_to_room.insert(direction, room);
+ }
+}
+
+struct Item {
+ name: String,
+}
+
+struct Inventory {
+ items: Vec<Item>,
+}
+
+impl Inventory {
+ fn new() -> Inventory {
+ Inventory {
+ items: Vec::new()
+ }
+ }
+}
+
+struct Player {
+ name: String,
+ inventory: Inventory,
+}
+
+impl Player {
+ fn new(name: &'static str) -> Player {
+ Player {
+ name: name.to_string(),
+ inventory: Inventory::new()
+ }
+ }
+}
+
+impl TraversesWorld for Player {
+}
+
+impl Show for Player {
+ fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
+ formatter.write_str("Player{ name:");
+ formatter.write_str(self.name.as_slice());
+ formatter.write_str(" }");
+ Ok(())
+ }
+}
+
+fn str_to_direction(to_parse: &str) -> RoomDirection {
+ match to_parse {
+ "w" | "west" => RoomDirection::West,
+ "e" | "east" => RoomDirection::East,
+ "n" | "north" => RoomDirection::North,
+ "s" | "south" => RoomDirection::South,
+ "in" => RoomDirection::In,
+ "out" => RoomDirection::Out,
+ "up" => RoomDirection::Up,
+ "down" => RoomDirection::Down,
+ _ => None //~ ERROR mismatched types
+ }
+}
+
+fn main() {
+ let mut player = Player::new("Test player");
+ let mut room = Room::new("A test room");
+ println!("Made a player: {}", player);
+ println!("Direction parse: {}", str_to_direction("east"));
+ match player.attemptTraverse(&room, "west") {
+ Ok(_) => println!("Was able to move west"),
+ Err(msg) => println!("Not able to move west: {}", msg)
+ };
+}
--- /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.
+
+struct Foo<'a> {
+ data: &'a[u8],
+}
+
+impl <'a> Foo<'a>{
+ fn bar(self: &mut Foo) {
+ //~^ mismatched types: expected `Foo<'a>`, found `Foo<'_>` (lifetime mismatch)
+ //~| mismatched types: expected `Foo<'a>`, found `Foo<'_>` (lifetime mismatch)
+ }
+}
+
+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.
+
+#![feature(unboxed_closures)]
+#![allow(dead_code)]
+
+type foo = fn(&u8, &u8) -> &u8; //~ ERROR missing lifetime specifier
+//~^ HELP the signature does not say whether it is borrowed from argument 1 or argument 2
+
+fn bar<F: Fn(&u8, &u8) -> &u8>(f: &F) {} //~ ERROR missing lifetime specifier
+//~^ HELP the signature does not say whether it is borrowed from argument 1 or argument 2
+
+fn main() {}
-// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
+// 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.
//
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// ignore-test
-
-use std::io::ReaderUtil;
-use std::io::Reader;
-
-fn bar(r:@ReaderUtil) -> String { r.read_line() }
+trait Foo {}
+impl Foo for u8 {}
fn main() {
- let r : @Reader = io::stdin();
- let _m = bar(r as @ReaderUtil);
+ let r: Box<Foo> = box 5;
+ let _m: Box<Foo> = r as Box<Foo>;
+ //~^ ERROR `core::kinds::Sized` is not implemented for the type `Foo`
+ //~| ERROR `Foo` is not implemented for the type `Foo`
}
// Regresion test for issue 7364
static boxed: Box<RefCell<int>> = box RefCell::new(0);
//~^ ERROR statics are not allowed to have custom pointers
-//~^^ ERROR: the trait `core::kinds::Sync` is not implemented for the type
-//~^^^ ERROR: the trait `core::kinds::Sync` is not implemented for the type
-//~^^^^ ERROR: the trait `core::kinds::Sync` is not implemented for the type
+//~| ERROR: the trait `core::kinds::Sync` is not implemented for the type
+//~| ERROR: the trait `core::kinds::Sync` is not implemented for the type
fn main() { }
f(x);
//~^ ERROR `core::kinds::Sync` is not implemented
//~^^ ERROR `core::kinds::Sync` is not implemented
- //~^^^ ERROR `core::kinds::Sync` is not implemented
}
--- /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.
+
+fn f() {
+ 'l: loop {
+ fn g() {
+ loop {
+ break 'l; //~ ERROR use of undeclared label
+ }
+ }
+ }
+}
+
+fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// ensure that the TaskRng isn't/doesn't become accidentally sendable.
+// ensure that the ThreadRng isn't/doesn't become accidentally sendable.
use std::rand;
fn test_send<S: Send>() {}
pub fn main() {
- test_send::<rand::TaskRng>();
+ test_send::<rand::ThreadRng>();
//~^ ERROR `core::kinds::Send` is not implemented
//~^^ ERROR `core::kinds::Send` is not implemented
}
use std::{char, os};
use std::io::{File, Command};
-use std::rand::{task_rng, Rng};
+use std::rand::{thread_rng, Rng};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an identifier
// this span used to upset the compiler).
fn random_char() -> char {
- let mut rng = task_rng();
+ let mut rng = thread_rng();
// a subset of the XID_start Unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) {
use std::{char, os};
use std::io::{File, Command};
-use std::rand::{task_rng, Rng};
+use std::rand::{thread_rng, Rng};
// creates a file with `fn main() { <random ident> }` and checks the
// compiler emits a span of the appropriate length (for the
// points, but should be the number of graphemes (FIXME #7043)
fn random_char() -> char {
- let mut rng = task_rng();
+ let mut rng = thread_rng();
// a subset of the XID_start Unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1u32, 4u32 + 1) {
let main_file = tmpdir.join("span_main.rs");
for _ in range(0u, 100) {
- let n = task_rng().gen_range(3u, 20);
+ let n = thread_rng().gen_range(3u, 20);
{
let _ = write!(&mut File::create(&main_file).unwrap(),
}
}
-struct Foo<Sized? T> {
+struct Foo<T: ?Sized> {
f: T
}
// As dst-struct.rs, but the unsized field is the only field in the struct.
-struct Fat<Sized? T> {
+struct Fat<T: ?Sized> {
ptr: T
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-struct Fat<Sized? T> {
+struct Fat<T: ?Sized> {
f1: int,
f2: &'static str,
ptr: T
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-struct Fat<Sized? T> {
+struct Fat<T: ?Sized> {
f1: int,
f2: &'static str,
ptr: T
--- /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.
+
+fn foo(_: &[&str]) {}
+
+fn bad(a: &str, b: &str) {
+ foo(&[a, b]);
+}
+
+fn good(a: &str, b: &str) {
+ foo(&[a.as_slice(), b.as_slice()]);
+}
+
+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.
+
+#![feature(unboxed_closures)]
+use std::ops::Fn;
+
+struct Foo<T>(T);
+
+impl<T: Copy> Fn<(), T> for Foo<T> {
+ extern "rust-call" fn call(&self, _: ()) -> T {
+ match *self {
+ Foo(t) => t
+ }
+ }
+}
+
+fn main() {
+ let t: u8 = 1;
+ println!("{}", Foo(t)());
+}
--- /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.
+
+fn foo<'r>() {
+ let maybe_value_ref: Option<&'r u8> = None;
+
+ let _ = maybe_value_ref.map(|& ref v| v);
+ let _ = maybe_value_ref.map(|& ref v| -> &'r u8 {v});
+ let _ = maybe_value_ref.map(|& ref v: &'r u8| -> &'r u8 {v});
+ let _ = maybe_value_ref.map(|& ref v: &'r u8| {v});
+}
+
+fn main() {
+ foo();
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo<'a> {
+ listener: ||: 'a
+}
+
+impl<'a> Foo<'a> {
+ fn new(listener: ||: 'a) -> Foo<'a> {
+ Foo { listener: listener }
+ }
+}
+
+fn main() {
+ let a = Foo::new(|| {});
+}
impl TraitWithSend for IndirectBlah {}
impl IndirectTraitWithSend for IndirectBlah {}
-fn test_trait<Sized? T: Send>() { println!("got here!") }
+fn test_trait<T: Send + ?Sized>() { println!("got here!") }
fn main() {
test_trait::<TraitWithSend>();
// Test that astconv doesn't forget about mutability of &mut str
fn main() {
- fn foo<Sized? T>(_: &mut T) {}
+ fn foo<T: ?Sized>(_: &mut T) {}
let _f: fn(&mut str) = foo;
}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub trait Borrow<Sized? Borrowed> {
+ fn borrow(&self) -> &Borrowed;
+}
+
+impl<T: Sized> Borrow<T> for T {
+ fn borrow(&self) -> &T { self }
+}
+
+trait Foo {
+ fn foo(&self, other: &Self);
+}
+
+fn bar<K, Q>(k: &K, q: &Q) where K: Borrow<Q>, Q: Foo {
+ q.foo(k.borrow())
+}
+
+struct MyTree<K>;
+
+impl<K> MyTree<K> {
+ // This caused a failure in #18906
+ fn bar<Q>(k: &K, q: &Q) where K: Borrow<Q>, Q: Foo {
+ q.foo(k.borrow())
+ }
+}
+
+fn main() {}
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
- use test1::foo::*;
- use test1::bar::*;
+ use test1::bar::p;
pub fn my_main() { assert!(p() == 2); }
}
}
}
-mod test3 {
-
- mod foo { pub fn p() -> int { 1 } }
- mod bar { pub fn p() -> int { 2 } }
-
- pub mod baz {
- use test3::bar::p;
-
- pub fn my_main() { assert!(p() == 2); }
- }
-}
-
fn main() {
test1::baz::my_main();
test2::baz::my_main();
- test3::baz::my_main();
}
use std::sync::Mutex;
pub fn main() {
- unsafe {
- let x = Some(Mutex::new(true));
- match x {
- Some(ref z) if *z.lock() => {
- assert!(*z.lock());
- },
- _ => panic!()
- }
+ let x = Some(Mutex::new(true));
+ match x {
+ Some(ref z) if *z.lock().unwrap() => {
+ assert!(*z.lock().unwrap());
+ },
+ _ => panic!()
}
}
use std::kinds::Sized;
// Note: this must be generic for the problem to show up
-trait Foo<A> for Sized? {
+trait Foo<A> for ?Sized {
fn foo(&self);
}
#![allow(unused_imports)]
use std::io::*;
-use std::io::net::tcp::*;
use std::io::test::*;
use std::io;
use std::time::Duration;
--- /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.
+
+mod base {
+ pub trait HasNew<T> {
+ fn new() -> T;
+ }
+
+ pub struct Foo {
+ dummy: (),
+ }
+
+ impl HasNew<Foo> for Foo {
+ fn new() -> Foo {
+ Foo { dummy: () }
+ }
+ }
+
+ pub struct Bar {
+ dummy: (),
+ }
+
+ impl HasNew<Bar> for Bar {
+ fn new() -> Bar {
+ Bar { dummy: () }
+ }
+ }
+}
+
+pub fn main() {
+ let _f: base::Foo = base::HasNew::new();
+ let _b: base::Bar = base::HasNew::new();
+}
//
// ignore-lexer-test FIXME #15879
-// Test syntax checks for `Sized?` syntax.
+// Test syntax checks for `?Sized` syntax.
-trait T1 for Sized? {}
-pub trait T2 for Sized? {}
-trait T3<X: T1> for Sized?: T2 {}
-trait T4<Sized? X> {}
-trait T5<Sized? X, Y> {}
-trait T6<Y, Sized? X> {}
-trait T7<Sized? X, Sized? Y> {}
-trait T8<Sized? X: T2> {}
-struct S1<Sized? X>;
-enum E<Sized? X> {}
-impl <Sized? X> T1 for S1<X> {}
-fn f<Sized? X>() {}
-type TT<Sized? T> = T;
+trait T1 for ?Sized {}
+pub trait T2 for ?Sized {}
+trait T3<X: T1> for ?Sized: T2 {}
+trait T4<X: ?Sized> {}
+trait T5<X: ?Sized, Y> {}
+trait T6<Y, X: ?Sized> {}
+trait T7<X: ?Sized, Y: ?Sized> {}
+trait T8<X: ?Sized+T2> {}
+trait T9<X: T2 + ?Sized> {}
+struct S1<X: ?Sized>;
+enum E<X: ?Sized> {}
+impl <X: ?Sized> T1 for S1<X> {}
+fn f<X: ?Sized>() {}
+type TT<T: ?Sized> = T;
pub fn main() {
}
// Test sized-ness checking in substitution.
// Unbounded.
-fn f1<Sized? X>(x: &X) {
+fn f1<X: ?Sized>(x: &X) {
f1::<X>(x);
}
fn f2<X>(x: &X) {
}
// Bounded.
-trait T for Sized? {}
-fn f3<Sized? X: T>(x: &X) {
+trait T for ?Sized {}
+fn f3<X: T+?Sized>(x: &X) {
f3::<X>(x);
}
fn f4<X: T>(x: &X) {
}
// Self type.
-trait T2 for Sized? {
+trait T2 for ?Sized {
fn f() -> Box<Self>;
}
struct S;
box S
}
}
-fn f5<Sized? X: T2>(x: &X) {
+fn f5<X: ?Sized+T2>(x: &X) {
let _: Box<X> = T2::f();
}
fn f6<X: T2>(x: &X) {
let _: Box<X> = T2::f();
}
-trait T3 for Sized? {
+trait T3 for ?Sized {
fn f() -> Box<Self>;
}
impl T3 for S {
box S
}
}
-fn f7<Sized? X: T3>(x: &X) {
+fn f7<X: ?Sized+T3>(x: &X) {
// This is valid, but the unsized bound on X is irrelevant because any type
// which implements T3 must have statically known size.
let _: Box<X> = T3::f();
fn m1(x: &T4<X>);
fn m2(x: &T5<X>);
}
-trait T5<Sized? X> {
+trait T5<X: ?Sized> {
// not an error (for now)
fn m1(x: &T4<X>);
fn m2(x: &T5<X>);
fn m1(x: &T4<X>);
fn m2(x: &T5<X>);
}
-trait T7<Sized? X: T> {
+trait T7<X: ?Sized+T> {
// not an error (for now)
fn m1(x: &T4<X>);
fn m2(x: &T5<X>);
}
// The last field in a struct or variant may be unsized
-struct S2<Sized? X> {
+struct S2<X: ?Sized> {
f: X,
}
-struct S3<Sized? X> {
+struct S3<X: ?Sized> {
f1: int,
f2: X,
}
-enum E<Sized? X> {
+enum E<X: ?Sized> {
V1(X),
V2{x: X},
V3(int, X),
use std::task;
use std::sync::atomic::{AtomicUint, INIT_ATOMIC_UINT, Relaxed};
-use std::rand::{task_rng, Rng, Rand};
+use std::rand::{thread_rng, Rng, Rand};
const REPEATS: uint = 5;
const MAX_LEN: uint = 32;
// IDs start from 0.
creation_count.store(0, Relaxed);
- let main = task_rng().gen_iter::<DropCounter>()
+ let main = thread_rng().gen_iter::<DropCounter>()
.take(len)
.collect::<Vec<DropCounter>>();
fn f(p: &mut Point) { p.z = 13; }
pub fn main() {
- unsafe {
- let x = Some(Mutex::new(true));
- match x {
- Some(ref z) if *z.lock() => {
- assert!(*z.lock());
- },
- _ => panic!()
- }
+ let x = Some(Mutex::new(true));
+ match x {
+ Some(ref z) if *z.lock().unwrap() => {
+ assert!(*z.lock().unwrap());
+ },
+ _ => panic!()
}
}