diff --git a/Makefile.in b/Makefile.in index 17ae845bf0773..a2394101f3a72 100644 --- a/Makefile.in +++ b/Makefile.in @@ -99,7 +99,7 @@ # 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: diff --git a/mk/dist.mk b/mk/dist.mk index bdda15dcc1835..963627dbe0997 100644 --- a/mk/dist.mk +++ b/mk/dist.mk @@ -23,6 +23,8 @@ # * 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 @@ -229,10 +231,20 @@ dist-install-dir-$(1): prepare-base-dir-$(1) docs compiler-docs $$(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 \ @@ -242,9 +254,50 @@ dist/$$(PKG_NAME)-$(1).tar.gz: dist-install-dir-$(1) --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),) @@ -257,7 +310,16 @@ endif 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 @@ -289,27 +351,20 @@ distcheck-docs: dist-docs # 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),) @@ -320,15 +375,13 @@ MAYBE_DIST_DOCS=dist-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 diff --git a/mk/grammar.mk b/mk/grammar.mk index a9f45907b8110..08461f9dcc2b7 100644 --- a/mk/grammar.mk +++ b/mk/grammar.mk @@ -31,7 +31,7 @@ $(BG): $(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 diff --git a/mk/install.mk b/mk/install.mk index 632df3c754b8d..f36ca4db7ca7e 100644 --- a/mk/install.mk +++ b/mk/install.mk @@ -20,6 +20,9 @@ ifeq (root user, $(USER) $(patsubst %,user,$(SUDO_USER))) $(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 @@ -33,6 +36,9 @@ ifeq (root user, $(USER) $(patsubst %,user,$(SUDO_USER))) $(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 diff --git a/mk/tests.mk b/mk/tests.mk index 1a122572e434c..bf07d6de0e026 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -74,14 +74,6 @@ endif 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) @@ -297,6 +289,7 @@ tidy: | 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 diff --git a/src/doc/guide-tasks.md b/src/doc/guide-tasks.md index 87a3abd8f226b..29c98e22ee978 100644 --- a/src/doc/guide-tasks.md +++ b/src/doc/guide-tasks.md @@ -1,6 +1,6 @@ -% 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 @@ -9,36 +9,36 @@ primitives. This guide will describe the concurrency model in Rust, how it 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. @@ -49,26 +49,26 @@ argument a closure (of type `F`) that it will run exactly once. This 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. @@ -78,7 +78,7 @@ of a channel, and a **receiver** is the receiving endpoint. Consider the followi example of calculating two results concurrently: ```{rust,ignore} -# use std::task::spawn; +# use std::thread::spawn; let (tx, rx): (Sender, Receiver) = channel(); @@ -102,12 +102,12 @@ into its component parts). let (tx, rx): (Sender, Receiver) = 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 || { @@ -116,10 +116,10 @@ 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 @@ -137,7 +137,7 @@ The `Sender` and `Receiver` pair created by `channel` enables efficient 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 } @@ -160,7 +160,7 @@ Instead we can clone the `tx`, which allows for multiple senders. 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)); @@ -172,7 +172,7 @@ let result = rx.recv() + rx.recv() + rx.recv(); ``` 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. @@ -182,9 +182,9 @@ simply use three `Sender` pairs, but it serves to illustrate the point. For 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 || { @@ -256,18 +256,18 @@ fn main() { ## 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} @@ -284,10 +284,10 @@ fn main() { 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)); }); } } @@ -306,8 +306,8 @@ let numbers_arc = Arc::new(numbers); # } ``` -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. @@ -319,29 +319,29 @@ if it were local. # let numbers=Vec::from_fn(1000000, |_| rand::random::()); # 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>`. `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` @@ -364,14 +364,14 @@ assert!(result.is_err()); 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 @@ -379,4 +379,4 @@ the entire program (perhaps you're writing an assert which, if it trips, 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). diff --git a/src/doc/guide.md b/src/doc/guide.md index 22cbd18a86520..d094c47da93bb 100644 --- a/src/doc/guide.md +++ b/src/doc/guide.md @@ -23,11 +23,16 @@ Linux or a Mac, all you need to do is this (note that you don't need to type 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) @@ -482,7 +487,7 @@ src/main.rs:2 let x; Giving it a type will compile, though: -```{ignore} +```{rust} let x: int; ``` @@ -1044,7 +1049,9 @@ struct Point(int, int, 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); ``` @@ -1604,10 +1611,6 @@ let a = [1i, 2i, 3i]; // a: [int, ..3] 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`: @@ -1895,7 +1898,7 @@ authors = ["Your Name "] 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() { @@ -3036,7 +3039,7 @@ test foo ... FAILED 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 @@ -3045,7 +3048,7 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured -task '
' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243 +thread '
' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243 ``` Lots of output! Let's break this down: @@ -3088,7 +3091,7 @@ failed, especially as we accumulate more tests. 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 @@ -3097,7 +3100,7 @@ failures: test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured -task '
' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243 +thread '
' 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. @@ -4263,7 +4266,7 @@ is that a moving closure always takes ownership of all variables that 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 @@ -4290,7 +4293,9 @@ let square = |x: int| { x * x }; 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 ``` @@ -5213,9 +5218,7 @@ as you can see, there's no overhead of deciding which version to call here, 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, @@ -5224,24 +5227,22 @@ processor. Rust's semantics lend themselves very nicely to solving a number of 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]; @@ -5257,15 +5258,15 @@ println!("The value of x[0] is: {}", x[0]); // error: use of moved value: `x` 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(); @@ -5278,14 +5279,14 @@ receive the message on the `Receiver` side with the `recv()` method. This method blocks until it gets a message. There's a similar method, `.try_recv()`, which returns an `Result` 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); }); @@ -5296,9 +5297,9 @@ 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. @@ -5337,7 +5338,7 @@ we'll just get the value immediately. ## 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} @@ -5346,14 +5347,14 @@ spawn(move || { }); ``` -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 { @@ -5362,7 +5363,7 @@ let result = task::try(move || { }); ``` -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. @@ -5410,7 +5411,7 @@ fn main() { } ``` -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} diff --git a/src/doc/index.md b/src/doc/index.md index 779099558220a..e54bf0eb24282 100644 --- a/src/doc/index.md +++ b/src/doc/index.md @@ -58,7 +58,7 @@ a guide that can help you out: * [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) diff --git a/src/doc/intro.md b/src/doc/intro.md index 5be97034357eb..a4e9d85bffdf8 100644 --- a/src/doc/intro.md +++ b/src/doc/intro.md @@ -483,7 +483,7 @@ fn main() { 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; diff --git a/src/doc/reference.md b/src/doc/reference.md index b71994c9836a1..94c76aaa69518 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -194,11 +194,11 @@ grammar as double-quoted strings. Other tokens have exact rules given. | 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 @@ -899,8 +899,8 @@ mirrors the module hierarchy. // 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; } ``` @@ -909,9 +909,9 @@ The directories and files used for loading external file modules can be 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; } @@ -1188,7 +1188,7 @@ code safe, in the surrounding context. 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 @@ -1500,7 +1500,7 @@ be modified by the program. One of Rust's goals is to make concurrency bugs 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 @@ -2253,11 +2253,11 @@ A complete list of the built-in language items follows: * `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 @@ -2621,7 +2621,7 @@ The currently implemented features of the reference compiler are: 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 @@ -2939,7 +2939,7 @@ array is mutable, the resulting [lvalue](#lvalues,-rvalues-and-temporaries) can 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} @@ -3950,7 +3950,7 @@ Types in Rust are categorized into kinds, based on various properties of the 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`. @@ -3998,21 +3998,21 @@ to sendable. # 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*. @@ -4023,8 +4023,8 @@ The _items_ of a program are those functions, modules and types that have their 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 @@ -4034,10 +4034,10 @@ in the heap, heap allocations may outlive the frame they are allocated within. ### 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) @@ -4046,12 +4046,12 @@ sendable kinds of data constructor and pointers, never including references. 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. @@ -4105,72 +4105,69 @@ let y = x; // 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 @@ -4181,7 +4178,7 @@ environment and releases them back to its environment when they are no longer 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. @@ -4189,15 +4186,15 @@ 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. diff --git a/src/etc/kate/rust.xml b/src/etc/kate/rust.xml index c22cd9c20479c..9d0450285091c 100644 --- a/src/etc/kate/rust.xml +++ b/src/etc/kate/rust.xml @@ -245,6 +245,7 @@ + @@ -255,7 +256,7 @@ - + diff --git a/src/etc/make-win-dist.py b/src/etc/make-win-dist.py index 95e647c91cfe6..ea2a98db2dc1f 100644 --- a/src/etc/make-win-dist.py +++ b/src/etc/make-win-dist.py @@ -114,11 +114,5 @@ def make_win_dist(rust_root, gcc_root, target_triple): 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]) diff --git a/src/grammar/RustLexer.g4 b/src/grammar/RustLexer.g4 index 0ff9af7aca133..00af6d358e5eb 100644 --- a/src/grammar/RustLexer.g4 +++ b/src/grammar/RustLexer.g4 @@ -112,7 +112,8 @@ LIT_INTEGER ; 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 diff --git a/src/grammar/verify.rs b/src/grammar/verify.rs index f7b19cf6fbf5e..bdb616fcc99b8 100644 --- a/src/grammar/verify.rs +++ b/src/grammar/verify.rs @@ -61,7 +61,7 @@ fn parse_token_list(file: &str) -> HashMap { "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, @@ -71,7 +71,7 @@ fn parse_token_list(file: &str) -> HashMap { "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, @@ -80,8 +80,8 @@ fn parse_token_list(file: &str) -> HashMap { "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, @@ -95,9 +95,9 @@ fn parse_token_list(file: &str) -> HashMap { "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), @@ -107,8 +107,8 @@ fn parse_token_list(file: &str) -> HashMap { "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, }; @@ -189,17 +189,17 @@ fn parse_antlr_token(s: &str, tokens: &HashMap) -> TokenAn 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 }), @@ -214,8 +214,8 @@ fn parse_antlr_token(s: &str, tokens: &HashMap) -> TokenAn }; let sp = syntax::codemap::Span { - lo: syntax::codemap::BytePos(from_str::(start).unwrap() - offset), - hi: syntax::codemap::BytePos(from_str::(end).unwrap() + 1), + lo: syntax::codemap::BytePos(start.parse::().unwrap() - offset), + hi: syntax::codemap::BytePos(end.parse::().unwrap() + 1), expn_id: syntax::codemap::NO_EXPANSION }; @@ -247,7 +247,9 @@ fn main() { 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(); @@ -284,17 +286,17 @@ fn main() { 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(..), diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 3e235caab18ad..21c47cdf3d752 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -58,7 +58,7 @@ //! let five = five.clone(); //! //! Thread::spawn(move || { -//! let mut number = five.lock(); +//! let mut number = five.lock().unwrap(); //! //! *number += 1; //! @@ -80,7 +80,7 @@ use core::nonzero::NonZero; 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. @@ -722,7 +722,7 @@ mod tests { 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)... } diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index c6b6a784f06e3..cdc30efd2d9a2 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -8,7 +8,7 @@ // 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` @@ -371,7 +371,7 @@ mod imp { mod test { extern crate test; use self::test::Bencher; - use core::ptr::RawPtr; + use core::ptr::PtrExt; use heap; #[test] diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 13dc4474c1a19..214fae02ce272 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Task-local reference-counted boxes (the `Rc` type). +//! Thread-local reference-counted boxes (the `Rc` type). //! //! The `Rc` 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 @@ -154,7 +154,7 @@ use core::nonzero::NonZero; 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}; diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 1f4df1fd0a5a2..b0fa5434a1474 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -412,7 +412,7 @@ impl TypedArenaChunk { let size = calculate_size::(self.capacity); deallocate(self as *mut TypedArenaChunk as *mut u8, size, mem::min_align_of::>()); - if next.is_not_null() { + if !next.is_null() { let capacity = (*next).capacity; (*next).destroy(capacity); } diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index f20b37cb60f26..d8ce79f4fe90d 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -95,7 +95,7 @@ impl Rawlink { /// 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()) } } diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index 363d30abd0347..fe9d8de440a17 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -114,14 +114,14 @@ mod prelude { 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; diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 404804cd91d2e..c55a8ba104ebe 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -96,7 +96,7 @@ use core::mem::size_of; 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::*; @@ -1343,11 +1343,14 @@ pub mod raw { #[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; @@ -1963,7 +1966,7 @@ mod tests { fn test_sort() { for len in range(4u, 25) { for _ in range(0i, 100) { - let mut v = task_rng().gen_iter::().take(len) + let mut v = thread_rng().gen_iter::().take(len) .collect::>(); let mut v1 = v.clone(); @@ -1999,7 +2002,7 @@ mod tests { // 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::() % 10; + let n = thread_rng().gen::() % 10; counts[n] += 1; (n, counts[n]) }).collect::>(); diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 881eb45f7cce7..7c7a7e19a2f18 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -89,8 +89,6 @@ pub use unicode::str::{Words, Graphemes, GraphemeIndices}; 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 */ @@ -1768,26 +1766,13 @@ impl StrExt for str {} #[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() { @@ -3354,7 +3339,7 @@ mod tests { #[cfg(test)] mod bench { use super::*; - use prelude::*; + use prelude::{SliceExt, IteratorExt, DoubleEndedIteratorExt}; use test::Bencher; use test::black_box; diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 9460b9a896646..c6c19cae75f1e 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -12,6 +12,8 @@ //! An owned, growable string that enforces that its contents are valid UTF-8. +#![stable] + use core::prelude::*; use core::borrow::{Cow, IntoCow}; @@ -36,6 +38,18 @@ pub struct String { vec: Vec, } +/// A possible error value from the `String::from_utf8` function. +#[stable] +pub struct FromUtf8Error { + bytes: Vec, + 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. /// @@ -98,19 +112,20 @@ impl 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) -> Result, Utf8Error)> { + #[stable] + pub fn from_utf8(vec: Vec) -> Result { 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 }) } } @@ -124,7 +139,7 @@ impl String { /// 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), @@ -251,22 +266,23 @@ impl String { /// // 𝄞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()); /// /// // 𝄞muic /// 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 { + #[stable] + pub fn from_utf16(v: &[u16]) -> Result { 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 @@ -293,12 +309,13 @@ impl String { /// # Examples /// /// ```rust + /// # #![allow(deprecated)] /// let chars = &['h', 'e', 'l', 'l', 'o']; /// let s = String::from_chars(chars); /// assert_eq!(s.as_slice(), "hello"); /// ``` #[inline] - #[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() } @@ -309,7 +326,7 @@ impl String { /// * We call `Vec::from_raw_parts` to get a `Vec`; /// * 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), @@ -344,7 +361,7 @@ impl String { /// 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) -> String { String { vec: bytes } } @@ -369,12 +386,12 @@ impl String { /// # 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() @@ -400,7 +417,7 @@ impl String { /// 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()) } @@ -410,19 +427,21 @@ impl String { /// # 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 /// @@ -431,7 +450,7 @@ impl String { /// assert!(s.capacity() >= 10); /// ``` #[inline] - #[unstable = "matches collection reform specification, waiting for dust to settle"] + #[stable] pub fn capacity(&self) -> uint { self.vec.capacity() } @@ -442,8 +461,9 @@ impl String { 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 /// @@ -457,17 +477,18 @@ impl String { /// 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 /// @@ -481,7 +502,7 @@ impl String { /// 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) } @@ -498,7 +519,7 @@ impl String { /// 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() } @@ -515,7 +536,7 @@ impl String { /// 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); @@ -568,7 +589,7 @@ impl String { /// 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) @@ -587,7 +608,7 @@ impl String { /// assert_eq!(s.pop(), None); /// ``` #[inline] - #[unstable = "this function was just renamed from pop_char"] + #[stable] pub fn pop(&mut self) -> Option { let len = self.len(); if len == 0 { @@ -602,7 +623,7 @@ impl String { } /// 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 /// @@ -611,23 +632,21 @@ impl String { /// /// # 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 { + #[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 { @@ -636,7 +655,7 @@ impl String { len - next); self.vec.set_len(len - (next - idx)); } - Some(ch) + ch } /// Insert a character into the string buffer at byte position `idx`. @@ -650,7 +669,7 @@ impl String { /// /// 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); @@ -686,7 +705,7 @@ impl String { /// } /// 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 { &mut self.vec } @@ -713,6 +732,7 @@ impl String { /// 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. @@ -731,6 +751,29 @@ impl String { } } +impl FromUtf8Error { + /// Consume this error, returning the bytes that were attempted to make a + /// `String` with. + #[stable] + pub fn into_bytes(self) -> Vec { 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 for String { fn from_iter>(iterator: I) -> String { @@ -933,6 +976,7 @@ impl FromStr for 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; @@ -1038,7 +1082,7 @@ mod tests { use prelude::*; use test::Bencher; - use str::{StrExt, Utf8Error}; + use str::Utf8Error; use str; use super::as_string; @@ -1057,16 +1101,17 @@ mod tests { #[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] @@ -1171,15 +1216,15 @@ mod tests { 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] @@ -1312,12 +1357,10 @@ mod tests { #[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"); } diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index b45424a5eed3f..01a1e7f97110a 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -158,7 +158,7 @@ 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}; @@ -167,7 +167,6 @@ use option::Option::{None, Some}; #[stable] pub struct Cell { value: UnsafeCell, - noshare: marker::NoSync, } impl Cell { @@ -176,7 +175,6 @@ impl Cell { pub fn new(value: T) -> Cell { Cell { value: UnsafeCell::new(value), - noshare: marker::NoSync, } } @@ -208,6 +206,9 @@ impl Cell { } } +#[stable] +unsafe impl Send for Cell where T: Send {} + #[stable] impl Clone for Cell { fn clone(&self) -> Cell { @@ -235,7 +236,6 @@ impl PartialEq for Cell { pub struct RefCell { value: UnsafeCell, borrow: Cell, - noshare: marker::NoSync, } // Values [1, MAX-1] represent the number of `Ref` active @@ -251,7 +251,6 @@ impl RefCell { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), - noshare: marker::NoSync, } } @@ -341,6 +340,9 @@ impl RefCell { } } +#[stable] +unsafe impl Send for RefCell where T: Send {} + #[stable] impl Clone for RefCell { fn clone(&self) -> RefCell { diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 686ccf6f1a251..5d84d0c7797ec 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -36,7 +36,7 @@ pub trait Clone { /// 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() } diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index 2cd9e7c45098e..781dbb0e55a3f 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -85,16 +85,6 @@ macro_rules! assert { ); } -/// 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 { @@ -117,7 +107,7 @@ macro_rules! debug_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)*); }) diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index f6abc8da79c0c..fd1598db8cdfc 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -57,7 +57,7 @@ pub use iter::{IteratorOrdExt, MutableDoubleEndedIterator, ExactSizeIterator}; 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}; diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 8c724b4d8521f..75bb8d33ea85f 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -16,11 +16,10 @@ //! 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 @@ -87,16 +86,16 @@ //! 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 :( @@ -121,7 +120,7 @@ pub use intrinsics::set_memory; /// assert!(p.is_null()); /// ``` #[inline] -#[unstable = "may need a different name after pending changes to pointer types"] +#[stable] pub fn null() -> *const T { 0 as *const T } /// Creates a null mutable raw pointer. @@ -135,31 +134,31 @@ pub fn null() -> *const T { 0 as *const T } /// assert!(p.is_null()); /// ``` #[inline] -#[unstable = "may need a different name after pending changes to pointer types"] +#[stable] pub fn null_mut() -> *mut T { 0 as *mut T } -/// Zeroes out `count * size_of::` bytes of memory at `dst`. `count` may be `0`. +/// Zeroes out `count * size_of::` 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(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(x: *mut T, y: *mut T) { // Give ourselves some scratch space to work with let mut tmp: T = mem::uninitialized(); @@ -183,7 +182,7 @@ pub unsafe fn swap(x: *mut T, y: *mut T) { /// 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(dest: *mut T, mut src: T) -> T { mem::swap(mem::transmute(dest), &mut src); // cannot overlap src @@ -201,7 +200,7 @@ pub unsafe fn replace(dest: *mut T, mut src: T) -> T { /// `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(src: *const T) -> T { let mut tmp: T = mem::uninitialized(); copy_nonoverlapping_memory(&mut tmp, src, 1); @@ -214,8 +213,7 @@ pub unsafe fn read(src: *const T) -> T { /// /// 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(dest: *mut T) -> T { // Copy the data out from `dest`: let tmp = read(&*dest); @@ -226,8 +224,8 @@ pub unsafe fn read_and_zero(dest: *mut T) -> T { 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 /// @@ -235,36 +233,44 @@ pub unsafe fn read_and_zero(dest: *mut T) -> T { /// 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(dst: *mut T, src: T) { intrinsics::move_val_init(&mut *dst, src) } /// Methods on raw pointers -pub trait RawPtr { - /// Returns a null raw pointer. +#[stable] +pub trait PtrExt { + /// 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 @@ -272,39 +278,51 @@ pub trait RawPtr { /// /// # 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{ - /// Returns `None` if the pointer is null, or else returns a mutable reference - /// to the value wrapped in `Some`. +#[stable] +pub trait MutPtrExt{ + /// 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 RawPtr for *const T { +#[stable] +impl PtrExt 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 @@ -314,22 +332,29 @@ impl RawPtr for *const T { } } -impl RawPtr for *mut T { +#[stable] +impl PtrExt 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 @@ -339,8 +364,11 @@ impl RawPtr for *mut T { } } -impl RawMutPtr for *mut T { +#[stable] +impl MutPtrExt 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 @@ -510,28 +538,33 @@ impl PartialOrd for *mut T { /// raw `*mut T` (which conveys no particular ownership semantics). /// Useful for building abstractions like `Vec` or `Box`, which /// internally use raw pointers to manage the memory that they own. +#[unstable = "recently added to this module"] pub struct Unique(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 Send for Unique { } /// `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 Sync for Unique { } impl Unique { /// Returns a null Unique. + #[unstable = "recently added to this module"] pub fn null() -> Unique { - 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) } } diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 8014b4dc89d70..bd1c6dbcf1e9a 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -332,7 +332,7 @@ impl Result { /// Convert from `Result` to `Option` /// - /// Converts `self` into an `Option`, consuming `self`, + /// Converts `self` into an `Option`, consuming `self`, /// and discarding the value, if any. /// /// # Example diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index d25f96ac15fa6..f356a0867d252 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -47,7 +47,7 @@ use ops::{FnMut, mod}; 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}; @@ -1335,7 +1335,7 @@ pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] { #[deprecated] pub mod raw { use mem::transmute; - use ptr::RawPtr; + use ptr::PtrExt; use raw::Slice; use ops::FnOnce; use option::Option; diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 1fc5f90028dad..8db672b265375 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -28,7 +28,7 @@ use mem; 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}; @@ -1073,7 +1073,7 @@ const TAG_CONT_U8: u8 = 0b1000_0000u8; /// Unsafe operations #[deprecated] pub mod raw { - use ptr::RawPtr; + use ptr::PtrExt; use raw::Slice; use slice::SliceExt; use str::StrExt; diff --git a/src/libflate/lib.rs b/src/libflate/lib.rs index 8c4f74027a52f..aa1550ae5b874 100644 --- a/src/libflate/lib.rs +++ b/src/libflate/lib.rs @@ -112,7 +112,7 @@ mod tests { #[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); diff --git a/src/librand/distributions/exponential.rs b/src/librand/distributions/exponential.rs index 431a530726a08..f31f3468a4c00 100644 --- a/src/librand/distributions/exponential.rs +++ b/src/librand/distributions/exponential.rs @@ -64,7 +64,7 @@ impl Rand for Exp1 { /// 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)] diff --git a/src/librand/distributions/gamma.rs b/src/librand/distributions/gamma.rs index d33d838766f22..618db380db8d4 100644 --- a/src/librand/distributions/gamma.rs +++ b/src/librand/distributions/gamma.rs @@ -44,7 +44,7 @@ use super::{IndependentSample, Sample, Exp}; /// 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); /// ``` /// @@ -191,7 +191,7 @@ impl IndependentSample for GammaLargeShape { /// 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 { @@ -248,7 +248,7 @@ impl IndependentSample for 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 { @@ -292,7 +292,7 @@ impl IndependentSample for 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 { diff --git a/src/librand/distributions/mod.rs b/src/librand/distributions/mod.rs index 58125c67fdae9..54cb8ae190718 100644 --- a/src/librand/distributions/mod.rs +++ b/src/librand/distributions/mod.rs @@ -96,7 +96,7 @@ pub struct Weighted { /// 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)); diff --git a/src/librand/distributions/normal.rs b/src/librand/distributions/normal.rs index 16413af626739..3507282ec486a 100644 --- a/src/librand/distributions/normal.rs +++ b/src/librand/distributions/normal.rs @@ -81,7 +81,7 @@ impl Rand for StandardNormal { /// /// // 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)] @@ -129,7 +129,7 @@ impl IndependentSample for Normal { /// /// // 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)] diff --git a/src/librand/distributions/range.rs b/src/librand/distributions/range.rs index 6301623bbdc18..20ba3566d5b12 100644 --- a/src/librand/distributions/range.rs +++ b/src/librand/distributions/range.rs @@ -39,7 +39,7 @@ use distributions::{Sample, IndependentSample}; /// /// 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); diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 514ff81da518e..273b991bc22f2 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -138,10 +138,10 @@ pub trait 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]) { @@ -173,9 +173,9 @@ pub trait Rng { /// # 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)>()); @@ -191,9 +191,9 @@ pub trait Rng { /// # 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::().take(10).collect::>(); /// println!("{}", x); /// println!("{}", rng.gen_iter::<(f64, bool)>().take(5) @@ -218,9 +218,9 @@ pub trait Rng { /// # 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); @@ -236,9 +236,9 @@ pub trait Rng { /// # 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 { @@ -250,9 +250,9 @@ pub trait Rng { /// # 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> { @@ -266,10 +266,10 @@ pub trait Rng { /// # 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); /// ``` @@ -286,9 +286,9 @@ pub trait Rng { /// # 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()); @@ -520,8 +520,8 @@ mod test { } } - pub fn rng() -> MyRng { - MyRng { inner: rand::task_rng() } + pub fn rng() -> MyRng { + MyRng { inner: rand::thread_rng() } } pub fn weak_rng() -> MyRng { diff --git a/src/librand/rand_impls.rs b/src/librand/rand_impls.rs index 3b38fde3884f1..e50153076c390 100644 --- a/src/librand/rand_impls.rs +++ b/src/librand/rand_impls.rs @@ -215,7 +215,7 @@ impl Rand for Option { #[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 { @@ -240,7 +240,7 @@ mod tests { 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::>(); @@ -253,7 +253,7 @@ mod tests { #[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::>(); diff --git a/src/libregex/parse.rs b/src/libregex/parse.rs index 105687b89fdd7..86c02de76dcc6 100644 --- a/src/libregex/parse.rs +++ b/src/libregex/parse.rs @@ -519,8 +519,8 @@ impl<'a> Parser<'a> { }; 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::(); // Parse the min and max values from the regex. let (mut min, mut max): (uint, Option); @@ -954,7 +954,7 @@ impl<'a> Parser<'a> { } fn slice(&self, start: uint, end: uint) -> String { - String::from_chars(self.chars[start..end]) + self.chars[start..end].iter().cloned().collect() } } diff --git a/src/libregex/test/bench.rs b/src/libregex/test/bench.rs index 0c204f759e6ad..17521ff7ea54b 100644 --- a/src/libregex/test/bench.rs +++ b/src/libregex/test/bench.rs @@ -9,8 +9,9 @@ // 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}; @@ -22,30 +23,30 @@ fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { 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::(), + repeat("a").take(n).collect::()).as_slice()).unwrap(); + let text = repeat("a").take(n).collect::(); 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::()); 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::()); 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::()); bench_assert_match(b, re, text.as_slice()); } @@ -53,7 +54,7 @@ fn match_class(b: &mut Bencher) { 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::()); bench_assert_match(b, re, text.as_slice()); } @@ -77,7 +78,7 @@ fn anchored_literal_short_non_match(b: &mut Bencher) { #[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::(); b.iter(|| re.is_match(text.as_slice())); } @@ -91,7 +92,7 @@ fn anchored_literal_short_match(b: &mut Bencher) { #[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::(); b.iter(|| re.is_match(text.as_slice())); } @@ -154,7 +155,7 @@ fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") } 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::>(); for (i, b) in bytes.iter_mut().enumerate() { diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 3edcd0b515641..35c29f646e4a0 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -1782,9 +1782,9 @@ impl LintPass for Stability { 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); } diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 6782b3a74813e..2a670b308b6b2 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -1308,7 +1308,7 @@ fn encode_info_for_item(ecx: &EncodeContext, } } } - 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); diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index da1bd09ceffdd..c2992a81d2083 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -25,7 +25,7 @@ use middle::ty::*; 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}; @@ -76,7 +76,7 @@ impl<'a> fmt::Show for Matrix<'a> { }).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::(); try!(write!(f, "{}\n", br)); for row in pretty_printed_matrix.into_iter() { try!(write!(f, "+")); diff --git a/src/librustc/middle/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs index 2f62858071f6a..3d3eac7b6ed9f 100644 --- a/src/librustc/middle/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -1043,7 +1043,6 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { ident: ty_param.ident, id: ty_param.id, bounds: bounds, - unbound: ty_param.unbound.clone(), default: ty_param.default.clone(), span: ty_param.span, } @@ -1063,7 +1062,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { // 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(); @@ -1087,7 +1086,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { path: new_path, ref_id: tr.ref_id, } - }) + }, modifier) } } }) diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index 6f63ae166fe41..730da26eda3dc 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -122,7 +122,7 @@ impl<'v> Visitor<'v> for ParentVisitor { // 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) => { @@ -328,7 +328,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { // 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) => { @@ -1178,7 +1178,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { } } - ast::ItemTrait(_, _, _, _, ref methods) => { + ast::ItemTrait(_, _, _, ref methods) => { for m in methods.iter() { match *m { ast::ProvidedMethod(ref m) => { @@ -1242,7 +1242,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> { ast::ItemStruct(ref def, _) => check_struct(&**def), - ast::ItemTrait(_, _, _, _, ref methods) => { + ast::ItemTrait(_, _, _, ref methods) => { for m in methods.iter() { match *m { ast::RequiredMethod(..) => {} @@ -1306,7 +1306,7 @@ impl<'a, 'tcx> VisiblePrivateTypesVisitor<'a, 'tcx> { 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; @@ -1349,7 +1349,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for VisiblePrivateTypesVisitor<'a, 'tcx> { // 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 } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 22dea3be1d4b6..4feafff3b9211 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -105,7 +105,7 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> { 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; @@ -232,7 +232,9 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> { } } - 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| { diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 232646f64a7d1..617be82701a09 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -4740,7 +4740,7 @@ pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId) 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() diff --git a/src/librustc_back/arm.rs b/src/librustc_back/arm.rs index ea4d5c820f8b8..7e28cd699a1a6 100644 --- a/src/librustc_back/arm.rs +++ b/src/librustc_back/arm.rs @@ -26,7 +26,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -34,7 +34,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -42,7 +42,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -50,7 +50,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -58,7 +58,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -66,7 +66,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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() } }, diff --git a/src/librustc_back/mips.rs b/src/librustc_back/mips.rs index 322f001c31e1b..bc7732157cefe 100644 --- a/src/librustc_back/mips.rs +++ b/src/librustc_back/mips.rs @@ -21,7 +21,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -29,7 +29,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -37,7 +37,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -45,7 +45,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -53,7 +53,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -61,7 +61,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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() } }, diff --git a/src/librustc_back/mipsel.rs b/src/librustc_back/mipsel.rs index e7ce5b0a429bc..3eea0a0dba405 100644 --- a/src/librustc_back/mipsel.rs +++ b/src/librustc_back/mipsel.rs @@ -21,7 +21,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -29,7 +29,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -37,7 +37,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -45,7 +45,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -53,7 +53,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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 => { @@ -61,7 +61,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs -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() } }, diff --git a/src/librustc_back/target/arm_apple_ios.rs b/src/librustc_back/target/arm_apple_ios.rs index 8be98a517757f..8bb64eae625f4 100644 --- a/src/librustc_back/target/arm_apple_ios.rs +++ b/src/librustc_back/target/arm_apple_ios.rs @@ -16,7 +16,7 @@ pub fn target() -> Target { -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(), diff --git a/src/librustc_back/target/arm_linux_androideabi.rs b/src/librustc_back/target/arm_linux_androideabi.rs index 97bc747916d03..0a5aa56055e1b 100644 --- a/src/librustc_back/target/arm_linux_androideabi.rs +++ b/src/librustc_back/target/arm_linux_androideabi.rs @@ -24,7 +24,7 @@ pub fn target() -> Target { -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(), diff --git a/src/librustc_back/target/arm_unknown_linux_gnueabi.rs b/src/librustc_back/target/arm_unknown_linux_gnueabi.rs index aecab18826419..985af35e1454c 100644 --- a/src/librustc_back/target/arm_unknown_linux_gnueabi.rs +++ b/src/librustc_back/target/arm_unknown_linux_gnueabi.rs @@ -17,7 +17,7 @@ pub fn target() -> Target { -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(), diff --git a/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs b/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs index 305862d357a49..3cf0c31282052 100644 --- a/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs +++ b/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs @@ -17,7 +17,7 @@ pub fn target() -> Target { -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(), diff --git a/src/librustc_back/target/i386_apple_ios.rs b/src/librustc_back/target/i386_apple_ios.rs index fe336601a81ac..45669bc958599 100644 --- a/src/librustc_back/target/i386_apple_ios.rs +++ b/src/librustc_back/target/i386_apple_ios.rs @@ -15,7 +15,7 @@ pub fn target() -> Target { 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(), diff --git a/src/librustc_back/target/i686_apple_darwin.rs b/src/librustc_back/target/i686_apple_darwin.rs index bd3dd3246aa6d..feef5b98dcbcf 100644 --- a/src/librustc_back/target/i686_apple_darwin.rs +++ b/src/librustc_back/target/i686_apple_darwin.rs @@ -18,7 +18,7 @@ pub fn target() -> Target { 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(), diff --git a/src/librustc_back/target/mips_unknown_linux_gnu.rs b/src/librustc_back/target/mips_unknown_linux_gnu.rs index 45e02ecb98ca6..c8c5ddcbd0d00 100644 --- a/src/librustc_back/target/mips_unknown_linux_gnu.rs +++ b/src/librustc_back/target/mips_unknown_linux_gnu.rs @@ -16,7 +16,7 @@ pub fn target() -> Target { -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(), diff --git a/src/librustc_back/target/mipsel_unknown_linux_gnu.rs b/src/librustc_back/target/mipsel_unknown_linux_gnu.rs index 1ba99b167c30a..3571f7b26c021 100644 --- a/src/librustc_back/target/mipsel_unknown_linux_gnu.rs +++ b/src/librustc_back/target/mipsel_unknown_linux_gnu.rs @@ -16,7 +16,7 @@ pub fn target() -> Target { -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(), diff --git a/src/librustc_back/target/x86_64_apple_darwin.rs b/src/librustc_back/target/x86_64_apple_darwin.rs index 4e958d73a39da..07e6cdfed2c67 100644 --- a/src/librustc_back/target/x86_64_apple_darwin.rs +++ b/src/librustc_back/target/x86_64_apple_darwin.rs @@ -17,7 +17,7 @@ pub fn target() -> Target { 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(), diff --git a/src/librustc_back/target/x86_64_pc_windows_gnu.rs b/src/librustc_back/target/x86_64_pc_windows_gnu.rs index 9247e1da0a58d..6ca74eb7fc07d 100644 --- a/src/librustc_back/target/x86_64_pc_windows_gnu.rs +++ b/src/librustc_back/target/x86_64_pc_windows_gnu.rs @@ -19,7 +19,7 @@ pub fn target() -> Target { 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(), diff --git a/src/librustc_back/target/x86_64_unknown_dragonfly.rs b/src/librustc_back/target/x86_64_unknown_dragonfly.rs index 75dbff9428b3e..bff3eaf6bc8fa 100644 --- a/src/librustc_back/target/x86_64_unknown_dragonfly.rs +++ b/src/librustc_back/target/x86_64_unknown_dragonfly.rs @@ -16,7 +16,7 @@ pub fn target() -> Target { 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(), diff --git a/src/librustc_back/target/x86_64_unknown_freebsd.rs b/src/librustc_back/target/x86_64_unknown_freebsd.rs index 37801f3bf2519..8d5603a3878db 100644 --- a/src/librustc_back/target/x86_64_unknown_freebsd.rs +++ b/src/librustc_back/target/x86_64_unknown_freebsd.rs @@ -16,7 +16,7 @@ pub fn target() -> Target { 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(), diff --git a/src/librustc_back/target/x86_64_unknown_linux_gnu.rs b/src/librustc_back/target/x86_64_unknown_linux_gnu.rs index ac04e6e14ba5c..e0a67cd62504c 100644 --- a/src/librustc_back/target/x86_64_unknown_linux_gnu.rs +++ b/src/librustc_back/target/x86_64_unknown_linux_gnu.rs @@ -16,7 +16,7 @@ pub fn target() -> Target { 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(), diff --git a/src/librustc_back/x86.rs b/src/librustc_back/x86.rs index 21c4fd424748f..52c07165900a9 100644 --- a/src/librustc_back/x86.rs +++ b/src/librustc_back/x86.rs @@ -22,7 +22,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) "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() } @@ -30,7 +30,7 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) "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() } diff --git a/src/librustc_back/x86_64.rs b/src/librustc_back/x86_64.rs index 88cd6743192fd..cbb288a533d6a 100644 --- a/src/librustc_back/x86_64.rs +++ b/src/librustc_back/x86_64.rs @@ -19,42 +19,42 @@ pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs 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() } diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index e2791aff14e49..e20404bf63891 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -540,7 +540,7 @@ pub fn monitor(f: F) { 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::() { let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None); diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index c168709eec5b9..7f01bf087381b 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -345,9 +345,6 @@ impl Rib { #[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 } @@ -462,6 +459,22 @@ impl ImportResolution { target.unwrap().shadowable } + + fn set_target_and_id(&mut self, + namespace: Namespace, + target: Option, + 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. @@ -1493,7 +1506,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ItemImpl(_, _, Some(_), _, _) => parent, - ItemTrait(_, _, _, _, ref items) => { + ItemTrait(_, _, _, ref items) => { let name_bindings = self.add_child(name, parent.clone(), @@ -1719,11 +1732,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { view_path.span, id, is_public, - if shadowable == Shadowable::Never { - Shadowable::Glob - } else { - shadowable - }); + shadowable); } } } @@ -2712,64 +2721,45 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // 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( @@ -2825,7 +2815,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // 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, @@ -2851,12 +2842,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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 { @@ -2876,8 +2866,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // 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 { @@ -2885,8 +2878,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // 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; @@ -2908,8 +2904,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // 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, @@ -2919,8 +2914,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } // 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_, @@ -2965,41 +2959,39 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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( @@ -3019,6 +3011,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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 \ @@ -4008,6 +4004,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } } + /// Searches the current set of local scopes and + /// applies translations for closures. fn search_ribs(&self, ribs: &[Rib], name: Name, @@ -4029,6 +4027,27 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { None } + /// Searches the current set of local scopes for labels. + /// Stops after meeting a closure. + fn search_label(&self, name: Name) -> Option { + 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"); @@ -4093,7 +4112,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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); @@ -4114,13 +4133,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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. @@ -4368,12 +4380,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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 => {} @@ -4395,7 +4401,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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(..) => {} @@ -5848,8 +5854,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { 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, diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 513b955da3f58..99e11bf520205 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -98,7 +98,7 @@ impl SharedEmitter { } 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) => { @@ -123,7 +123,7 @@ impl Emitter for SharedEmitter { 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, @@ -915,7 +915,7 @@ fn run_work_multithreaded(sess: &Session, 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); diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index f491bc84b62c4..51ea0af8e10ea 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -636,7 +636,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { 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); } } @@ -710,7 +710,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { // 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(..) => { @@ -763,37 +763,38 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } fn process_path(&mut self, - ex: &ast::Expr, - path: &ast::Path) { + id: NodeId, + span: Span, + path: &ast::Path, + ref_kind: Option) { 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); @@ -828,34 +829,31 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } 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, @@ -982,18 +980,19 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } }; 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, _) => { @@ -1052,7 +1051,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { &**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) => { @@ -1076,7 +1075,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { 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); } } @@ -1162,8 +1161,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { } 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) { @@ -1184,7 +1183,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { // '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, }; @@ -1308,7 +1307,10 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { // 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), @@ -1405,46 +1407,50 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { 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 { - "".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 { + "".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); diff --git a/src/librustc_trans/save/recorder.rs b/src/librustc_trans/save/recorder.rs index b2dd9218f1797..f62073e54e6d9 100644 --- a/src/librustc_trans/save/recorder.rs +++ b/src/librustc_trans/save/recorder.rs @@ -61,7 +61,7 @@ macro_rules! svec { }) } -#[deriving(Copy)] +#[deriving(Copy,Show)] pub enum Row { Variable, Enum, diff --git a/src/librustc_trans/save/span_utils.rs b/src/librustc_trans/save/span_utils.rs index e9d862d3781bb..244d0476832bd 100644 --- a/src/librustc_trans/save/span_utils.rs +++ b/src/librustc_trans/save/span_utils.rs @@ -294,8 +294,8 @@ impl<'a> SpanUtils<'a> { } pub fn sub_span_after_keyword(&self, - span: Span, - keyword: keywords::Keyword) -> Option { + span: Span, + keyword: keywords::Keyword) -> Option { let mut toks = self.retokenise_span(span); loop { let ts = toks.real_token(); diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index dd5809730d6f5..f0d738d839d7a 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -983,23 +983,14 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef, llargs: &[ValueRef], fn_ty: Ty<'tcx>, - call_info: Option, - // FIXME(15064) is_lang_item is a horrible hack, please remove it - // at the soonest opportunity. - is_lang_item: bool) + call_info: Option) -> (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 => { @@ -1554,8 +1545,7 @@ pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>) } // 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 diff --git a/src/librustc_trans/trans/builder.rs b/src/librustc_trans/trans/builder.rs index 1b9c9d221b909..5249f59d78f75 100644 --- a/src/librustc_trans/trans/builder.rs +++ b/src/librustc_trans/trans/builder.rs @@ -501,7 +501,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { 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); @@ -512,7 +512,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { 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); diff --git a/src/librustc_trans/trans/callee.rs b/src/librustc_trans/trans/callee.rs index e3fe749b49003..a159cda9fbaed 100644 --- a/src/librustc_trans/trans/callee.rs +++ b/src/librustc_trans/trans/callee.rs @@ -779,8 +779,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, llfn, llargs[], callee_ty, - call_info, - dest.is_none()); + call_info); bcx = b; llresult = llret; diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index 1f61fed3998d1..b15b75c6715b7 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -190,8 +190,8 @@ pub fn validate_substs(substs: &Substs) { } // 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. diff --git a/src/librustc_trans/trans/glue.rs b/src/librustc_trans/trans/glue.rs index e276543264b0a..e0a878c8261ef 100644 --- a/src/librustc_trans/trans/glue.rs +++ b/src/librustc_trans/trans/glue.rs @@ -292,7 +292,7 @@ fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, 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 diff --git a/src/librustc_trans/trans/value.rs b/src/librustc_trans/trans/value.rs index 4f9b8c5ea37c9..9e959ce4221e7 100644 --- a/src/librustc_trans/trans/value.rs +++ b/src/librustc_trans/trans/value.rs @@ -20,7 +20,7 @@ pub struct Value(pub ValueRef); 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 } } @@ -37,7 +37,7 @@ impl Value { pub fn get_parent(self) -> Option { unsafe { match llvm::LLVMGetInstructionParent(self.get()) { - p if p.is_not_null() => Some(BasicBlock(p)), + p if !p.is_null() => Some(BasicBlock(p)), _ => None } } @@ -77,7 +77,7 @@ impl Value { pub fn get_first_use(self) -> Option { unsafe { match llvm::LLVMGetFirstUse(self.get()) { - u if u.is_not_null() => Some(Use(u)), + u if !u.is_null() => Some(Use(u)), _ => None } } @@ -119,7 +119,7 @@ impl Value { /// 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() } } } @@ -142,7 +142,7 @@ impl Use { pub fn get_next_use(self) -> Option { unsafe { match llvm::LLVMGetNextUse(self.get()) { - u if u.is_not_null() => Some(Use(u)), + u if !u.is_null() => Some(Use(u)), _ => None } } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 81e6ec4df5627..d6f1f5fedc581 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -164,10 +164,16 @@ pub fn opt_ast_region_to_region<'tcx, AC: AstConv<'tcx>, RS: RegionScope>( 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 { @@ -1626,7 +1632,7 @@ pub fn partition_bounds<'a>(tcx: &ty::ctxt, 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) { @@ -1664,6 +1670,7 @@ pub fn partition_bounds<'a>(tcx: &ty::ctxt, } trait_bounds.push(b); } + ast::TraitTyParamBound(_, ast::TraitBoundModifier::Maybe) => {} ast::RegionTyParamBound(ref l) => { region_bounds.push(l); } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index fb23ad8e340ce..c8c8211f29253 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -673,7 +673,7 @@ pub fn check_item(ccx: &CrateCtxt, it: &ast::Item) { } } - 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 { diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 793c5f5b4a058..8d07f1e435503 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -259,7 +259,7 @@ fn collect_trait_methods<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, 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() { @@ -627,11 +627,6 @@ pub fn ensure_no_ty_param_bounds(ccx: &CrateCtxt, ast::RegionTyParamBound(..) => { } } } - - match ty_param.unbound { - Some(_) => { warn = true; } - None => { } - } } if warn { @@ -1146,7 +1141,7 @@ pub fn convert(ccx: &CrateCtxt, it: &ast::Item) { 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={}", @@ -1338,13 +1333,12 @@ pub fn trait_def_of_item<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, 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( @@ -1367,7 +1361,6 @@ pub fn trait_def_of_item<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, token::SELF_KEYWORD_NAME, self_param_ty, bounds.as_slice(), - unbound, it.span); let substs = mk_item_substs(ccx, &ty_generics); @@ -1683,29 +1676,37 @@ fn ty_generics_for_fn_or_method<'tcx,AC>( 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, 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); @@ -1717,7 +1718,7 @@ fn add_unsized_bound<'tcx,AC>(this: &AC, 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 => {} } } @@ -1807,7 +1808,7 @@ fn ty_generics<'tcx,AC>(this: &AC, 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, @@ -1880,7 +1881,7 @@ fn ty_generics<'tcx,AC>(this: &AC, 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; } }; @@ -1978,7 +1979,6 @@ fn get_or_create_type_parameter_def<'tcx,AC>(this: &AC, param.ident.name, param_ty, param.bounds[], - ¶m.unbound, param.span); let default = match param.default { None => None, @@ -2023,7 +2023,6 @@ fn compute_bounds<'tcx,AC>(this: &AC, name_of_bounded_thing: ast::Name, param_ty: ty::ParamTy, ast_bounds: &[ast::TyParamBound], - unbound: &Option, span: Span) -> ty::ParamBounds<'tcx> where AC: AstConv<'tcx> { @@ -2032,11 +2031,9 @@ fn compute_bounds<'tcx,AC>(this: &AC, param_ty, ast_bounds); - add_unsized_bound(this, - unbound, &mut param_bounds.builtin_bounds, - "type parameter", + ast_bounds, span); check_bounds_compatible(this.tcx(), diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index bdd8c7c3da7c0..30869186ba5e9 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -353,7 +353,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for TermsContext<'a, '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); diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index cdc51bb801c58..3eda39f54a997 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -163,13 +163,12 @@ pub fn build_external_trait(cx: &DocContext, tcx: &ty::ctxt, } }); 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 } } @@ -328,7 +327,7 @@ fn build_impl(cx: &DocContext, tcx: &ty::ctxt, 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!(), } }), diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 0308194527e95..b7845f23be298 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -458,8 +458,6 @@ pub struct TyParam { pub did: ast::DefId, pub bounds: Vec, pub default: Option, - /// An optional default bound on the parameter which is unbound, like `Sized?` - pub default_unbound: Option } impl Clean for ast::TyParam { @@ -469,7 +467,6 @@ impl Clean 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) } } } @@ -478,13 +475,12 @@ impl<'tcx> Clean for ty::TypeParameterDef<'tcx> { 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 } } } @@ -492,14 +488,14 @@ impl<'tcx> Clean for ty::TypeParameterDef<'tcx> { #[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)] pub enum TyParamBound { RegionBound(Lifetime), - TraitBound(PolyTrait) + TraitBound(PolyTrait, ast::TraitBoundModifier) } impl Clean 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), } } } @@ -600,7 +596,7 @@ impl Clean for ty::BuiltinBound { did: did, }, lifetimes: vec![] - }) + }, ast::TraitBoundModifier::None) } } @@ -648,37 +644,20 @@ impl<'tcx> Clean for ty::TraitRef<'tcx> { 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, Option)> for ty::ParamBounds<'tcx> { - fn clean(&self, cx: &DocContext) -> (Vec, Option) { +impl<'tcx> Clean> for ty::ParamBounds<'tcx> { + fn clean(&self, cx: &DocContext) -> Vec { 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 } } @@ -689,7 +668,7 @@ impl<'tcx> Clean>> for subst::Substs<'tcx> { 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} } } @@ -1047,8 +1026,6 @@ pub struct Trait { pub items: Vec, pub generics: Generics, pub bounds: Vec, - /// An optional default bound not required for `Self`, like `Sized?` - pub default_unbound: Option } impl Clean for doctree::Trait { @@ -1065,7 +1042,6 @@ impl Clean 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) }), } } @@ -2412,7 +2388,6 @@ impl Clean for ty::AssociatedType { }, bounds: vec![], default: None, - default_unbound: None }), visibility: None, def_id: self.def_id, diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index 7f7c055062aaa..251ce5aefeb71 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -178,7 +178,6 @@ pub struct Trait { pub whence: Span, pub vis: ast::Visibility, pub stab: Option, - pub default_unbound: Option // FIXME(tomjakubowski) } pub struct Impl { diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 25c4f4e01b620..585183e2af75e 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -97,9 +97,6 @@ impl fmt::Show for clean::Generics { 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 { @@ -123,7 +120,7 @@ impl<'a> fmt::Show for WhereClause<'a> { if gens.where_predicates.len() == 0 { return Ok(()); } - try!(f.write(" where ".as_bytes())); + try!(f.write(" where ".as_bytes())); for (i, pred) in gens.where_predicates.iter().enumerate() { if i > 0 { try!(f.write(", ".as_bytes())); @@ -149,6 +146,7 @@ impl<'a> fmt::Show for WhereClause<'a> { } } } + try!(f.write("".as_bytes())); Ok(()) } } @@ -182,8 +180,12 @@ impl fmt::Show for clean::TyParamBound { 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) } } } @@ -458,12 +460,15 @@ impl fmt::Show for clean::Type { 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()); } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 304dbe201e8fd..bfb03cb2589c2 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1679,9 +1679,6 @@ fn item_function(w: &mut fmt::Formatter, it: &clean::Item, 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(' '); diff --git a/src/librustdoc/html/static/main.css b/src/librustdoc/html/static/main.css index dc62273364c20..9d4f341a30e25 100644 --- a/src/librustdoc/html/static/main.css +++ b/src/librustdoc/html/static/main.css @@ -306,6 +306,11 @@ nav.sub { 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; } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 4374ce5deef4e..e71711aa8d6e7 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -322,7 +322,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { }; 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, @@ -334,7 +334,6 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { whence: item.span, vis: item.vis, stab: self.stability(item.id), - default_unbound: def_ub.clone() }; om.traits.push(t); }, diff --git a/src/libserialize/base64.rs b/src/libserialize/base64.rs index f1dffa55bb01a..fae73cc834fd2 100644 --- a/src/libserialize/base64.rs +++ b/src/libserialize/base64.rs @@ -392,10 +392,10 @@ mod tests { #[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::()); assert_eq!(v.to_base64(STANDARD) .from_base64() diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 830d96fe172bc..3f0d59c319a69 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -29,7 +29,7 @@ //! * `String`: equivalent to rust's `String` //! * `Array`: equivalent to rust's `Vec`, but also allowing objects of different types in the //! same array -//! * `Object`: equivalent to rust's `Treemap` +//! * `Object`: equivalent to rust's `BTreeMap` //! * `Null` //! //! An object is a series of string keys mapping to values, in `"key": value` format. @@ -2517,7 +2517,7 @@ mod tests { #[test] fn test_from_str_trait() { let s = "null"; - assert!(::std::str::from_str::(s).unwrap() == from_str(s).unwrap()); + assert!(s.parse::().unwrap() == s.parse().unwrap()); } #[test] @@ -3729,8 +3729,8 @@ mod tests { 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) }; @@ -3762,8 +3762,8 @@ mod tests { 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); diff --git a/src/libstd/bitflags.rs b/src/libstd/bitflags.rs index 5dd76047779a0..a46b8a9ad9024 100644 --- a/src/libstd/bitflags.rs +++ b/src/libstd/bitflags.rs @@ -104,6 +104,10 @@ /// - `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` diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs index ffe19203769d4..f28abcc10cfd8 100644 --- a/src/libstd/c_str.rs +++ b/src/libstd/c_str.rs @@ -537,7 +537,8 @@ pub unsafe fn from_c_multistring(buf: *const libc::c_char, #[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; diff --git a/src/libstd/c_vec.rs b/src/libstd/c_vec.rs index f4338815f759b..0aa51ee66ed63 100644 --- a/src/libstd/c_vec.rs +++ b/src/libstd/c_vec.rs @@ -40,7 +40,7 @@ use mem; 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; diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index d749cd77cef2d..7b7473b2c993c 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -264,27 +264,35 @@ fn test_resize_policy() { /// } /// ``` /// -/// 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)] @@ -888,8 +896,8 @@ impl, V, S, H: Hasher> HashMap { /// } /// ``` #[unstable = "matches collection reform specification, waiting for dust to settle"] - pub fn iter(&self) -> Entries { - Entries { inner: self.table.iter() } + pub fn iter(&self) -> Iter { + Iter { inner: self.table.iter() } } /// An iterator visiting all key-value pairs in arbitrary order, @@ -1305,8 +1313,8 @@ impl + Eq, Sized? Q, V, S, H: Hasher> IndexMut for HashMap { - inner: table::Entries<'a, K, V> +pub struct Iter<'a, K: 'a, V: 'a> { + inner: table::Iter<'a, K, V> } /// HashMap mutable values iterator @@ -1326,12 +1334,12 @@ pub struct IntoIter { /// 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 @@ -1373,7 +1381,7 @@ enum VacantEntryState { NoElem(EmptyBucket), } -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) { self.inner.size_hint() } } diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index 3ae3a8ffbad3b..f76b8ac3326f5 100644 --- a/src/libstd/collections/hash/table.rs +++ b/src/libstd/collections/hash/table.rs @@ -23,7 +23,7 @@ use num::{Int, UnsignedInt}; 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}; @@ -657,8 +657,8 @@ impl RawTable { } } - pub fn iter(&self) -> Entries { - Entries { + pub fn iter(&self) -> Iter { + Iter { iter: self.raw_buckets(), elems_left: self.size(), } @@ -770,7 +770,7 @@ impl<'a, K, V> Iterator<(K, V)> for RevMoveBuckets<'a, K, V> { } /// 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, } @@ -793,7 +793,7 @@ pub struct Drain<'a, K: 'a, V: 'a> { 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; diff --git a/src/libstd/comm/mod.rs b/src/libstd/comm/mod.rs index c85bea87218ff..a405627aecc45 100644 --- a/src/libstd/comm/mod.rs +++ b/src/libstd/comm/mod.rs @@ -181,7 +181,7 @@ // 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 @@ -316,7 +316,6 @@ use core::prelude::*; pub use self::TryRecvError::*; pub use self::TrySendError::*; -use self::Flavor::*; use alloc::arc::Arc; use core::kinds; @@ -337,7 +336,8 @@ macro_rules! test { 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 } } @@ -478,7 +478,7 @@ impl UnsafeFlavor for Receiver { #[unstable] pub fn channel() -> (Sender, Receiver) { 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. @@ -518,7 +518,7 @@ pub fn channel() -> (Sender, Receiver) { of channel that is is creating"] pub fn sync_channel(bound: uint) -> (SyncSender, Receiver) { 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))) } //////////////////////////////////////////////////////////////////////////////// @@ -592,7 +592,7 @@ impl Sender { #[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() { @@ -600,7 +600,7 @@ impl Sender { } 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) @@ -618,13 +618,13 @@ impl Sender { } } } - 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; @@ -635,42 +635,42 @@ impl Sender { impl Clone for Sender { fn clone(&self) -> Sender { 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)) } } @@ -678,10 +678,10 @@ impl Clone for Sender { impl Drop for Sender { 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!(), } } } @@ -827,7 +827,7 @@ impl Receiver { pub fn try_recv(&self) -> Result { 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), @@ -835,7 +835,7 @@ impl Receiver { 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), @@ -843,14 +843,14 @@ impl Receiver { 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), @@ -881,7 +881,7 @@ impl Receiver { pub fn recv_opt(&self) -> Result { 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!(), @@ -889,7 +889,7 @@ impl Receiver { 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!(), @@ -897,14 +897,14 @@ impl Receiver { 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()); @@ -924,22 +924,22 @@ impl select::Packet for Receiver { 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() }; } }; @@ -953,24 +953,24 @@ impl select::Packet for Receiver { 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) }; } }; @@ -985,14 +985,14 @@ impl select::Packet for Receiver { 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() }, }; @@ -1015,10 +1015,10 @@ impl<'a, T: Send> Iterator for Messages<'a, T> { impl Drop for Receiver { 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(); }, } } } @@ -1047,7 +1047,7 @@ unsafe impl kinds::Sync for RacyCell { } // Oh dear #[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 { diff --git a/src/libstd/comm/shared.rs b/src/libstd/comm/shared.rs index 1022694e634f6..3f23ec5dc6659 100644 --- a/src/libstd/comm/shared.rs +++ b/src/libstd/comm/shared.rs @@ -86,7 +86,7 @@ impl Packet { // 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 @@ -435,7 +435,7 @@ impl Packet { // 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 diff --git a/src/libstd/comm/sync.rs b/src/libstd/comm/sync.rs index 88338849965b0..82ec1814ebde7 100644 --- a/src/libstd/comm/sync.rs +++ b/src/libstd/comm/sync.rs @@ -121,9 +121,9 @@ fn wait<'a, 'b, T: Send>(lock: &'a Mutex>, 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 @@ -161,7 +161,7 @@ impl Packet { fn acquire_send_slot(&self) -> MutexGuard> { 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; @@ -202,7 +202,7 @@ impl Packet { } pub fn try_send(&self, t: T) -> Result<(), super::TrySendError> { - 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() { @@ -239,7 +239,7 @@ impl Packet { // When reading this, remember that there can only ever be one receiver at // time. pub fn recv(&self) -> Result { - 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. @@ -258,7 +258,7 @@ impl Packet { } pub fn try_recv(&self) -> Result { - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); // Easy cases first if guard.disconnected { return Err(Disconnected) } @@ -315,7 +315,7 @@ impl Packet { } // 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) { @@ -326,7 +326,7 @@ impl Packet { } 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; @@ -372,14 +372,14 @@ impl Packet { // 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 { @@ -397,7 +397,7 @@ impl Packet { // // 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) => { @@ -413,7 +413,7 @@ impl Packet { impl Drop for Packet { 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()); } diff --git a/src/libstd/error.rs b/src/libstd/error.rs index cd7d9aacc9010..9a46a500a4b47 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -81,6 +81,7 @@ use prelude::*; use str::Utf8Error; +use string::{FromUtf8Error, FromUtf16Error}; /// Base functionality for all errors in Rust. pub trait Error: Send { @@ -117,3 +118,12 @@ impl Error for Utf8Error { fn detail(&self) -> Option { Some(self.to_string()) } } + +impl Error for FromUtf8Error { + fn description(&self) -> &str { "invalid utf-8" } + fn detail(&self) -> Option { Some(self.to_string()) } +} + +impl Error for FromUtf16Error { + fn description(&self) -> &str { "invalid utf-16" } +} diff --git a/src/libstd/hash.rs b/src/libstd/hash.rs index 52e3c718b2d56..737fef23c7466 100644 --- a/src/libstd/hash.rs +++ b/src/libstd/hash.rs @@ -79,7 +79,7 @@ impl RandomSipHasher { /// 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 { diff --git a/src/libstd/io/extensions.rs b/src/libstd/io/extensions.rs index c1f1a5b786985..e8765e3c2317e 100644 --- a/src/libstd/io/extensions.rs +++ b/src/libstd/io/extensions.rs @@ -22,7 +22,7 @@ use num::Int; 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}; diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index f2db2875ebf2c..caa6590bb2821 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -1148,6 +1148,19 @@ mod test { 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(); diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 20b1162d859c7..79327a29615ae 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -400,8 +400,8 @@ impl<'a> Buffer for BufReader<'a> { 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; diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index e1f5efae79fc7..7a25360e695e4 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -935,7 +935,7 @@ impl<'a> Reader for &'a mut (Reader+'a) { // API yet. If so, it should be a method on Vec. unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec, start: uint, end: uint) -> &'a mut [T] { use raw::Slice; - use ptr::RawPtr; + use ptr::PtrExt; assert!(start <= end); assert!(end <= v.capacity()); @@ -1724,7 +1724,7 @@ pub fn standard_error(kind: IoErrorKind) -> IoError { /// 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, @@ -1736,7 +1736,7 @@ pub enum FileMode { /// 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, @@ -1959,8 +1959,8 @@ impl fmt::Show for FilePermission { #[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)] diff --git a/src/libstd/io/net/pipe.rs b/src/libstd/io/net/pipe.rs index 4afc72cde711e..93f37a8c98ff8 100644 --- a/src/libstd/io/net/pipe.rs +++ b/src/libstd/io/net/pipe.rs @@ -269,7 +269,7 @@ mod tests { 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; diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index 6adb5387f2ef5..24cf06973cc69 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -484,9 +484,12 @@ impl sys_common::AsInner for TcpAcceptor { 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)] diff --git a/src/libstd/io/net/udp.rs b/src/libstd/io/net/udp.rs index 5bf47dceb5a0e..1431067d4c6a3 100644 --- a/src/libstd/io/net/udp.rs +++ b/src/libstd/io/net/udp.rs @@ -250,9 +250,9 @@ impl Writer for UdpStream { 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)] diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 93aa627ffba13..b127507f048d2 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -745,8 +745,10 @@ mod tests { 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; @@ -1205,6 +1207,7 @@ mod tests { #[test] #[cfg(windows)] fn env_map_keys_ci() { + use c_str::ToCStr; use super::EnvKey; let mut cmd = Command::new(""); cmd.env("path", "foo"); diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 6bd721599f341..6c8e4eea40fdc 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -146,7 +146,7 @@ impl StdinReader { /// ``` pub fn lock<'a>(&'a mut self) -> StdinReaderGuard<'a> { StdinReaderGuard { - inner: self.inner.lock() + inner: self.inner.lock().unwrap() } } @@ -155,7 +155,7 @@ impl StdinReader { /// The read is performed atomically - concurrent read calls in other /// threads will not interleave with this one. pub fn read_line(&mut self) -> IoResult { - self.inner.lock().0.read_line() + self.inner.lock().unwrap().0.read_line() } /// Like `Buffer::read_until`. @@ -163,7 +163,7 @@ impl StdinReader { /// 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> { - self.inner.lock().0.read_until(byte) + self.inner.lock().unwrap().0.read_until(byte) } /// Like `Buffer::read_char`. @@ -171,13 +171,13 @@ impl StdinReader { /// The read is performed atomically - concurrent read calls in other /// threads will not interleave with this one. pub fn read_char(&mut self) -> IoResult { - 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 { - 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 @@ -185,23 +185,23 @@ impl Reader for StdinReader { // incur the costs of repeated locking). fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult { - 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) -> IoResult { - 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> { - 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 { - 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 { - self.inner.lock().0.read_be_uint_n(nbytes) + self.inner.lock().unwrap().0.read_be_uint_n(nbytes) } } diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index 43893ca012653..90d7c1388a196 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -280,7 +280,7 @@ mod test { 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() { diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index 7c8763979bb36..48ff1a364e93c 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -147,8 +147,10 @@ pub fn test_num(ten: T, two: T) where #[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; diff --git a/src/libstd/os.rs b/src/libstd/os.rs index ceb9a4102f635..989f44f7b8e42 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -46,7 +46,8 @@ use option::Option; 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}; @@ -730,7 +731,7 @@ fn real_args() -> Vec { 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 { @@ -1438,7 +1439,7 @@ mod tests { } 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::()); assert!(getenv(n.as_slice()).is_none()); diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index d941665f0482f..60f147eac9b2b 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -1239,7 +1239,7 @@ mod bench { extern crate test; use self::test::Bencher; use super::*; - use prelude::*; + use prelude::{Clone, GenericPath}; #[bench] fn join_home_dir(b: &mut Bencher) { diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 1d17ae987b208..879a96e802643 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -21,7 +21,7 @@ use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; 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}; @@ -777,7 +777,7 @@ impl Path { } } } 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() + diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs index d1540f98a2355..fc59f06ae6cf3 100644 --- a/src/libstd/prelude.rs +++ b/src/libstd/prelude.rs @@ -73,7 +73,7 @@ #[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}; diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index c590c0f575ee6..d4f72a53aec1b 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -18,10 +18,10 @@ //! 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 @@ -61,7 +61,7 @@ //! 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::(), rng.gen::()) //! } @@ -97,7 +97,7 @@ //! //! 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; @@ -183,7 +183,7 @@ //! // 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); @@ -257,7 +257,7 @@ impl StdRng { /// 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 @@ -307,28 +307,28 @@ pub fn weak_rng() -> XorShiftRng { } } -/// Controls how the task-local RNG is reseeded. -struct TaskRngReseeder; +/// Controls how the thread-local RNG is reseeded. +struct ThreadRngReseeder; -impl reseeding::Reseeder for TaskRngReseeder { +impl reseeding::Reseeder 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; +static THREAD_RNG_RESEED_THRESHOLD: uint = 32_768; +type ThreadRngInner = reseeding::ReseedingRng; -/// The task-local RNG. -pub struct TaskRng { - rng: Rc>, +/// The thread-local RNG. +pub struct ThreadRng { + rng: Rc>, } -/// 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::()`. +/// chaining style, e.g. `thread_rng().gen::()`. /// /// The RNG provided will reseed itself from the operating system /// after generating a certain amount of randomness. @@ -337,23 +337,23 @@ pub struct TaskRng { /// 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> = { + thread_local!(static THREAD_RNG_KEY: Rc> = { 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() } @@ -368,7 +368,7 @@ impl Rng for TaskRng { } } -/// 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. @@ -390,7 +390,7 @@ impl Rng for TaskRng { /// ``` #[inline] pub fn random() -> T { - task_rng().gen() + thread_rng().gen() } /// Randomly sample up to `amount` elements from an iterator. @@ -398,9 +398,9 @@ pub fn random() -> T { /// # 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); /// ``` @@ -420,7 +420,7 @@ pub fn sample, R: Rng>(rng: &mut R, #[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 } @@ -453,7 +453,7 @@ mod test { #[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); @@ -473,20 +473,20 @@ mod test { #[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::(); let b = r.gen::(); debug!("{}", (a, b)); @@ -494,14 +494,14 @@ mod test { #[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); @@ -509,7 +509,7 @@ mod test { #[test] fn test_gen_vec() { - let mut r = task_rng(); + let mut r = thread_rng(); assert_eq!(r.gen_iter::().take(0).count(), 0u); assert_eq!(r.gen_iter::().take(10).count(), 10u); assert_eq!(r.gen_iter::().take(16).count(), 16u); @@ -517,7 +517,7 @@ mod test { #[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] = &[]; @@ -526,7 +526,7 @@ mod test { #[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]; @@ -545,8 +545,8 @@ mod test { } #[test] - fn test_task_rng() { - let mut r = task_rng(); + fn test_thread_rng() { + let mut r = thread_rng(); r.gen::(); let mut v = [1i, 1, 1]; r.shuffle(&mut v); @@ -574,7 +574,7 @@ mod test { 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::>(); let small_sample = sample(&mut r, vals.iter(), 5); let large_sample = sample(&mut r, vals.iter(), vals.len() + 5); @@ -589,7 +589,7 @@ mod test { #[test] fn test_std_rng_seeded() { - let s = task_rng().gen_iter::().take(256).collect::>(); + let s = thread_rng().gen_iter::().take(256).collect::>(); 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), @@ -598,7 +598,7 @@ mod test { #[test] fn test_std_rng_reseed() { - let s = task_rng().gen_iter::().take(256).collect::>(); + let s = thread_rng().gen_iter::().take(256).collect::>(); let mut r: StdRng = SeedableRng::from_seed(s.as_slice()); let string1 = r.gen_ascii_chars().take(100).collect::(); diff --git a/src/libstd/rt/backtrace.rs b/src/libstd/rt/backtrace.rs index 775e9bb526f7c..3eeb0ad3968fe 100644 --- a/src/libstd/rt/backtrace.rs +++ b/src/libstd/rt/backtrace.rs @@ -60,19 +60,19 @@ mod test { 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"); } } diff --git a/src/libstd/rt/mod.rs b/src/libstd/rt/mod.rs index d64336569c6e9..e877dd5c6aab8 100644 --- a/src/libstd/rt/mod.rs +++ b/src/libstd/rt/mod.rs @@ -53,7 +53,7 @@ pub mod args; 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; @@ -137,9 +137,9 @@ fn lang_start(main: *const u8, argc: int, argv: *const *const u8) -> int { /// /// 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. diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index 98940a2b381c7..773322e4f57f1 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -36,7 +36,7 @@ use sys_common::stack; 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. @@ -50,14 +50,14 @@ pub struct Task { 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 { @@ -67,31 +67,31 @@ 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>, - /// 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, - /// The size of the stack for the spawned task + /// The size of the stack for the spawned thread pub stack_size: Option, } -/// 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>; -/// A handle to a blocked task. Usually this means having the Box -/// 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 +/// pointer by ownership, but if the thread is killable, a killer can steal it /// at any time. pub enum BlockedTask { Owned(Box), Shared(Arc), } -/// 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>, } @@ -101,7 +101,7 @@ pub struct BlockedTasks { } impl Task { - /// Creates a new uninitialized task. + /// Creates a new uninitialized thread. pub fn new(stack_bounds: Option<(uint, uint)>, stack_guard: Option) -> Task { Task { unwinder: Unwinder::new(), @@ -153,17 +153,17 @@ impl Task { }) } - /// 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()`. /// @@ -172,30 +172,30 @@ impl Task { /// 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, f: ||) -> Box { - 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::) { - 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 = Local::take(); match result { Ok(()) => task, @@ -203,13 +203,13 @@ impl 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) -> Box { if self.is_destroyed() { @@ -219,14 +219,14 @@ impl Task { } } - /// 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, result: Result) -> Box { // 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); @@ -235,15 +235,15 @@ impl Task { // 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 = Local::take(); task.state = Destroyed; @@ -253,7 +253,7 @@ impl Task { /// 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. // @@ -262,31 +262,31 @@ impl Task { // 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` object. Naturally, this looks like it violates // ownership semantics in that there may be two `Box` 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. // @@ -319,11 +319,11 @@ impl Task { 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() { @@ -342,15 +342,15 @@ impl Task { 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) { unsafe { @@ -362,21 +362,21 @@ impl Task { } } - /// 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 { if self.stack_guard != 0 { Some(self.stack_guard) @@ -385,9 +385,9 @@ impl Task { } } - /// 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; @@ -396,7 +396,7 @@ impl Task { 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); } } @@ -414,7 +414,7 @@ impl Iterator for BlockedTasks { } 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> { match self { Owned(task) => Some(task), @@ -427,7 +427,7 @@ impl BlockedTask { } } - /// 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()); @@ -438,12 +438,12 @@ impl BlockedTask { #[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) -> 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 { let arc = match self { Owned(task) => { @@ -543,7 +543,7 @@ mod test { drop(Task::new(None, None)); } - // Task blocking tests + // Thread blocking tests #[test] fn block_and_wake() { diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index 261a8335173d0..9b57dcc9e18bf 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -79,7 +79,7 @@ struct Exception { 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; @@ -106,14 +106,14 @@ thread_local! { static PANICKING: Cell = Cell::new(false) } /// /// * 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: F) -> Result<(), Box> { @@ -203,7 +203,7 @@ fn rust_exception_class() -> uw::_Unwind_Exception_Class { // _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 @@ -570,7 +570,7 @@ pub fn begin_unwind(msg: M, file_line: &(&'static str, uint)) -> // 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. @@ -593,7 +593,7 @@ fn begin_unwind_inner(msg: Box, file_line: &(&'static str, uint)) -> 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, @@ -621,7 +621,7 @@ fn begin_unwind_inner(msg: Box, file_line: &(&'static str, uint)) -> // 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() } } @@ -629,10 +629,10 @@ fn begin_unwind_inner(msg: Box, file_line: &(&'static str, uint)) -> 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. diff --git a/src/libstd/sync/atomic.rs b/src/libstd/sync/atomic.rs index 26778ef70b3ca..bdf947438f36b 100644 --- a/src/libstd/sync/atomic.rs +++ b/src/libstd/sync/atomic.rs @@ -180,7 +180,7 @@ impl Drop for AtomicOption { #[cfg(test)] mod test { - use prelude::*; + use prelude::{Some, None}; use super::*; #[test] diff --git a/src/libstd/sync/barrier.rs b/src/libstd/sync/barrier.rs index 6cdb199819aff..4091f0df39597 100644 --- a/src/libstd/sync/barrier.rs +++ b/src/libstd/sync/barrier.rs @@ -69,7 +69,7 @@ impl Barrier { /// 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 { @@ -77,7 +77,7 @@ impl Barrier { // 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; diff --git a/src/libstd/sync/condvar.rs b/src/libstd/sync/condvar.rs index f1940bfd829b7..15faf5be258f5 100644 --- a/src/libstd/sync/condvar.rs +++ b/src/libstd/sync/condvar.rs @@ -11,10 +11,11 @@ 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 /// @@ -44,18 +45,19 @@ use time::Duration; /// // 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 } unsafe impl Send for Condvar {} @@ -73,6 +75,7 @@ unsafe impl Sync for Condvar {} /// /// static CVAR: StaticCondvar = CONDVAR_INIT; /// ``` +#[unstable = "may be merged with Condvar in the future"] pub struct StaticCondvar { inner: sys::Condvar, mutex: AtomicUint, @@ -82,24 +85,16 @@ unsafe impl Send for StaticCondvar {} 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 { @@ -113,8 +108,8 @@ impl Condvar { /// 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. /// @@ -123,16 +118,24 @@ impl Condvar { /// 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(&self, mutex_guard: &T) { + #[stable] + pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) + -> LockResult> { unsafe { let me: &'static Condvar = &*(self as *const _); - me.inner.wait(mutex_guard) + me.inner.wait(guard) } } @@ -156,11 +159,11 @@ impl Condvar { // provide. There are also additional concerns about the unix-specific // implementation which may need to be addressed. #[allow(dead_code)] - fn wait_timeout(&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) } } @@ -171,6 +174,7 @@ impl Condvar { /// `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. @@ -180,6 +184,7 @@ impl Condvar { /// way. /// /// To wake up only one thread, see `notify_one()`. + #[stable] pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } } } @@ -194,13 +199,19 @@ impl StaticCondvar { /// notification. /// /// See `Condvar::wait`. - pub fn wait(&'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> { + 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) } } @@ -209,26 +220,31 @@ impl StaticCondvar { /// /// See `Condvar::wait_timeout`. #[allow(dead_code)] // may want to stabilize this later, see wait_timeout above - fn wait_timeout(&'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. @@ -237,6 +253,7 @@ impl StaticCondvar { /// 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() } @@ -288,12 +305,12 @@ mod tests { 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(); } } @@ -309,13 +326,13 @@ mod tests { 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(()); }); @@ -324,7 +341,7 @@ mod tests { 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); @@ -339,13 +356,15 @@ mod tests { 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(); } } @@ -357,15 +376,15 @@ mod tests { 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(); } } diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 7605a6a96a005..092acc7ff2569 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -19,14 +19,15 @@ 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; diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 4d2fbfc4055f4..52004bb4a8f5f 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -12,7 +12,7 @@ use prelude::*; 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 @@ -26,12 +26,23 @@ use sys_common::mutex as sys; /// /// # 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}; @@ -48,11 +59,14 @@ use sys_common::mutex as sys; /// 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(()); @@ -63,6 +77,36 @@ use sys_common::mutex as sys; /// /// 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 { // 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 @@ -93,14 +137,15 @@ unsafe impl Sync for Mutex { } /// 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: poison::Flag, } unsafe impl Sync for StaticMutex {} @@ -111,31 +156,27 @@ 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, - __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, + __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 Mutex { /// Creates a new mutex in an unlocked state ready for use. + #[stable] pub fn new(t: T) -> Mutex { Mutex { inner: box MUTEX_INIT, @@ -150,15 +191,14 @@ impl Mutex { /// 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 { - 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> { + unsafe { self.inner.lock.lock() } + MutexGuard::new(&*self.inner, &self.data) } /// Attempts to acquire this lock. @@ -169,17 +209,17 @@ impl Mutex { /// /// 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> { - 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> { + if unsafe { self.inner.lock.try_lock() } { + Ok(try!(MutexGuard::new(&*self.inner, &self.data))) + } else { + Err(TryLockError::WouldBlock) } } } @@ -194,19 +234,27 @@ impl Drop for Mutex { } } +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> { 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 { + #[inline] + #[unstable = "may be merged with Mutex in the future"] + pub fn try_lock(&'static self) -> TryLockResult> { if unsafe { self.lock.try_lock() } { - Some(StaticMutexGuard::new(self)) + Ok(try!(MutexGuard::new(self, &DUMMY.0))) } else { - None + Err(TryLockError::WouldBlock) } } @@ -220,61 +268,54 @@ impl StaticMutex { /// *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, guard: StaticMutexGuard) -> MutexGuard { - MutexGuard { __lock: lock, __guard: guard } + fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell) + -> LockResult> { + 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 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 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)] @@ -292,16 +333,16 @@ mod 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(); } } @@ -316,7 +357,7 @@ mod test { fn inc() { for _ in range(0, J) { unsafe { - let _g = M.lock(); + let _g = M.lock().unwrap(); CNT += 1; } } @@ -343,7 +384,7 @@ mod test { #[test] fn try_lock() { let m = Mutex::new(()); - assert!(m.try_lock().is_some()); + *m.try_lock().unwrap() = (); } #[test] @@ -355,22 +396,21 @@ mod 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()); @@ -379,31 +419,35 @@ mod test { 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] @@ -414,8 +458,8 @@ mod 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(()); }); @@ -432,13 +476,13 @@ mod test { } 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); } } diff --git a/src/libstd/sync/poison.rs b/src/libstd/sync/poison.rs index ad08e9873faad..edf16d99f4966 100644 --- a/src/libstd/sync/poison.rs +++ b/src/libstd/sync/poison.rs @@ -8,31 +8,127 @@ // 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 } +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 { + 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 { + guard: T, +} + +/// An enumeration of possible errors which can occur while calling the +/// `try_lock` method. +#[stable] +pub enum TryLockError { + /// The lock could not be acquired because another task failed while holding + /// the lock. + #[stable] + Poisoned(PoisonError), + /// 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 = Result>; + +/// 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 = Result>; + +impl fmt::Show for PoisonError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "poisoned lock: another task failed inside".fmt(f) + } +} + +impl PoisonError { + /// 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 FromError> for TryLockError { + fn from_error(err: PoisonError) -> TryLockError { + TryLockError::Poisoned(err) } +} - pub fn done(&mut self) { - if !self.panicking && Thread::panicking() { - *self.flag = true; +impl fmt::Show for TryLockError { + 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(guard: T) -> PoisonError { + PoisonError { guard: guard } +} + +pub fn map_result(result: LockResult, f: F) + -> LockResult + where F: FnOnce(T) -> U { + match result { + Ok(t) => Ok(f(t)), + Err(PoisonError { guard }) => Err(new_poison_error(f(guard))) + } +} diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 76d05d9bfd419..7f3c77c97adef 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -10,10 +10,10 @@ 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 /// @@ -28,12 +28,14 @@ use sync::poison; /// 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; @@ -42,19 +44,20 @@ use sync::poison; /// /// // 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 { inner: Box, data: UnsafeCell, @@ -77,64 +80,55 @@ unsafe impl Sync for RWLock {} /// 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, + 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, - __guard: StaticRWLockReadGuard, + __lock: &'a StaticRWLock, + __data: &'a UnsafeCell, + __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, - __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, + __poison: poison::Guard, + __marker: marker::NoSend, } impl RWLock { /// Creates a new instance of an RWLock which is unlocked and read to go. + #[stable] pub fn new(t: T) -> RWLock { RWLock { inner: box RWLOCK_INIT, data: UnsafeCell::new(t) } } @@ -151,17 +145,16 @@ impl RWLock { /// 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 { - unsafe { - let lock: &'static StaticRWLock = &*(&*self.inner as *const _); - RWLockReadGuard::new(self, lock.read()) - } + #[stable] + pub fn read(&self) -> LockResult> { + unsafe { self.inner.lock.read() } + RWLockReadGuard::new(&*self.inner, &self.data) } /// Attempt to acquire this lock with shared read access. @@ -173,18 +166,19 @@ impl RWLock { /// 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> { - 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> { + if unsafe { self.inner.lock.try_read() } { + Ok(try!(RWLockReadGuard::new(&*self.inner, &self.data))) + } else { + Err(TryLockError::WouldBlock) } } @@ -197,17 +191,16 @@ impl RWLock { /// 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 { - unsafe { - let lock: &'static StaticRWLock = &*(&*self.inner as *const _); - RWLockWriteGuard::new(self, lock.write()) - } + #[stable] + pub fn write(&self) -> LockResult> { + unsafe { self.inner.lock.write() } + RWLockWriteGuard::new(&*self.inner, &self.data) } /// Attempt to lock this rwlock with exclusive write access. @@ -216,18 +209,19 @@ impl RWLock { /// 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> { - 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> { + if unsafe { self.inner.lock.try_read() } { + Ok(try!(RWLockWriteGuard::new(&*self.inner, &self.data))) + } else { + Err(TryLockError::WouldBlock) } } } @@ -235,30 +229,37 @@ impl RWLock { #[unsafe_destructor] impl Drop for RWLock { 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> { + 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 { - 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> { + if unsafe { self.lock.try_read() } { + Ok(try!(RWLockReadGuard::new(self, &DUMMY.0))) } else { - None + Err(TryLockError::WouldBlock) } } @@ -267,20 +268,23 @@ impl StaticRWLock { /// /// 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> { + 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 { - 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> { + if unsafe { self.lock.try_write() } { + Ok(try!(RWLockWriteGuard::new(self, &DUMMY.0))) } else { - None + Err(TryLockError::WouldBlock) } } @@ -290,70 +294,62 @@ impl StaticRWLock { /// 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, guard: StaticRWLockReadGuard) - -> RWLockReadGuard { - RWLockReadGuard { __lock: lock, __guard: guard } + fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell) + -> LockResult> { + poison::map_result(lock.poison.borrow(), |_| { + RWLockReadGuard { + __lock: lock, + __data: data, + __marker: marker::NoSend, + } + }) } } impl<'rwlock, T> RWLockWriteGuard<'rwlock, T> { - fn new(lock: &RWLock, guard: StaticRWLockWriteGuard) - -> RWLockWriteGuard { - RWLockWriteGuard { __lock: lock, __guard: guard } + fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell) + -> LockResult> { + poison::map_result(lock.poison.borrow(), |guard| { + RWLockWriteGuard { + __lock: lock, + __data: data, + __poison: guard, + __marker: marker::NoSend, + } + }) } } impl<'rwlock, T> Deref 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 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 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(); } } } @@ -368,19 +364,19 @@ mod tests { #[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(); } } @@ -394,12 +390,12 @@ mod tests { 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); @@ -411,51 +407,47 @@ mod tests { } #[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 = 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 = 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 = 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 = Thread::spawn(move|| { + let _lock = arc2.read().unwrap(); + panic!() }).join(); - let lock = arc.write(); + let lock = arc.write().unwrap(); assert_eq!(*lock, 1); } @@ -466,7 +458,7 @@ mod tests { 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; @@ -481,7 +473,7 @@ mod tests { 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); })); } @@ -493,7 +485,7 @@ mod tests { // Wait for writer to finish rx.recv(); - let lock = arc.read(); + let lock = arc.read().unwrap(); assert_eq!(*lock, 10); } @@ -507,14 +499,14 @@ mod tests { } 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); } } diff --git a/src/libstd/sync/semaphore.rs b/src/libstd/sync/semaphore.rs index 574b0f22bee00..e3b683a6ccb38 100644 --- a/src/libstd/sync/semaphore.rs +++ b/src/libstd/sync/semaphore.rs @@ -68,9 +68,9 @@ impl Semaphore { /// 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; } @@ -80,7 +80,7 @@ impl Semaphore { /// 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(); } diff --git a/src/libstd/sync/task_pool.rs b/src/libstd/sync/task_pool.rs index 366e4b7d35b01..ee534f6cdde3e 100644 --- a/src/libstd/sync/task_pool.rs +++ b/src/libstd/sync/task_pool.rs @@ -8,7 +8,7 @@ // 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::*; @@ -45,9 +45,9 @@ impl<'a> Drop for Sentinel<'a> { } } -/// 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 @@ -69,34 +69,34 @@ impl<'a> Drop for Sentinel<'a> { /// 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 } 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::(); 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(&self, job: F) where F : FnOnce(), F : Send { @@ -106,14 +106,14 @@ impl TaskPool { fn spawn_in_pool(jobs: Arc>>) { 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() }; @@ -165,12 +165,12 @@ mod test { 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(); @@ -189,7 +189,7 @@ mod test { 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|| { diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys/common/backtrace.rs index 1d646eb06b167..866bf1d8a7d63 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys/common/backtrace.rs @@ -115,10 +115,10 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { // 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('$') { diff --git a/src/libstd/sys/common/helper_thread.rs b/src/libstd/sys/common/helper_thread.rs index a629f035b07af..9ef1c33312fc8 100644 --- a/src/libstd/sys/common/helper_thread.rs +++ b/src/libstd/sys/common/helper_thread.rs @@ -83,7 +83,7 @@ impl Helper { 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); @@ -95,7 +95,7 @@ impl Helper { 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(); @@ -111,7 +111,7 @@ impl Helper { /// 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 @@ -127,7 +127,7 @@ impl Helper { // 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> = mem::transmute(*self.chan.get()); @@ -137,7 +137,7 @@ impl Helper { // Wait for the child to exit while !*self.shutdown.get() { - self.cond.wait(&guard); + guard = self.cond.wait(guard).unwrap(); } drop(guard); diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys/common/net.rs index 382f6875b281d..7a09137a225dc 100644 --- a/src/libstd/sys/common/net.rs +++ b/src/libstd/sys/common/net.rs @@ -269,7 +269,7 @@ pub fn get_host_addresses(host: Option<&str>, servname: Option<&str>, // 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)); @@ -669,7 +669,7 @@ impl TcpStream { 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 @@ -808,7 +808,7 @@ impl UdpSocket { 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 diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index 983d0e5fa1486..ddae9a132c314 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -244,7 +244,7 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { use iter::{Iterator, IteratorExt}; use os; use path::GenericPath; - use ptr::RawPtr; + use ptr::PtrExt; use ptr; use slice::SliceExt; diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index f3babca32871a..4b7ac8ff4d3a9 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -109,6 +109,8 @@ pub fn decode_error(errno: i32) -> IoError { "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 diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs index f1b078b4e80ab..868b460aa5ed3 100644 --- a/src/libstd/sys/unix/pipe.rs +++ b/src/libstd/sys/unix/pipe.rs @@ -145,7 +145,7 @@ impl UnixStream { 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 diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index d1cb91bcdb377..06259d61fcb84 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -131,7 +131,6 @@ extern "system" { pub mod compat { use intrinsics::{atomic_store_relaxed, transmute}; - use iter::IteratorExt; use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; use prelude::*; diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index 15eddd569beec..3ad439078b9a1 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -265,8 +265,8 @@ pub fn readdir(p: &Path) -> IoResult> { { 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, diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 6924687d8c470..aee98e22836be 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -121,6 +121,8 @@ pub fn decode_error(errno: i32) -> IoError { "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 diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index e007b46b261b4..fa08290a888e9 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -99,8 +99,9 @@ pub fn error_string(errnum: i32) -> String { 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), } } } @@ -147,7 +148,7 @@ pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD) -> Option IoResult { } 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, diff --git a/src/libstd/sys/windows/tty.rs b/src/libstd/sys/windows/tty.rs index f793de5bb57ef..99292b3b44bd1 100644 --- a/src/libstd/sys/windows/tty.rs +++ b/src/libstd/sys/windows/tty.rs @@ -101,8 +101,8 @@ impl TTY { }; 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); } diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 56731bd7ec3ee..a7b3ee996a34d 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -313,7 +313,7 @@ impl Thread { /// 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`, 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. @@ -334,6 +334,7 @@ impl Thread { } /// Determines whether the current thread is panicking. + #[inline] pub fn panicking() -> bool { unwind::panicking() } @@ -349,9 +350,9 @@ impl Thread { // 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; } @@ -360,7 +361,7 @@ impl Thread { /// /// 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(); diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index 242dceb425636..4cfa27093527a 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -240,13 +240,18 @@ impl Key { 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>) -> &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. /// diff --git a/src/libstd/thread_local/scoped.rs b/src/libstd/thread_local/scoped.rs index 756c86c211547..5f96548c0530a 100644 --- a/src/libstd/thread_local/scoped.rs +++ b/src/libstd/thread_local/scoped.rs @@ -62,10 +62,10 @@ pub struct Key { #[doc(hidden)] pub inner: KeyInner } #[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); ); } @@ -240,6 +240,8 @@ mod tests { use cell::Cell; use prelude::*; + scoped_thread_local!(static FOO: uint); + #[test] fn smoke() { scoped_thread_local!(static BAR: uint); @@ -264,4 +266,16 @@ mod tests { }); }); } + + #[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()); + } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index debcbcd2154bd..f253943943dcc 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -371,10 +371,18 @@ pub const DUMMY_NODE_ID: NodeId = -1; /// 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; #[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] @@ -382,7 +390,6 @@ pub struct TyParam { pub ident: Ident, pub id: NodeId, pub bounds: TyParamBounds, - pub unbound: Option, pub default: Option>, pub span: Span } @@ -1488,7 +1495,7 @@ pub struct PolyTraitRef { pub bound_lifetimes: Vec, /// 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)] @@ -1577,8 +1584,6 @@ pub enum Item_ { /// Represents a Trait Declaration ItemTrait(Unsafety, Generics, - Option, // (optional) default bound not required for Self. - // Currently, only Sized makes sense here. TyParamBounds, Vec), ItemImpl(Unsafety, diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index 9b42a8f754069..5a4f5731be50d 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -780,9 +780,9 @@ impl<'ast> Visitor<'ast> for NodeCollector<'ast> { 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)); } } diff --git a/src/libsyntax/config.rs b/src/libsyntax/config.rs index d2185a00876d2..94a3784291d0b 100644 --- a/src/libsyntax/config.rs +++ b/src/libsyntax/config.rs @@ -139,11 +139,11 @@ fn fold_item_underscore(cx: &mut Context, item: ast::Item_) -> ast::Item_ .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) diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 77165168746b7..239af18890909 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -68,7 +68,6 @@ pub trait AstBuilder { span: Span, id: ast::Ident, bounds: OwnedSlice, - unbound: Option, default: Option>) -> ast::TyParam; fn trait_ref(&self, path: ast::Path) -> ast::TraitRef; @@ -414,13 +413,11 @@ impl<'a> AstBuilder for ExtCtxt<'a> { span: Span, id: ast::Ident, bounds: OwnedSlice, - unbound: Option, default: Option>) -> ast::TyParam { ast::TyParam { ident: id, id: ast::DUMMY_NODE_ID, bounds: bounds, - unbound: unbound, default: default, span: span } @@ -455,7 +452,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } 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 { diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 57dfbc0c6e8bc..3c8d74c14ee63 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -58,10 +58,10 @@ fn expand_deriving_decodable_imp(cx: &mut ExtCtxt, 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 { diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 8bd3df6232ce5..5829f34bccc5d 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -134,10 +134,10 @@ fn expand_deriving_encodable_imp(cx: &mut ExtCtxt, 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 { diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index cf0201294ae54..e4e31139d82f4 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -417,7 +417,6 @@ impl<'a> TraitDef<'a> { cx.typaram(self.span, ty_param.ident, OwnedSlice::from_vec(bounds), - ty_param.unbound.clone(), None) })); diff --git a/src/libsyntax/ext/deriving/generic/ty.rs b/src/libsyntax/ext/deriving/generic/ty.rs index 56d11c2377fa4..95bdd8b9ffd2f 100644 --- a/src/libsyntax/ext/deriving/generic/ty.rs +++ b/src/libsyntax/ext/deriving/generic/ty.rs @@ -189,15 +189,19 @@ impl<'a> Ty<'a> { } -fn mk_ty_param(cx: &ExtCtxt, span: Span, name: &str, - bounds: &[Path], unbound: Option, - 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, ty_params: Vec) @@ -216,7 +220,7 @@ fn mk_generics(lifetimes: Vec, ty_params: Vec) #[deriving(Clone)] pub struct LifetimeBounds<'a> { pub lifetimes: Vec<(&'a str, Vec<&'a str>)>, - pub bounds: Vec<(&'a str, Option, Vec>)>, + pub bounds: Vec<(&'a str, Vec>)>, } impl<'a> LifetimeBounds<'a> { @@ -239,12 +243,11 @@ 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) } diff --git a/src/libsyntax/ext/deriving/hash.rs b/src/libsyntax/ext/deriving/hash.rs index 4e59124a1294f..72e3b45dc91b7 100644 --- a/src/libsyntax/ext/deriving/hash.rs +++ b/src/libsyntax/ext/deriving/hash.rs @@ -30,7 +30,7 @@ pub fn expand_deriving_hash(cx: &mut ExtCtxt, 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")) diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index 4f6e4d1fb3c10..1ddf5b2a5c31e 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -36,7 +36,6 @@ pub fn expand_deriving_rand(cx: &mut ExtCtxt, generics: LifetimeBounds { lifetimes: Vec::new(), bounds: vec!(("R", - None, vec!( Path::new(vec!("std", "rand", "Rng")) ))) }, explicit_self: None, diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 11a9fdee0b9b0..4f0169e31f229 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -736,18 +736,17 @@ pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) -> 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(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 } @@ -1043,7 +1042,7 @@ pub fn noop_fold_item_underscore(i: Item_, folder: &mut T) -> Item_ { 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 { @@ -1073,7 +1072,6 @@ pub fn noop_fold_item_underscore(i: Item_, folder: &mut T) -> Item_ { }).collect(); ItemTrait(unsafety, folder.fold_generics(generics), - unbound, bounds, methods) } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 2f43661eebeba..e88aabb044cc6 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -15,7 +15,7 @@ use self::ItemOrViewItem::*; 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}; @@ -117,6 +117,13 @@ pub enum PathParsingMode { 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. @@ -1087,12 +1094,12 @@ impl<'a> Parser<'a> { 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) @@ -1165,7 +1172,7 @@ impl<'a> Parser<'a> { // 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); @@ -1255,7 +1262,7 @@ impl<'a> Parser<'a> { 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 { @@ -1481,7 +1488,7 @@ impl<'a> Parser<'a> { 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. @@ -4029,13 +4036,14 @@ impl<'a> Parser<'a> { // 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 { if !self.eat(&token::Colon) { OwnedSlice::empty() } else { - self.parse_ty_param_bounds() + self.parse_ty_param_bounds(mode) } } @@ -4043,14 +4051,20 @@ impl<'a> Parser<'a> { // 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 { 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, @@ -4060,7 +4074,18 @@ impl<'a> Parser<'a> { } 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, } @@ -4089,13 +4114,14 @@ impl<'a> Parser<'a> { } } - /// 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; @@ -4106,7 +4132,14 @@ impl<'a> Parser<'a> { 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(); @@ -4118,7 +4151,6 @@ impl<'a> Parser<'a> { ident: ident, id: ast::DUMMY_NODE_ID, bounds: bounds, - unbound: unbound, default: default, span: span, } @@ -4260,7 +4292,7 @@ impl<'a> Parser<'a> { 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); @@ -4747,15 +4779,23 @@ impl<'a> Parser<'a> { 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, Vec) { @@ -4974,12 +5014,25 @@ impl<'a> Parser<'a> { } fn parse_for_sized(&mut self) -> Option { + // 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); @@ -5924,7 +5977,7 @@ impl<'a> Parser<'a> { } - /// 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 @@ -6036,7 +6089,7 @@ impl<'a> Parser<'a> { } 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 { @@ -6048,7 +6101,8 @@ impl<'a> Parser<'a> { 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))) } diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index f575d3d6c676b..f22a4b5c6ed10 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -724,7 +724,7 @@ pub fn fresh_name(src: &ast::Ident) -> ast::Name { // 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))*/ } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index accffbc35babe..02a03285d3b86 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -13,7 +13,7 @@ pub use self::AnnNode::*; 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; @@ -958,20 +958,25 @@ impl<'a> State<'a> { } 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()); @@ -2345,7 +2350,11 @@ impl<'a> State<'a> { } 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) => { @@ -2412,10 +2421,6 @@ impl<'a> State<'a> { } 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 { diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 22cfea862517e..1cd21ccac7a0e 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -85,8 +85,8 @@ pub trait Visitor<'v> { 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) @@ -244,7 +244,8 @@ pub fn walk_explicit_self<'v, V: Visitor<'v>>(visitor: &mut V, /// 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); @@ -324,7 +325,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { 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() { @@ -558,8 +559,8 @@ pub fn walk_ty_param_bounds_helper<'v, V: Visitor<'v>>(visitor: &mut V, 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); diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index a4ebcfe8a568b..420b1100ec1cd 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -39,7 +39,7 @@ //! [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", diff --git a/src/rust-installer b/src/rust-installer index aed7347241606..3a37981744a5a 160000 --- a/src/rust-installer +++ b/src/rust-installer @@ -1 +1 @@ -Subproject commit aed73472416064642911af790b25d57c9390b6c7 +Subproject commit 3a37981744a5af2433fed551f742465c78c9af7f diff --git a/src/test/bench/core-std.rs b/src/test/bench/core-std.rs index 16129593485b8..d9a4aede7d7d9 100644 --- a/src/test/bench/core-std.rs +++ b/src/test/bench/core-std.rs @@ -83,7 +83,7 @@ fn read_line() { } fn vec_plus() { - let mut r = rand::task_rng(); + let mut r = rand::thread_rng(); let mut v = Vec::new(); let mut i = 0; @@ -101,7 +101,7 @@ fn vec_plus() { } fn vec_append() { - let mut r = rand::task_rng(); + let mut r = rand::thread_rng(); let mut v = Vec::new(); let mut i = 0; @@ -122,7 +122,7 @@ fn vec_append() { } 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) { diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index 49f53bf9d3883..8ec44b2dd3c14 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -28,15 +28,15 @@ type pipe = Arc<(Mutex>, Condvar)>; 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() } diff --git a/src/test/compile-fail/double-type-import.rs b/src/test/compile-fail/double-type-import.rs new file mode 100644 index 0000000000000..923f95e69d122 --- /dev/null +++ b/src/test/compile-fail/double-type-import.rs @@ -0,0 +1,24 @@ +// 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 or the MIT license +// , 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; +} diff --git a/src/test/compile-fail/duplicate-trait-bounds.rs b/src/test/compile-fail/duplicate-trait-bounds.rs new file mode 100644 index 0000000000000..d9aa9d9dfccc7 --- /dev/null +++ b/src/test/compile-fail/duplicate-trait-bounds.rs @@ -0,0 +1,15 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +trait Foo {} + +fn foo() {} //~ ERROR `Foo` already appears in the list of bounds + +fn main() {} diff --git a/src/test/compile-fail/import-shadow-1.rs b/src/test/compile-fail/import-shadow-1.rs new file mode 100644 index 0000000000000..007b28b6924e4 --- /dev/null +++ b/src/test/compile-fail/import-shadow-1.rs @@ -0,0 +1,31 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/import-shadow-2.rs b/src/test/compile-fail/import-shadow-2.rs new file mode 100644 index 0000000000000..e597b55738386 --- /dev/null +++ b/src/test/compile-fail/import-shadow-2.rs @@ -0,0 +1,31 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/import-shadow-3.rs b/src/test/compile-fail/import-shadow-3.rs new file mode 100644 index 0000000000000..68222fa3fd727 --- /dev/null +++ b/src/test/compile-fail/import-shadow-3.rs @@ -0,0 +1,31 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/import-shadow-4.rs b/src/test/compile-fail/import-shadow-4.rs new file mode 100644 index 0000000000000..c698004bda0e4 --- /dev/null +++ b/src/test/compile-fail/import-shadow-4.rs @@ -0,0 +1,31 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/import-shadow-5.rs b/src/test/compile-fail/import-shadow-5.rs new file mode 100644 index 0000000000000..6ad7e5ec3e260 --- /dev/null +++ b/src/test/compile-fail/import-shadow-5.rs @@ -0,0 +1,31 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/import-shadow-6.rs b/src/test/compile-fail/import-shadow-6.rs new file mode 100644 index 0000000000000..1864251e71b42 --- /dev/null +++ b/src/test/compile-fail/import-shadow-6.rs @@ -0,0 +1,31 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/import-shadow-7.rs b/src/test/compile-fail/import-shadow-7.rs new file mode 100644 index 0000000000000..a2df266fb74f3 --- /dev/null +++ b/src/test/compile-fail/import-shadow-7.rs @@ -0,0 +1,31 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/issue-13853-2.rs b/src/test/compile-fail/issue-13853-2.rs new file mode 100644 index 0000000000000..ea0d880f4a1cc --- /dev/null +++ b/src/test/compile-fail/issue-13853-2.rs @@ -0,0 +1,16 @@ +// 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 or the MIT license +// , 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) { res.get } //~ ERROR attempted to take value of method +fn main() {} diff --git a/src/test/compile-fail/issue-13853-3.rs b/src/test/compile-fail/issue-13853-3.rs new file mode 100644 index 0000000000000..f10c47b594ea2 --- /dev/null +++ b/src/test/compile-fail/issue-13853-3.rs @@ -0,0 +1,33 @@ +// 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 or the MIT license +// , 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>), +} + +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() {} diff --git a/src/test/compile-fail/issue-13853-4.rs b/src/test/compile-fail/issue-13853-4.rs new file mode 100644 index 0000000000000..7d653f5ab9e29 --- /dev/null +++ b/src/test/compile-fail/issue-13853-4.rs @@ -0,0 +1,21 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/issue-13853-5.rs b/src/test/compile-fail/issue-13853-5.rs new file mode 100644 index 0000000000000..b3a4f341f8448 --- /dev/null +++ b/src/test/compile-fail/issue-13853-5.rs @@ -0,0 +1,23 @@ +// 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 or the MIT license +// , 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>(_x: D, _y: &'a str) -> &'a str { + } +} + +fn main() {} diff --git a/src/test/compile-fail/issue-13853.rs b/src/test/compile-fail/issue-13853.rs new file mode 100644 index 0000000000000..868836a4bbd0a --- /dev/null +++ b/src/test/compile-fail/issue-13853.rs @@ -0,0 +1,45 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +trait Node { + fn zomg(); +} + +trait Graph { + fn nodes<'a, I: Iterator<&'a N>>(&'a self) -> I; +} + +impl Graph for Vec { + 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>(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 +} diff --git a/src/test/compile-fail/issue-14227.rs b/src/test/compile-fail/issue-14227.rs new file mode 100644 index 0000000000000..c4846a64f29be --- /dev/null +++ b/src/test/compile-fail/issue-14227.rs @@ -0,0 +1,16 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/issue-15034.rs b/src/test/compile-fail/issue-15034.rs new file mode 100644 index 0000000000000..13d27e7152b03 --- /dev/null +++ b/src/test/compile-fail/issue-15034.rs @@ -0,0 +1,32 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/issue-16538.rs b/src/test/compile-fail/issue-16538.rs new file mode 100644 index 0000000000000..0e022834bacf2 --- /dev/null +++ b/src/test/compile-fail/issue-16538.rs @@ -0,0 +1,25 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/issue-17728.rs b/src/test/compile-fail/issue-17728.rs new file mode 100644 index 0000000000000..50b0a1a20c24c --- /dev/null +++ b/src/test/compile-fail/issue-17728.rs @@ -0,0 +1,132 @@ +// 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 or the MIT license +// , 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, + direction_to_room: HashMap, +} + +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, +} + +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) + }; +} diff --git a/src/test/compile-fail/issue-17740.rs b/src/test/compile-fail/issue-17740.rs new file mode 100644 index 0000000000000..73f86fee903e5 --- /dev/null +++ b/src/test/compile-fail/issue-17740.rs @@ -0,0 +1,22 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/issue-19707.rs b/src/test/compile-fail/issue-19707.rs new file mode 100644 index 0000000000000..9affb44b7445c --- /dev/null +++ b/src/test/compile-fail/issue-19707.rs @@ -0,0 +1,20 @@ +// 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 or the MIT license +// , 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 &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() {} diff --git a/src/test/compile-fail/issue-5543.rs b/src/test/compile-fail/issue-5543.rs index 0090dd544f655..bbd41b28f0361 100644 --- a/src/test/compile-fail/issue-5543.rs +++ b/src/test/compile-fail/issue-5543.rs @@ -1,4 +1,4 @@ -// 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. // @@ -8,14 +8,12 @@ // 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 = box 5; + let _m: Box = r as Box; + //~^ ERROR `core::kinds::Sized` is not implemented for the type `Foo` + //~| ERROR `Foo` is not implemented for the type `Foo` } diff --git a/src/test/compile-fail/issue-7364.rs b/src/test/compile-fail/issue-7364.rs index 2646edd7684e6..77836143f27dd 100644 --- a/src/test/compile-fail/issue-7364.rs +++ b/src/test/compile-fail/issue-7364.rs @@ -14,8 +14,7 @@ use std::cell::RefCell; // Regresion test for issue 7364 static boxed: Box> = 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() { } diff --git a/src/test/compile-fail/mut-not-freeze.rs b/src/test/compile-fail/mut-not-freeze.rs index 4b058f6fdb343..95ebb8bd88221 100644 --- a/src/test/compile-fail/mut-not-freeze.rs +++ b/src/test/compile-fail/mut-not-freeze.rs @@ -17,5 +17,4 @@ 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 } diff --git a/src/test/compile-fail/resolve-label.rs b/src/test/compile-fail/resolve-label.rs new file mode 100644 index 0000000000000..398b4f5859e65 --- /dev/null +++ b/src/test/compile-fail/resolve-label.rs @@ -0,0 +1,21 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/compile-fail/task-rng-isnt-sendable.rs b/src/test/compile-fail/task-rng-isnt-sendable.rs index d96599404deb8..f673c3b797809 100644 --- a/src/test/compile-fail/task-rng-isnt-sendable.rs +++ b/src/test/compile-fail/task-rng-isnt-sendable.rs @@ -8,14 +8,14 @@ // 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() {} pub fn main() { - test_send::(); + test_send::(); //~^ ERROR `core::kinds::Send` is not implemented //~^^ ERROR `core::kinds::Send` is not implemented } diff --git a/src/test/run-make/unicode-input/multiple_files.rs b/src/test/run-make/unicode-input/multiple_files.rs index 2aa4264225c96..88d8f10e7094d 100644 --- a/src/test/run-make/unicode-input/multiple_files.rs +++ b/src/test/run-make/unicode-input/multiple_files.rs @@ -10,7 +10,7 @@ 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 @@ -19,7 +19,7 @@ use std::rand::{task_rng, Rng}; // 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) { diff --git a/src/test/run-make/unicode-input/span_length.rs b/src/test/run-make/unicode-input/span_length.rs index 7b096d7d583a5..f83734b1502eb 100644 --- a/src/test/run-make/unicode-input/span_length.rs +++ b/src/test/run-make/unicode-input/span_length.rs @@ -10,7 +10,7 @@ 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() { }` and checks the // compiler emits a span of the appropriate length (for the @@ -18,7 +18,7 @@ use std::rand::{task_rng, Rng}; // 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) { @@ -38,7 +38,7 @@ fn main() { 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(), diff --git a/src/test/run-pass/dst-raw.rs b/src/test/run-pass/dst-raw.rs index 19af9fd7ea7b4..d3d2e3581aaf7 100644 --- a/src/test/run-pass/dst-raw.rs +++ b/src/test/run-pass/dst-raw.rs @@ -23,7 +23,7 @@ impl Trait for A { } } -struct Foo { +struct Foo { f: T } diff --git a/src/test/run-pass/dst-struct-sole.rs b/src/test/run-pass/dst-struct-sole.rs index 26cb27cc65392..47547bb7e5a27 100644 --- a/src/test/run-pass/dst-struct-sole.rs +++ b/src/test/run-pass/dst-struct-sole.rs @@ -10,7 +10,7 @@ // As dst-struct.rs, but the unsized field is the only field in the struct. -struct Fat { +struct Fat { ptr: T } diff --git a/src/test/run-pass/dst-struct.rs b/src/test/run-pass/dst-struct.rs index 3644ca81d5659..fb536904ac80f 100644 --- a/src/test/run-pass/dst-struct.rs +++ b/src/test/run-pass/dst-struct.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Fat { +struct Fat { f1: int, f2: &'static str, ptr: T diff --git a/src/test/run-pass/dst-trait.rs b/src/test/run-pass/dst-trait.rs index 907c7810736ba..abe55d78ac69a 100644 --- a/src/test/run-pass/dst-trait.rs +++ b/src/test/run-pass/dst-trait.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Fat { +struct Fat { f1: int, f2: &'static str, ptr: T diff --git a/src/test/run-pass/inconsistent-lifetime-mismatch.rs b/src/test/run-pass/inconsistent-lifetime-mismatch.rs new file mode 100644 index 0000000000000..b30583c666888 --- /dev/null +++ b/src/test/run-pass/inconsistent-lifetime-mismatch.rs @@ -0,0 +1,21 @@ +// 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 or the MIT license +// , 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() {} diff --git a/src/test/run-pass/issue-13655.rs b/src/test/run-pass/issue-13655.rs new file mode 100644 index 0000000000000..6fdaac992047f --- /dev/null +++ b/src/test/run-pass/issue-13655.rs @@ -0,0 +1,27 @@ +// 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 or the MIT license +// , 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); + +impl Fn<(), T> for Foo { + extern "rust-call" fn call(&self, _: ()) -> T { + match *self { + Foo(t) => t + } + } +} + +fn main() { + let t: u8 = 1; + println!("{}", Foo(t)()); +} diff --git a/src/test/run-pass/issue-13665.rs b/src/test/run-pass/issue-13665.rs new file mode 100644 index 0000000000000..5ccbe9a7980e8 --- /dev/null +++ b/src/test/run-pass/issue-13665.rs @@ -0,0 +1,22 @@ +// 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 or the MIT license +// , 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(); +} diff --git a/src/test/run-pass/issue-13808.rs b/src/test/run-pass/issue-13808.rs new file mode 100644 index 0000000000000..e20090adcf613 --- /dev/null +++ b/src/test/run-pass/issue-13808.rs @@ -0,0 +1,23 @@ +// 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 or the MIT license +// , 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(|| {}); +} diff --git a/src/test/run-pass/issue-15155.rs b/src/test/run-pass/issue-15155.rs index 053a4916e229a..3a63e63355cd0 100644 --- a/src/test/run-pass/issue-15155.rs +++ b/src/test/run-pass/issue-15155.rs @@ -22,7 +22,7 @@ struct IndirectBlah { x: Box } impl TraitWithSend for IndirectBlah {} impl IndirectTraitWithSend for IndirectBlah {} -fn test_trait() { println!("got here!") } +fn test_trait() { println!("got here!") } fn main() { test_trait::(); diff --git a/src/test/run-pass/issue-17361.rs b/src/test/run-pass/issue-17361.rs index fa38dcc198673..092bcf661a76a 100644 --- a/src/test/run-pass/issue-17361.rs +++ b/src/test/run-pass/issue-17361.rs @@ -11,6 +11,6 @@ // Test that astconv doesn't forget about mutability of &mut str fn main() { - fn foo(_: &mut T) {} + fn foo(_: &mut T) {} let _f: fn(&mut str) = foo; } diff --git a/src/test/run-pass/issue-18906.rs b/src/test/run-pass/issue-18906.rs new file mode 100644 index 0000000000000..e82359bc168e6 --- /dev/null +++ b/src/test/run-pass/issue-18906.rs @@ -0,0 +1,36 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub trait Borrow { + fn borrow(&self) -> &Borrowed; +} + +impl Borrow for T { + fn borrow(&self) -> &T { self } +} + +trait Foo { + fn foo(&self, other: &Self); +} + +fn bar(k: &K, q: &Q) where K: Borrow, Q: Foo { + q.foo(k.borrow()) +} + +struct MyTree; + +impl MyTree { + // This caused a failure in #18906 + fn bar(k: &K, q: &Q) where K: Borrow, Q: Foo { + q.foo(k.borrow()) + } +} + +fn main() {} diff --git a/src/test/run-pass/issue-7663.rs b/src/test/run-pass/issue-7663.rs index ee500b3d4fa36..39b0711721b54 100644 --- a/src/test/run-pass/issue-7663.rs +++ b/src/test/run-pass/issue-7663.rs @@ -17,8 +17,7 @@ mod test1 { 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); } } @@ -36,20 +35,7 @@ mod test2 { } } -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(); } diff --git a/src/test/run-pass/match-ref-binding-in-guard-3256.rs b/src/test/run-pass/match-ref-binding-in-guard-3256.rs index 9bb912e081ce6..a83bc73457e02 100644 --- a/src/test/run-pass/match-ref-binding-in-guard-3256.rs +++ b/src/test/run-pass/match-ref-binding-in-guard-3256.rs @@ -11,13 +11,11 @@ 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!() } } diff --git a/src/test/run-pass/method-recursive-blanket-impl.rs b/src/test/run-pass/method-recursive-blanket-impl.rs index b45faca2de602..4e4fb75b428cc 100644 --- a/src/test/run-pass/method-recursive-blanket-impl.rs +++ b/src/test/run-pass/method-recursive-blanket-impl.rs @@ -16,7 +16,7 @@ use std::kinds::Sized; // Note: this must be generic for the problem to show up -trait Foo for Sized? { +trait Foo for ?Sized { fn foo(&self); } diff --git a/src/test/run-pass/tcp-connect-timeouts.rs b/src/test/run-pass/tcp-connect-timeouts.rs index 2e4b9da691e39..2d087406fd6f7 100644 --- a/src/test/run-pass/tcp-connect-timeouts.rs +++ b/src/test/run-pass/tcp-connect-timeouts.rs @@ -23,7 +23,6 @@ #![allow(unused_imports)] use std::io::*; -use std::io::net::tcp::*; use std::io::test::*; use std::io; use std::time::Duration; diff --git a/src/test/run-pass/trait-static-method-generic-inference.rs b/src/test/run-pass/trait-static-method-generic-inference.rs new file mode 100644 index 0000000000000..4151ad6530ef4 --- /dev/null +++ b/src/test/run-pass/trait-static-method-generic-inference.rs @@ -0,0 +1,40 @@ +// 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mod base { + pub trait HasNew { + fn new() -> T; + } + + pub struct Foo { + dummy: (), + } + + impl HasNew for Foo { + fn new() -> Foo { + Foo { dummy: () } + } + } + + pub struct Bar { + dummy: (), + } + + impl HasNew for Bar { + fn new() -> Bar { + Bar { dummy: () } + } + } +} + +pub fn main() { + let _f: base::Foo = base::HasNew::new(); + let _b: base::Bar = base::HasNew::new(); +} diff --git a/src/test/run-pass/unsized.rs b/src/test/run-pass/unsized.rs index 141d6c88dd961..07b9fac66554e 100644 --- a/src/test/run-pass/unsized.rs +++ b/src/test/run-pass/unsized.rs @@ -10,21 +10,22 @@ // // 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 for Sized?: T2 {} -trait T4 {} -trait T5 {} -trait T6 {} -trait T7 {} -trait T8 {} -struct S1; -enum E {} -impl T1 for S1 {} -fn f() {} -type TT = T; +trait T1 for ?Sized {} +pub trait T2 for ?Sized {} +trait T3 for ?Sized: T2 {} +trait T4 {} +trait T5 {} +trait T6 {} +trait T7 {} +trait T8 {} +trait T9 {} +struct S1; +enum E {} +impl T1 for S1 {} +fn f() {} +type TT = T; pub fn main() { } diff --git a/src/test/run-pass/unsized2.rs b/src/test/run-pass/unsized2.rs index d28d47c0cfb85..8d2c99d4414c9 100644 --- a/src/test/run-pass/unsized2.rs +++ b/src/test/run-pass/unsized2.rs @@ -13,7 +13,7 @@ // Test sized-ness checking in substitution. // Unbounded. -fn f1(x: &X) { +fn f1(x: &X) { f1::(x); } fn f2(x: &X) { @@ -22,8 +22,8 @@ fn f2(x: &X) { } // Bounded. -trait T for Sized? {} -fn f3(x: &X) { +trait T for ?Sized {} +fn f3(x: &X) { f3::(x); } fn f4(x: &X) { @@ -32,7 +32,7 @@ fn f4(x: &X) { } // Self type. -trait T2 for Sized? { +trait T2 for ?Sized { fn f() -> Box; } struct S; @@ -41,14 +41,14 @@ impl T2 for S { box S } } -fn f5(x: &X) { +fn f5(x: &X) { let _: Box = T2::f(); } fn f6(x: &X) { let _: Box = T2::f(); } -trait T3 for Sized? { +trait T3 for ?Sized { fn f() -> Box; } impl T3 for S { @@ -56,7 +56,7 @@ impl T3 for S { box S } } -fn f7(x: &X) { +fn f7(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 = T3::f(); @@ -66,7 +66,7 @@ trait T4 { fn m1(x: &T4); fn m2(x: &T5); } -trait T5 { +trait T5 { // not an error (for now) fn m1(x: &T4); fn m2(x: &T5); @@ -76,21 +76,21 @@ trait T6 { fn m1(x: &T4); fn m2(x: &T5); } -trait T7 { +trait T7 { // not an error (for now) fn m1(x: &T4); fn m2(x: &T5); } // The last field in a struct or variant may be unsized -struct S2 { +struct S2 { f: X, } -struct S3 { +struct S3 { f1: int, f2: X, } -enum E { +enum E { V1(X), V2{x: X}, V3(int, X), diff --git a/src/test/run-pass/vector-sort-panic-safe.rs b/src/test/run-pass/vector-sort-panic-safe.rs index fe89c7532eebc..6ff1cffb4a42f 100644 --- a/src/test/run-pass/vector-sort-panic-safe.rs +++ b/src/test/run-pass/vector-sort-panic-safe.rs @@ -10,7 +10,7 @@ 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; @@ -59,7 +59,7 @@ pub fn main() { // IDs start from 0. creation_count.store(0, Relaxed); - let main = task_rng().gen_iter::() + let main = thread_rng().gen_iter::() .take(len) .collect::>(); diff --git a/src/test/run-pass/writealias.rs b/src/test/run-pass/writealias.rs index f48272366e2fd..dacfeb0081925 100644 --- a/src/test/run-pass/writealias.rs +++ b/src/test/run-pass/writealias.rs @@ -15,13 +15,11 @@ struct Point {x: int, y: int, z: int} 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!() } }