]> git.lizzy.rs Git - rust.git/commitdiff
auto merge of #20320 : alexcrichton/rust/rollup, r=alexcrichton
authorbors <bors@rust-lang.org>
Tue, 30 Dec 2014 08:02:39 +0000 (08:02 +0000)
committerbors <bors@rust-lang.org>
Tue, 30 Dec 2014 08:02:39 +0000 (08:02 +0000)
210 files changed:
Makefile.in
mk/dist.mk
mk/grammar.mk
mk/install.mk
mk/tests.mk
src/doc/guide-tasks.md
src/doc/guide.md
src/doc/index.md
src/doc/intro.md
src/doc/reference.md
src/etc/kate/rust.xml
src/etc/make-win-dist.py
src/grammar/RustLexer.g4
src/grammar/verify.rs
src/liballoc/arc.rs
src/liballoc/heap.rs
src/liballoc/rc.rs
src/libarena/lib.rs
src/libcollections/dlist.rs
src/libcollections/lib.rs
src/libcollections/slice.rs
src/libcollections/str.rs
src/libcollections/string.rs
src/libcore/cell.rs
src/libcore/clone.rs
src/libcore/macros.rs
src/libcore/prelude.rs
src/libcore/ptr.rs
src/libcore/result.rs
src/libcore/slice.rs
src/libcore/str/mod.rs
src/libflate/lib.rs
src/librand/distributions/exponential.rs
src/librand/distributions/gamma.rs
src/librand/distributions/mod.rs
src/librand/distributions/normal.rs
src/librand/distributions/range.rs
src/librand/lib.rs
src/librand/rand_impls.rs
src/libregex/parse.rs
src/libregex/test/bench.rs
src/librustc/lint/builtin.rs
src/librustc/metadata/encoder.rs
src/librustc/middle/check_match.rs
src/librustc/middle/infer/error_reporting.rs
src/librustc/middle/privacy.rs
src/librustc/middle/resolve_lifetime.rs
src/librustc/middle/ty.rs
src/librustc_back/arm.rs
src/librustc_back/mips.rs
src/librustc_back/mipsel.rs
src/librustc_back/target/arm_apple_ios.rs
src/librustc_back/target/arm_linux_androideabi.rs
src/librustc_back/target/arm_unknown_linux_gnueabi.rs
src/librustc_back/target/arm_unknown_linux_gnueabihf.rs
src/librustc_back/target/i386_apple_ios.rs
src/librustc_back/target/i686_apple_darwin.rs
src/librustc_back/target/mips_unknown_linux_gnu.rs
src/librustc_back/target/mipsel_unknown_linux_gnu.rs
src/librustc_back/target/x86_64_apple_darwin.rs
src/librustc_back/target/x86_64_pc_windows_gnu.rs
src/librustc_back/target/x86_64_unknown_dragonfly.rs
src/librustc_back/target/x86_64_unknown_freebsd.rs
src/librustc_back/target/x86_64_unknown_linux_gnu.rs
src/librustc_back/x86.rs
src/librustc_back/x86_64.rs
src/librustc_driver/lib.rs
src/librustc_resolve/lib.rs
src/librustc_trans/back/write.rs
src/librustc_trans/save/mod.rs
src/librustc_trans/save/recorder.rs
src/librustc_trans/save/span_utils.rs
src/librustc_trans/trans/base.rs
src/librustc_trans/trans/builder.rs
src/librustc_trans/trans/callee.rs
src/librustc_trans/trans/common.rs
src/librustc_trans/trans/glue.rs
src/librustc_trans/trans/value.rs
src/librustc_typeck/astconv.rs
src/librustc_typeck/check/mod.rs
src/librustc_typeck/collect.rs
src/librustc_typeck/variance.rs
src/librustdoc/clean/inline.rs
src/librustdoc/clean/mod.rs
src/librustdoc/doctree.rs
src/librustdoc/html/format.rs
src/librustdoc/html/render.rs
src/librustdoc/html/static/main.css
src/librustdoc/visit_ast.rs
src/libserialize/base64.rs
src/libserialize/json.rs
src/libstd/bitflags.rs
src/libstd/c_str.rs
src/libstd/c_vec.rs
src/libstd/collections/hash/map.rs
src/libstd/collections/hash/table.rs
src/libstd/comm/mod.rs
src/libstd/comm/shared.rs
src/libstd/comm/sync.rs
src/libstd/error.rs
src/libstd/hash.rs
src/libstd/io/extensions.rs
src/libstd/io/fs.rs
src/libstd/io/mem.rs
src/libstd/io/mod.rs
src/libstd/io/net/pipe.rs
src/libstd/io/net/tcp.rs
src/libstd/io/net/udp.rs
src/libstd/io/process.rs
src/libstd/io/stdio.rs
src/libstd/io/util.rs
src/libstd/num/mod.rs
src/libstd/os.rs
src/libstd/path/posix.rs
src/libstd/path/windows.rs
src/libstd/prelude.rs
src/libstd/rand/mod.rs
src/libstd/rt/backtrace.rs
src/libstd/rt/mod.rs
src/libstd/rt/task.rs
src/libstd/rt/unwind.rs
src/libstd/sync/atomic.rs
src/libstd/sync/barrier.rs
src/libstd/sync/condvar.rs
src/libstd/sync/mod.rs
src/libstd/sync/mutex.rs
src/libstd/sync/poison.rs
src/libstd/sync/rwlock.rs
src/libstd/sync/semaphore.rs
src/libstd/sync/task_pool.rs
src/libstd/sys/common/backtrace.rs
src/libstd/sys/common/helper_thread.rs
src/libstd/sys/common/net.rs
src/libstd/sys/unix/backtrace.rs
src/libstd/sys/unix/mod.rs
src/libstd/sys/unix/pipe.rs
src/libstd/sys/windows/c.rs
src/libstd/sys/windows/fs.rs
src/libstd/sys/windows/mod.rs
src/libstd/sys/windows/os.rs
src/libstd/sys/windows/tty.rs
src/libstd/thread.rs
src/libstd/thread_local/mod.rs
src/libstd/thread_local/scoped.rs
src/libsyntax/ast.rs
src/libsyntax/ast_map/mod.rs
src/libsyntax/config.rs
src/libsyntax/ext/build.rs
src/libsyntax/ext/deriving/decodable.rs
src/libsyntax/ext/deriving/encodable.rs
src/libsyntax/ext/deriving/generic/mod.rs
src/libsyntax/ext/deriving/generic/ty.rs
src/libsyntax/ext/deriving/hash.rs
src/libsyntax/ext/deriving/rand.rs
src/libsyntax/fold.rs
src/libsyntax/parse/parser.rs
src/libsyntax/parse/token.rs
src/libsyntax/print/pprust.rs
src/libsyntax/visit.rs
src/libterm/lib.rs
src/rust-installer
src/test/bench/core-std.rs
src/test/bench/msgsend-ring-mutex-arcs.rs
src/test/compile-fail/double-type-import.rs [new file with mode: 0644]
src/test/compile-fail/duplicate-trait-bounds.rs [new file with mode: 0644]
src/test/compile-fail/import-shadow-1.rs [new file with mode: 0644]
src/test/compile-fail/import-shadow-2.rs [new file with mode: 0644]
src/test/compile-fail/import-shadow-3.rs [new file with mode: 0644]
src/test/compile-fail/import-shadow-4.rs [new file with mode: 0644]
src/test/compile-fail/import-shadow-5.rs [new file with mode: 0644]
src/test/compile-fail/import-shadow-6.rs [new file with mode: 0644]
src/test/compile-fail/import-shadow-7.rs [new file with mode: 0644]
src/test/compile-fail/issue-13853-2.rs [new file with mode: 0644]
src/test/compile-fail/issue-13853-3.rs [new file with mode: 0644]
src/test/compile-fail/issue-13853-4.rs [new file with mode: 0644]
src/test/compile-fail/issue-13853-5.rs [new file with mode: 0644]
src/test/compile-fail/issue-13853.rs [new file with mode: 0644]
src/test/compile-fail/issue-14227.rs [new file with mode: 0644]
src/test/compile-fail/issue-15034.rs [new file with mode: 0644]
src/test/compile-fail/issue-16538.rs [new file with mode: 0644]
src/test/compile-fail/issue-17728.rs [new file with mode: 0644]
src/test/compile-fail/issue-17740.rs [new file with mode: 0644]
src/test/compile-fail/issue-19707.rs [new file with mode: 0644]
src/test/compile-fail/issue-5543.rs
src/test/compile-fail/issue-7364.rs
src/test/compile-fail/mut-not-freeze.rs
src/test/compile-fail/resolve-label.rs [new file with mode: 0644]
src/test/compile-fail/task-rng-isnt-sendable.rs
src/test/run-make/unicode-input/multiple_files.rs
src/test/run-make/unicode-input/span_length.rs
src/test/run-pass/dst-raw.rs
src/test/run-pass/dst-struct-sole.rs
src/test/run-pass/dst-struct.rs
src/test/run-pass/dst-trait.rs
src/test/run-pass/inconsistent-lifetime-mismatch.rs [new file with mode: 0644]
src/test/run-pass/issue-13655.rs [new file with mode: 0644]
src/test/run-pass/issue-13665.rs [new file with mode: 0644]
src/test/run-pass/issue-13808.rs [new file with mode: 0644]
src/test/run-pass/issue-15155.rs
src/test/run-pass/issue-17361.rs
src/test/run-pass/issue-18906.rs [new file with mode: 0644]
src/test/run-pass/issue-7663.rs
src/test/run-pass/match-ref-binding-in-guard-3256.rs
src/test/run-pass/method-recursive-blanket-impl.rs
src/test/run-pass/tcp-connect-timeouts.rs
src/test/run-pass/trait-static-method-generic-inference.rs [new file with mode: 0644]
src/test/run-pass/unsized.rs
src/test/run-pass/unsized2.rs
src/test/run-pass/vector-sort-panic-safe.rs
src/test/run-pass/writealias.rs

index 17ae845bf0773da92ce98f685375a92e3e709b2f..a2394101f3a72f8a30a7cc952bd712289165fba9 100644 (file)
@@ -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:
index bdda15dcc1835a9d63e40766707ef9c52da85c94..963627dbe099723f16c3cf12512f33d2d6815154 100644 (file)
@@ -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
index a9f45907b8110b50716f02bbe0ebefd43fcb00b5..08461f9dcc2b760c895a92d6a35a659ebeca782d 100644 (file)
@@ -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
index 632df3c754b8d153efdf193e1365f7a5bfa73366..f36ca4db7ca7ef13eddcbaa26cc46c5fc2e81af1 100644 (file)
@@ -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
index 1a122572e434c4c7a05f3c906209735fcbdab964..bf07d6de0e026eb766a27eeda227a63082f806af 100644 (file)
@@ -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
index 87a3abd8f226bef6f68d36f86301db06037b2898..29c98e22ee9788d70fb19cecbcc0d9bb929ad5c4 100644 (file)
@@ -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<int>, Receiver<int>) = channel();
 
@@ -102,12 +102,12 @@ into its component parts).
 let (tx, rx): (Sender<int>, Receiver<int>) = channel();
 ```
 
-The child task will use the sender to send data to the parent task, which will
+The child thread will use the sender to send data to the parent thread, which will
 wait to receive the data on the receiver. The next statement spawns the child
-task.
+thread.
 
 ```{rust,ignore}
-# use std::task::spawn;
+# use std::thread::spawn;
 # fn some_expensive_computation() -> int { 42 }
 # let (tx, rx) = channel();
 spawn(move || {
@@ -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::<f64>());
 # let numbers_arc = Arc::new(numbers);
 # let num = 4;
-let task_numbers = numbers_arc.clone();
+let thread_numbers = numbers_arc.clone();
 spawn(move || {
-    // Capture task_numbers and use it as if it was the underlying vector
-    println!("{}-norm = {}", num, pnorm(task_numbers.as_slice(), num));
+    // Capture thread_numbers and use it as if it was the underlying vector
+    println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
 });
 # }
 ```
 
-# Handling task panics
+# Handling thread panics
 
 Rust has a built-in mechanism for raising exceptions. The `panic!()` macro
 (which can also be written with an error string as an argument: `panic!(
 ~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a
-boolean expression is false) are both ways to raise exceptions. When a task
-raises an exception, the task unwinds its stack—running destructors and
+boolean expression is false) are both ways to raise exceptions. When a thread
+raises an exception, the thread unwinds its stack—running destructors and
 freeing memory along the way—and then exits. Unlike exceptions in C++,
-exceptions in Rust are unrecoverable within a single task: once a task panics,
+exceptions in Rust are unrecoverable within a single thread: once a thread panics,
 there is no way to "catch" the exception.
 
-While it isn't possible for a task to recover from panicking, tasks may notify
+While it isn't possible for a thread to recover from panicking, threads may notify
 each other if they panic. The simplest way of handling a panic is with the
 `try` function, which is similar to `spawn`, but immediately blocks and waits
-for the child task to finish. `try` returns a value of type
+for the child thread to finish. `try` returns a value of type
 `Result<T, Box<Any + Send>>`. `Result` is an `enum` type with two variants:
 `Ok` and `Err`. In this case, because the type arguments to `Result` are `int`
 and `()`, callers can pattern-match on a result to check whether it's an `Ok`
@@ -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).
index 22cbd18a86520a46f8b9c2998ae28fc8b53f32c9..d094c47da93bb3f1386e61ae2dd9d210cdf23e0a 100644 (file)
@@ -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 <you@example.com>"]
 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 '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
+thread '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
 ```
 
 Lots of output! Let's break this down:
@@ -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 '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
+thread '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
 ```
 
 After all the tests run, Rust will show us any output from our failed tests.
@@ -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<T>` side with the `recv()` method.  This
 method blocks until it gets a message. There's a similar method, `.try_recv()`,
 which returns an `Result<T, TryRecvError>` and does not block.
 
-If you want to send messages to the task as well, create two channels!
+If you want to send messages to the thread as well, create two channels!
 
 ```{rust,ignore}
 let (tx1, rx1) = channel();
 let (tx2, rx2) = channel();
 
 spawn(move || {
-    tx1.send("Hello from a task!".to_string());
+    tx1.send("Hello from a thread!".to_string());
     let message = rx2.recv();
     println!("{}", message);
 });
@@ -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}
index 779099558220a9e96cfc7b1a4d02707e4cdf6a49..e54bf0eb24282d3670d04549bbf752b6a73ce4ab 100644 (file)
@@ -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)
index 5be97034357eb11dde654053571898fa2cc9a924..a4e9d85bffdf8eb203e0de8dc2f0319b06e1b130 100644 (file)
@@ -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;
 
index b71994c9836a16548f93d20a35bf31acb6033467..94c76aaa69518aa37f461c9156d0427bbb64791a 100644 (file)
@@ -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 &mdash; once it has been spawned &mdash; in the
+A thread begins its lifecycle &mdash; once it has been spawned &mdash; 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 &mdash;
 when a message arrives at a sender, or a buffer opens to receive a message
-&mdash; then the blocked task will unblock and transition back to *running*.
+&mdash; 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.
index c22cd9c20479cf6e4fe044252e3f19d5ba42e170..9d0450285091c13703745d94a3ed53a611a3946a 100644 (file)
                <context attribute="CharEscape" lineEndContext="#pop" name="CharEscape">
                        <AnyChar String="nrt\&apos;&quot;" attribute="CharEscape" context="#pop"/>
                        <RegExpr String="x[0-9a-fA-F]{2}" attribute="CharEscape" context="#pop"/>
+                       <RegExpr String="u\{[0-9a-fA-F]{1,6}\}" attribute="CharEscape" context="#pop"/>
                        <RegExpr String="u[0-9a-fA-F]{4}" attribute="CharEscape" context="#pop"/>
                        <RegExpr String="U[0-9a-fA-F]{8}" attribute="CharEscape" context="#pop"/>
                        <RegExpr String="." attribute="Error" context="#pop"/>
                        <Detect2Chars char="*" char1="/" attribute="Comment" context="#pop" endRegion="Comment"/>
                </context>
        </contexts>
-    <itemDatas>
+       <itemDatas>
                <itemData name="Normal Text"  defStyleNum="dsNormal"/>
                <itemData name="Keyword"      defStyleNum="dsKeyword" color="#770088" bold="1"/>
                <itemData name="Self"         defStyleNum="dsKeyword" color="#FF0000" bold="1"/>
index 95e647c91cfe60ce71ae2cd2fa748fb52c9b0375..ea2a98db2dc1f94bc98fce3668c9a33fa18fadfd 100644 (file)
@@ -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])
index 0ff9af7aca133625e3b98670951babfeafc3b1b0..00af6d358e5eb3d3643592bb929db3c7adf2b275 100644 (file)
@@ -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
index f7b19cf6fbf5e06ef290bbbe45878b1659f9ac36..bdb616fcc99b83d744c28afed4ce5c8dcd250a36 100644 (file)
@@ -61,7 +61,7 @@ fn id() -> token::Token {
             "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 id() -> token::Token {
             "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 id() -> token::Token {
             "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 id() -> token::Token {
             "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 id() -> token::Token {
             "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<String, token::Token>) -> 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<String, token::Token>) -> TokenAn
     };
 
     let sp = syntax::codemap::Span {
-        lo: syntax::codemap::BytePos(from_str::<u32>(start).unwrap() - offset),
-        hi: syntax::codemap::BytePos(from_str::<u32>(end).unwrap() + 1),
+        lo: syntax::codemap::BytePos(start.parse::<u32>().unwrap() - offset),
+        hi: syntax::codemap::BytePos(end.parse::<u32>().unwrap() + 1),
         expn_id: syntax::codemap::NO_EXPANSION
     };
 
@@ -247,7 +247,9 @@ fn next(r: &mut lexer::StringReader) -> TokenAndSpan {
     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 @@ macro_rules! matches (
                     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(..),
index 3e235caab18ad1431befa20a802419cb497f1c88..21c47cdf3d752129153e6d983120417650eb3410 100644 (file)
@@ -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::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 @@ struct Cycle {
 
         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)...
     }
index c6b6a784f06e3f912f085a9f1d0cc0e6f3f30426..cdc30efd2d9a289049492fe8e518f98c1f9a7cc2 100644 (file)
@@ -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 @@ pub fn stats_print() {}
 mod test {
     extern crate test;
     use self::test::Bencher;
-    use core::ptr::RawPtr;
+    use core::ptr::PtrExt;
     use heap;
 
     #[test]
index 13dc4474c1a193e6124f1993cac4c78237d52bac..214fae02ce27210e3010f41ec6cdda38c2c65fea 100644 (file)
@@ -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<T>` type).
+//! Thread-local reference-counted boxes (the `Rc<T>` type).
 //!
 //! The `Rc<T>` type provides shared ownership of an immutable value. Destruction is deterministic,
 //! and will occur as soon as the last owner is gone. It is marked as non-sendable because it
 use core::ops::{Deref, Drop};
 use core::option::Option;
 use core::option::Option::{Some, None};
-use core::ptr::{mod, RawPtr};
+use core::ptr::{mod, PtrExt};
 use core::result::Result;
 use core::result::Result::{Ok, Err};
 
index 1f4df1fd0a5a28e1199ac28ca10c0ec90bc39433..b0fa5434a1474c65f2ebb64be23a4316f337b87f 100644 (file)
@@ -412,7 +412,7 @@ unsafe fn destroy(&mut self, len: uint) {
         let size = calculate_size::<T>(self.capacity);
         deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size,
                    mem::min_align_of::<TypedArenaChunk<T>>());
-        if next.is_not_null() {
+        if !next.is_null() {
             let capacity = (*next).capacity;
             (*next).destroy(capacity);
         }
index f20b37cb60f265f82ab89b90ce49851c724f50f1..d8ce79f4fe90d29c3e9f28e80cf46848cf7f3a94 100644 (file)
@@ -95,7 +95,7 @@ fn some(n: &mut T) -> Rawlink<T> {
     /// 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())
         }
     }
 
index 363d30abd0347b02eef24cd234b3abb6a1c08dc7..fe9d8de440a17aca42c15bad4f6d11fc071b031b 100644 (file)
@@ -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;
index 404804cd91d2ee76e980e26182a00d34bc42e66a..c55a8ba104ebefc86c31fd17cc2053a02f82378d 100644 (file)
@@ -96,7 +96,7 @@
 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 @@ fn test_reverse() {
     fn test_sort() {
         for len in range(4u, 25) {
             for _ in range(0i, 100) {
-                let mut v = task_rng().gen_iter::<uint>().take(len)
+                let mut v = thread_rng().gen_iter::<uint>().take(len)
                                       .collect::<Vec<uint>>();
                 let mut v1 = v.clone();
 
@@ -1999,7 +2002,7 @@ fn test_sort_stability() {
                 // number this element is, i.e. the second elements
                 // will occur in sorted order.
                 let mut v = range(0, len).map(|_| {
-                        let n = task_rng().gen::<uint>() % 10;
+                        let n = thread_rng().gen::<uint>() % 10;
                         counts[n] += 1;
                         (n, counts[n])
                     }).collect::<Vec<(uint, int)>>();
index 881eb45f7cce74afc91c48d9ee66d64447aaae29..7c7a7e19a2f18c92ece50074a8dceaf1e5992643 100644 (file)
@@ -89,8 +89,6 @@
 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 @@ fn test_into_maybe_owned() {
 #[cfg(test)]
 mod bench {
     use super::*;
-    use prelude::*;
+    use prelude::{SliceExt, IteratorExt, DoubleEndedIteratorExt};
     use test::Bencher;
     use test::black_box;
 
index 9460b9a8966468f40dccd332fa2c25c0f8178624..c6c19cae75f1efc1b55a005d0f6a8eeb6cf307d6 100644 (file)
@@ -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<u8>,
 }
 
+/// A possible error value from the `String::from_utf8` function.
+#[stable]
+pub struct FromUtf8Error {
+    bytes: Vec<u8>,
+    error: Utf8Error,
+}
+
+/// A possible error value from the `String::from_utf16` function.
+#[stable]
+#[allow(missing_copy_implementations)]
+pub struct FromUtf16Error(());
+
 impl String {
     /// Creates a new string buffer initialized with the empty string.
     ///
@@ -98,19 +112,20 @@ pub fn from_str(string: &str) -> String {
     /// use std::str::Utf8Error;
     ///
     /// let hello_vec = vec![104, 101, 108, 108, 111];
-    /// let s = String::from_utf8(hello_vec);
-    /// assert_eq!(s, Ok("hello".to_string()));
+    /// let s = String::from_utf8(hello_vec).unwrap();
+    /// assert_eq!(s, "hello");
     ///
     /// let invalid_vec = vec![240, 144, 128];
-    /// let s = String::from_utf8(invalid_vec);
-    /// assert_eq!(s, Err((vec![240, 144, 128], Utf8Error::TooShort)));
+    /// let s = String::from_utf8(invalid_vec).err().unwrap();
+    /// assert_eq!(s.utf8_error(), Utf8Error::TooShort);
+    /// assert_eq!(s.into_bytes(), vec![240, 144, 128]);
     /// ```
     #[inline]
-    #[unstable = "error type may change"]
-    pub fn from_utf8(vec: Vec<u8>) -> Result<String, (Vec<u8>, Utf8Error)> {
+    #[stable]
+    pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
         match str::from_utf8(vec.as_slice()) {
             Ok(..) => Ok(String { vec: vec }),
-            Err(e) => Err((vec, e))
+            Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
         }
     }
 
@@ -124,7 +139,7 @@ pub fn from_utf8(vec: Vec<u8>) -> Result<String, (Vec<u8>, Utf8Error)> {
     /// 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 @@ macro_rules! error(() => ({
     /// // 𝄞music
     /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075,
     ///                   0x0073, 0x0069, 0x0063];
-    /// assert_eq!(String::from_utf16(v), Some("𝄞music".to_string()));
+    /// assert_eq!(String::from_utf16(v).unwrap(),
+    ///            "𝄞music".to_string());
     ///
     /// // 𝄞mu<invalid>ic
     /// v[4] = 0xD800;
-    /// assert_eq!(String::from_utf16(v), None);
+    /// assert!(String::from_utf16(v).is_err());
     /// ```
-    #[unstable = "error value in return may change"]
-    pub fn from_utf16(v: &[u16]) -> Option<String> {
+    #[stable]
+    pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> {
         let mut s = String::with_capacity(v.len());
         for c in unicode_str::utf16_items(v) {
             match c {
                 Utf16Item::ScalarValue(c) => s.push(c),
-                Utf16Item::LoneSurrogate(_) => return None
+                Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())),
             }
         }
-        Some(s)
+        Ok(s)
     }
 
     /// Decode a UTF-16 encoded vector `v` into a string, replacing
@@ -293,12 +309,13 @@ pub fn from_utf16_lossy(v: &[u16]) -> 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 @@ pub fn from_chars(chs: &[char]) -> String {
     /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
     /// * We assume that the `Vec` contains valid UTF-8.
     #[inline]
-    #[unstable = "function just moved from string::raw"]
+    #[stable]
     pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
         String {
             vec: Vec::from_raw_parts(buf, length, capacity),
@@ -344,7 +361,7 @@ pub unsafe fn from_raw_buf_len(buf: *const u8, len: uint) -> 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<u8>) -> String {
         String { vec: bytes }
     }
@@ -369,12 +386,12 @@ pub fn into_bytes(self) -> Vec<u8> {
     /// # 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 @@ pub fn from_char(length: uint, ch: char) -> 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 @@ pub fn push_str(&mut self, string: &str) {
     /// # 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 @@ pub fn grow(&mut self, count: uint, ch: char) {
     /// 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 @@ pub fn reserve_additional(&mut self, extra: uint) {
         self.vec.reserve(extra)
     }
 
-    /// Reserves capacity for at least `additional` more bytes to be inserted in the given
-    /// `String`. The collection may reserve more space to avoid frequent reallocations.
+    /// 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 @@ pub fn reserve_additional(&mut self, extra: uint) {
     /// 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 @@ pub fn reserve(&mut self, additional: uint) {
     /// 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 @@ pub fn reserve_exact(&mut self, additional: uint) {
     /// 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 @@ pub fn shrink_to_fit(&mut self) {
     /// 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 @@ pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
     /// assert_eq!(s.as_slice(), "he");
     /// ```
     #[inline]
-    #[unstable = "the panic conventions for strings are under development"]
+    #[stable]
     pub fn truncate(&mut self, new_len: uint) {
         assert!(self.is_char_boundary(new_len));
         self.vec.truncate(new_len)
@@ -587,7 +608,7 @@ pub fn truncate(&mut self, new_len: uint) {
     /// assert_eq!(s.pop(), None);
     /// ```
     #[inline]
-    #[unstable = "this function was just renamed from pop_char"]
+    #[stable]
     pub fn pop(&mut self) -> Option<char> {
         let len = self.len();
         if len == 0 {
@@ -602,7 +623,7 @@ pub fn pop(&mut self) -> Option<char> {
     }
 
     /// 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 @@ pub fn pop(&mut self) -> Option<char> {
     ///
     /// # Panics
     ///
-    /// If `idx` does not lie on a character boundary, then this function will
-    /// panic.
+    /// If `idx` does not lie on a character boundary, or if it is out of
+    /// bounds, then this function will panic.
     ///
     /// # Examples
     ///
     /// ```
     /// let mut s = String::from_str("foo");
-    /// assert_eq!(s.remove(0), Some('f'));
-    /// assert_eq!(s.remove(1), Some('o'));
-    /// assert_eq!(s.remove(0), Some('o'));
-    /// assert_eq!(s.remove(0), None);
+    /// assert_eq!(s.remove(0), 'f');
+    /// assert_eq!(s.remove(1), 'o');
+    /// assert_eq!(s.remove(0), 'o');
     /// ```
-    #[unstable = "the panic semantics of this function and return type \
-                  may change"]
-    pub fn remove(&mut self, idx: uint) -> Option<char> {
+    #[stable]
+    pub fn remove(&mut self, idx: uint) -> char {
         let len = self.len();
-        if idx >= len { return None }
+        assert!(idx <= len);
 
         let CharRange { ch, next } = self.char_range_at(idx);
         unsafe {
@@ -636,7 +655,7 @@ pub fn remove(&mut self, idx: uint) -> Option<char> {
                              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 @@ pub fn remove(&mut self, idx: uint) -> Option<char> {
     ///
     /// 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 @@ pub fn insert(&mut self, idx: uint, ch: char) {
     /// }
     /// assert_eq!(s.as_slice(), "olleh");
     /// ```
-    #[unstable = "the name of this method may be changed"]
+    #[stable]
     pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
         &mut self.vec
     }
@@ -713,6 +732,7 @@ pub fn len(&self) -> uint { self.vec.len() }
     /// 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 @@ pub fn clear(&mut self) {
     }
 }
 
+impl FromUtf8Error {
+    /// Consume this error, returning the bytes that were attempted to make a
+    /// `String` with.
+    #[stable]
+    pub fn into_bytes(self) -> Vec<u8> { self.bytes }
+
+    /// Access the underlying UTF8-error that was the cause of this error.
+    #[stable]
+    pub fn utf8_error(&self) -> Utf8Error { self.error }
+}
+
+impl fmt::Show for FromUtf8Error {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        self.error.fmt(f)
+    }
+}
+
+impl fmt::Show for FromUtf16Error {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        "invalid utf-16: lone surrogate found".fmt(f)
+    }
+}
+
 #[experimental = "waiting on FromIterator stabilization"]
 impl FromIterator<char> for String {
     fn from_iter<I:Iterator<char>>(iterator: I) -> String {
@@ -933,6 +976,7 @@ fn from_str(s: &str) -> Option<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 @@ fn test_from_str() {
     #[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 @@ fn test_from_utf16() {
     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 @@ fn test_str_add() {
     #[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");
     }
 
index b45424a5eed3f7d4209e62880fd653eed298cbe5..01a1e7f97110a93668dfa1a641e82459b4a23834 100644 (file)
 use clone::Clone;
 use cmp::PartialEq;
 use default::Default;
-use kinds::{marker, Copy};
+use kinds::{Copy, Send};
 use ops::{Deref, DerefMut, Drop};
 use option::Option;
 use option::Option::{None, Some};
 #[stable]
 pub struct Cell<T> {
     value: UnsafeCell<T>,
-    noshare: marker::NoSync,
 }
 
 impl<T:Copy> Cell<T> {
@@ -176,7 +175,6 @@ impl<T:Copy> Cell<T> {
     pub fn new(value: T) -> Cell<T> {
         Cell {
             value: UnsafeCell::new(value),
-            noshare: marker::NoSync,
         }
     }
 
@@ -208,6 +206,9 @@ pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
     }
 }
 
+#[stable]
+unsafe impl<T> Send for Cell<T> where T: Send {}
+
 #[stable]
 impl<T:Copy> Clone for Cell<T> {
     fn clone(&self) -> Cell<T> {
@@ -235,7 +236,6 @@ fn eq(&self, other: &Cell<T>) -> bool {
 pub struct RefCell<T> {
     value: UnsafeCell<T>,
     borrow: Cell<BorrowFlag>,
-    noshare: marker::NoSync,
 }
 
 // Values [1, MAX-1] represent the number of `Ref` active
@@ -251,7 +251,6 @@ pub fn new(value: T) -> RefCell<T> {
         RefCell {
             value: UnsafeCell::new(value),
             borrow: Cell::new(UNUSED),
-            noshare: marker::NoSync,
         }
     }
 
@@ -341,6 +340,9 @@ pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
     }
 }
 
+#[stable]
+unsafe impl<T> Send for RefCell<T> where T: Send {}
+
 #[stable]
 impl<T: Clone> Clone for RefCell<T> {
     fn clone(&self) -> RefCell<T> {
index 686ccf6f1a2513c25e2c7dfd5aa2265d11b90ccb..5d84d0c7797ecfe5e20be75223be58fc107e0963 100644 (file)
@@ -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()
     }
index 2cd9e7c45098ea82425f62351e62b13dc423e98d..781dbb0e55a3f8a99b61d8d084a4b5ab4ef1575b 100644 (file)
@@ -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)*); })
index f6abc8da79c0c9d1ddb6bbea9445d4f56a7f035b..fd1598db8cdfccbce8f40bf4f072ff51b80d7212 100644 (file)
@@ -57,7 +57,7 @@
 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};
index 8c724b4d8521fdeec603b29edf7876ea5fa977ec..75bb8d33ea85f514419190b2d52be05d579d8f51 100644 (file)
 //! typically limited to a few patterns.
 //!
 //! Use the [`null` function](fn.null.html) to create null pointers,
-//! the [`is_null`](trait.RawPtr.html#tymethod.is_null)
-//! and [`is_not_null`](trait.RawPtr.html#method.is_not_null)
-//! methods of the [`RawPtr` trait](trait.RawPtr.html) to check for null.
-//! The `RawPtr` trait is imported by the prelude, so `is_null` etc.
-//! work everywhere. The `RawPtr` also defines the `offset` method,
+//! the [`is_null`](trait.PtrExt.html#tymethod.is_null)
+//! methods of the [`PtrExt` trait](trait.PtrExt.html) to check for null.
+//! The `PtrExt` trait is imported by the prelude, so `is_null` etc.
+//! work everywhere. The `PtrExt` also defines the `offset` method,
 //! for pointer math.
 //!
 //! # Common ways to create unsafe pointers
 //! but C APIs hand out a lot of pointers generally, so are a common source
 //! of unsafe pointers in Rust.
 
+#![stable]
+
 use mem;
 use clone::Clone;
 use intrinsics;
+use option::Option::{mod, Some, None};
 use kinds::{Send, Sync};
-use option::Option;
-use option::Option::{Some, None};
 
 use cmp::{PartialEq, Eq, Ord, PartialOrd, Equiv};
-use cmp::Ordering;
-use cmp::Ordering::{Less, Equal, Greater};
+use cmp::Ordering::{mod, Less, Equal, Greater};
 
 // FIXME #19649: instrinsic docs don't render, so these have no docs :(
 
 /// assert!(p.is_null());
 /// ```
 #[inline]
-#[unstable = "may need a different name after pending changes to pointer types"]
+#[stable]
 pub fn null<T>() -> *const T { 0 as *const T }
 
 /// Creates a null mutable raw pointer.
@@ -135,31 +134,31 @@ pub fn null<T>() -> *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<T>() -> *mut T { 0 as *mut T }
 
-/// Zeroes out `count * size_of::<T>` bytes of memory at `dst`. `count` may be `0`.
+/// Zeroes out `count * size_of::<T>` bytes of memory at `dst`. `count` may be
+/// `0`.
 ///
 /// # Safety
 ///
-/// Beyond accepting a raw pointer, this is unsafe because it will not drop the contents of `dst`,
-/// and may be used to create invalid instances of `T`.
+/// Beyond accepting a raw pointer, this is unsafe because it will not drop the
+/// contents of `dst`, and may be used to create invalid instances of `T`.
 #[inline]
-#[experimental = "uncertain about naming and semantics"]
-#[allow(experimental)]
+#[unstable = "may play a larger role in std::ptr future extensions"]
 pub unsafe fn zero_memory<T>(dst: *mut T, count: uint) {
     set_memory(dst, 0, count);
 }
 
 /// Swaps the values at two mutable locations of the same type, without
-/// deinitialising either. They may overlap, unlike `mem::swap` which is otherwise
-/// equivalent.
+/// deinitialising either. They may overlap, unlike `mem::swap` which is
+/// otherwise equivalent.
 ///
 /// # Safety
 ///
 /// This is only unsafe because it accepts a raw pointer.
 #[inline]
-#[unstable]
+#[stable]
 pub unsafe fn swap<T>(x: *mut T, y: *mut T) {
     // Give ourselves some scratch space to work with
     let mut tmp: T = mem::uninitialized();
@@ -183,7 +182,7 @@ pub unsafe fn swap<T>(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<T>(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<T>(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<T>(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<T>(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<T>(dest: *mut T) -> T {
     // Copy the data out from `dest`:
     let tmp = read(&*dest);
@@ -226,8 +224,8 @@ pub unsafe fn read_and_zero<T>(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<T>(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<T>(dst: *mut T, src: T) {
     intrinsics::move_val_init(&mut *dst, src)
 }
 
 /// Methods on raw pointers
-pub trait RawPtr<T> {
-    /// Returns a null raw pointer.
+#[stable]
+pub trait PtrExt<T> {
+    /// Returns the null pointer.
+    #[deprecated = "call ptr::null instead"]
     fn null() -> Self;
 
     /// Returns true if the pointer is null.
-    fn is_null(&self) -> bool;
+    #[stable]
+    fn is_null(self) -> bool;
 
-    /// Returns true if the pointer is not null.
-    fn is_not_null(&self) -> bool { !self.is_null() }
+    /// Returns true if the pointer is not equal to the null pointer.
+    #[deprecated = "use !p.is_null() instead"]
+    fn is_not_null(self) -> bool { !self.is_null() }
 
-    /// Returns the address of the pointer.
-    fn to_uint(&self) -> uint;
+    /// Returns true if the pointer is not null.
+    #[deprecated = "use `as uint` instead"]
+    fn to_uint(self) -> uint;
 
-    /// Returns `None` if the pointer is null, or else returns a reference to the
-    /// value wrapped in `Some`.
+    /// Returns `None` if the pointer is null, or else returns a reference to
+    /// the value wrapped in `Some`.
     ///
     /// # Safety
     ///
-    /// While this method and its mutable counterpart are useful for null-safety,
-    /// it is important to note that this is still an unsafe operation because
-    /// the returned value could be pointing to invalid memory.
+    /// While this method and its mutable counterpart are useful for
+    /// null-safety, it is important to note that this is still an unsafe
+    /// operation because the returned value could be pointing to invalid
+    /// memory.
+    #[unstable = "Option is not clearly the right return type, and we may want \
+                  to tie the return lifetime to a borrow of the raw pointer"]
     unsafe fn as_ref<'a>(&self) -> Option<&'a T>;
 
     /// Calculates the offset from a pointer. `count` is in units of T; e.g. a
@@ -272,39 +278,51 @@ fn is_not_null(&self) -> bool { !self.is_null() }
     ///
     /// # Safety
     ///
-    /// The offset must be in-bounds of the object, or one-byte-past-the-end. Otherwise
-    /// `offset` invokes Undefined Behaviour, regardless of whether the pointer is used.
+    /// The offset must be in-bounds of the object, or one-byte-past-the-end.
+    /// Otherwise `offset` invokes Undefined Behaviour, regardless of whether
+    /// the pointer is used.
+    #[stable]
     unsafe fn offset(self, count: int) -> Self;
 }
 
 /// Methods on mutable raw pointers
-pub trait RawMutPtr<T>{
-    /// Returns `None` if the pointer is null, or else returns a mutable reference
-    /// to the value wrapped in `Some`.
+#[stable]
+pub trait MutPtrExt<T>{
+    /// Returns `None` if the pointer is null, or else returns a mutable
+    /// reference to the value wrapped in `Some`.
     ///
     /// # Safety
     ///
     /// As with `as_ref`, this is unsafe because it cannot verify the validity
     /// of the returned pointer.
+    #[unstable = "Option is not clearly the right return type, and we may want \
+                  to tie the return lifetime to a borrow of the raw pointer"]
     unsafe fn as_mut<'a>(&self) -> Option<&'a mut T>;
 }
 
-impl<T> RawPtr<T> for *const T {
+#[stable]
+impl<T> PtrExt<T> for *const T {
     #[inline]
+    #[deprecated = "call ptr::null instead"]
     fn null() -> *const T { null() }
 
     #[inline]
-    fn is_null(&self) -> bool { *self == RawPtr::null() }
+    #[stable]
+    fn is_null(self) -> bool { self as uint == 0 }
 
     #[inline]
-    fn to_uint(&self) -> uint { *self as uint }
+    #[deprecated = "use `as uint` instead"]
+    fn to_uint(self) -> uint { self as uint }
 
     #[inline]
+    #[stable]
     unsafe fn offset(self, count: int) -> *const T {
         intrinsics::offset(self, count)
     }
 
     #[inline]
+    #[unstable = "return value does not necessarily convey all possible \
+                  information"]
     unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
         if self.is_null() {
             None
@@ -314,22 +332,29 @@ unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
     }
 }
 
-impl<T> RawPtr<T> for *mut T {
+#[stable]
+impl<T> PtrExt<T> for *mut T {
     #[inline]
+    #[deprecated = "call ptr::null instead"]
     fn null() -> *mut T { null_mut() }
 
     #[inline]
-    fn is_null(&self) -> bool { *self == RawPtr::null() }
+    #[stable]
+    fn is_null(self) -> bool { self as uint == 0 }
 
     #[inline]
-    fn to_uint(&self) -> uint { *self as uint }
+    #[deprecated = "use `as uint` instead"]
+    fn to_uint(self) -> uint { self as uint }
 
     #[inline]
+    #[stable]
     unsafe fn offset(self, count: int) -> *mut T {
         intrinsics::offset(self as *const T, count) as *mut T
     }
 
     #[inline]
+    #[unstable = "return value does not necessarily convey all possible \
+                  information"]
     unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
         if self.is_null() {
             None
@@ -339,8 +364,11 @@ unsafe fn as_ref<'a>(&self) -> Option<&'a T> {
     }
 }
 
-impl<T> RawMutPtr<T> for *mut T {
+#[stable]
+impl<T> MutPtrExt<T> for *mut T {
     #[inline]
+    #[unstable = "return value does not necessarily convey all possible \
+                  information"]
     unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> {
         if self.is_null() {
             None
@@ -510,28 +538,33 @@ fn ge(&self, other: &*mut T) -> bool { *self >= *other }
 /// raw `*mut T` (which conveys no particular ownership semantics).
 /// Useful for building abstractions like `Vec<T>` or `Box<T>`, which
 /// internally use raw pointers to manage the memory that they own.
+#[unstable = "recently added to this module"]
 pub struct Unique<T>(pub *mut T);
 
 /// `Unique` pointers are `Send` if `T` is `Send` because the data they
 /// reference is unaliased. Note that this aliasing invariant is
 /// unenforced by the type system; the abstraction using the
 /// `Unique` must enforce it.
+#[unstable = "recently added to this module"]
 unsafe impl<T:Send> Send for Unique<T> { }
 
 /// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
 /// reference is unaliased. Note that this aliasing invariant is
 /// unenforced by the type system; the abstraction using the
 /// `Unique` must enforce it.
+#[unstable = "recently added to this module"]
 unsafe impl<T:Sync> Sync for Unique<T> { }
 
 impl<T> Unique<T> {
     /// Returns a null Unique.
+    #[unstable = "recently added to this module"]
     pub fn null() -> Unique<T> {
-        Unique(RawPtr::null())
+        Unique(null_mut())
     }
 
     /// Return an (unsafe) pointer into the memory owned by `self`.
+    #[unstable = "recently added to this module"]
     pub unsafe fn offset(self, offset: int) -> *mut T {
-        (self.0 as *const T).offset(offset) as *mut T
+        self.0.offset(offset)
     }
 }
index 8014b4dc89d70e10faf55286c45e1bc71885e157..bd1c6dbcf1e9a4166d4a111cbbc32166dab2969f 100644 (file)
@@ -332,7 +332,7 @@ pub fn ok(self) -> Option<T> {
 
     /// Convert from `Result<T, E>` to `Option<E>`
     ///
-    /// Converts `self` into an `Option<T>`, consuming `self`,
+    /// Converts `self` into an `Option<E>`, consuming `self`,
     /// and discarding the value, if any.
     ///
     /// # Example
index d25f96ac15fa656b32e8d4e14975ac080381da37..f356a0867d2529b57397d944790dbca42cff5ccb 100644 (file)
@@ -47,7 +47,7 @@
 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;
index 1fc5f90028dad73ea219ff409ae8a59dce147f55..8db672b26537532fa44ad720c5cc91e7558e5c9b 100644 (file)
@@ -28,7 +28,7 @@
 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 @@ pub struct CharRange {
 /// Unsafe operations
 #[deprecated]
 pub mod raw {
-    use ptr::RawPtr;
+    use ptr::PtrExt;
     use raw::Slice;
     use slice::SliceExt;
     use str::StrExt;
index 8c4f74027a52f0a7a9ede9a5b4e7d8b17ebcadb5..aa1550ae5b874cfbfd5d08dfcfb82e4af1d4ccf9 100644 (file)
@@ -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);
index 431a530726a083291ab0a38cf547e304d3d191cb..f31f3468a4c0065947d957f11a65f0e36c577a57 100644 (file)
@@ -64,7 +64,7 @@ fn zero_case<R:Rng>(rng: &mut R, _u: f64) -> f64 {
 /// 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)]
index d33d838766f220da9cda5952f77e8fd7308b1c60..618db380db8d4d8bdf13e9df1ac8dbf9574d974a 100644 (file)
@@ -44,7 +44,7 @@
 /// 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 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 /// 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 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 /// 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 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 /// 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 {
index 58125c67fdae9edef566e871a5a96de8d1ff453a..54cb8ae19071893eb320ef1f13bc208111c83ea1 100644 (file)
@@ -96,7 +96,7 @@ pub struct Weighted<T> {
 ///                      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));
index 16413af626739ed8fa65817f20d3aba8573359d3..3507282ec486af51ce63639998b1c1c624ed3fd7 100644 (file)
@@ -81,7 +81,7 @@ fn zero_case<R:Rng>(rng: &mut R, u: f64) -> f64 {
 ///
 /// // 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 @@ fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 {
 ///
 /// // 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)]
index 6301623bbdc184ba429a2296a30432a62c32adac..20ba3566d5b1226601d66f2697a9a8d15c97c63a 100644 (file)
@@ -39,7 +39,7 @@
 ///
 /// 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);
index 514ff81da518ec789c5614c169b197aa7a9887b0..273b991bc22f2a6561f032c014164b82b34551dc 100644 (file)
@@ -138,10 +138,10 @@ fn next_f64(&mut self) -> f64 {
     /// # 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 @@ fn fill_bytes(&mut self, dest: &mut [u8]) {
     /// # Example
     ///
     /// ```rust
-    /// use std::rand::{task_rng, Rng};
+    /// use std::rand::{thread_rng, Rng};
     ///
-    /// let mut rng = task_rng();
+    /// let mut rng = thread_rng();
     /// let x: uint = rng.gen();
     /// println!("{}", x);
     /// println!("{}", rng.gen::<(f64, bool)>());
@@ -191,9 +191,9 @@ fn gen<T: Rand>(&mut self) -> T {
     /// # Example
     ///
     /// ```
-    /// use std::rand::{task_rng, Rng};
+    /// use std::rand::{thread_rng, Rng};
     ///
-    /// let mut rng = task_rng();
+    /// let mut rng = thread_rng();
     /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
     /// println!("{}", x);
     /// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
@@ -218,9 +218,9 @@ fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
     /// # 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 @@ fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
     /// # 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 @@ fn gen_weighted_bool(&mut self, n: uint) -> bool {
     /// # Example
     ///
     /// ```rust
-    /// use std::rand::{task_rng, Rng};
+    /// use std::rand::{thread_rng, Rng};
     ///
-    /// let s: String = task_rng().gen_ascii_chars().take(10).collect();
+    /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
     /// println!("{}", s);
     /// ```
     fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
@@ -266,10 +266,10 @@ fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
     /// # Example
     ///
     /// ```
-    /// use std::rand::{task_rng, Rng};
+    /// use std::rand::{thread_rng, Rng};
     ///
     /// let choices = [1i, 2, 4, 8, 16, 32];
-    /// let mut rng = task_rng();
+    /// let mut rng = thread_rng();
     /// println!("{}", rng.choose(&choices));
     /// assert_eq!(rng.choose(choices[..0]), None);
     /// ```
@@ -286,9 +286,9 @@ fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
     /// # 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 @@ fn next<T: rand::Rng>(t: &mut T) -> u32 {
         }
     }
 
-    pub fn rng() -> MyRng<rand::TaskRng> {
-        MyRng { inner: rand::task_rng() }
+    pub fn rng() -> MyRng<rand::ThreadRng> {
+        MyRng { inner: rand::thread_rng() }
     }
 
     pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
index 3b38fde3884f1996a199d0bc603d76fe6e2e68bb..e50153076c390698759ab5f9832b016c0f9c5b5b 100644 (file)
@@ -215,7 +215,7 @@ fn rand<R: Rng>(rng: &mut R) -> Option<T> {
 #[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 @@ fn floating_point_edge_cases() {
     fn rand_open() {
         // this is unlikely to catch an incorrect implementation that
         // generates exactly 0 or 1, but it keeps it sane.
-        let mut rng = task_rng();
+        let mut rng = thread_rng();
         for _ in range(0u, 1_000) {
             // strict inequalities
             let Open01(f) = rng.gen::<Open01<f64>>();
@@ -253,7 +253,7 @@ fn rand_open() {
 
     #[test]
     fn rand_closed() {
-        let mut rng = task_rng();
+        let mut rng = thread_rng();
         for _ in range(0u, 1_000) {
             // strict inequalities
             let Closed01(f) = rng.gen::<Closed01<f64>>();
index 105687b89fdd77fb9758bdcdc87f2dee0f2b3f00..86c02de76dcc6b146839d378ee3473d264c9e814 100644 (file)
@@ -519,8 +519,8 @@ fn parse_counted(&mut self) -> Result<(), Error> {
             };
         self.chari = closer;
         let greed = try!(self.get_next_greedy());
-        let inner = String::from_chars(
-            self.chars[start+1..closer]);
+        let inner = self.chars[start+1..closer].iter().cloned()
+                                               .collect::<String>();
 
         // Parse the min and max values from the regex.
         let (mut min, mut max): (uint, Option<uint>);
@@ -954,7 +954,7 @@ fn cur(&self) -> char {
     }
 
     fn slice(&self, start: uint, end: uint) -> String {
-        String::from_chars(self.chars[start..end])
+        self.chars[start..end].iter().cloned().collect()
     }
 }
 
index 0c204f759e6adb7b99f0951ac03db70c8c51359a..17521ff7ea54bb9ebcdaf01e6298451bdb21e68e 100644 (file)
@@ -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::<String>(),
+                                repeat("a").take(n).collect::<String>()).as_slice()).unwrap();
+    let text = repeat("a").take(n).collect::<String>();
     bench_assert_match(b, re, text.as_slice());
 }
 
 #[bench]
 fn literal(b: &mut Bencher) {
     let re = regex!("y");
-    let text = format!("{}y", "x".repeat(50));
+    let text = format!("{}y", repeat("x").take(50).collect::<String>());
     bench_assert_match(b, re, text.as_slice());
 }
 
 #[bench]
 fn not_literal(b: &mut Bencher) {
     let re = regex!(".y");
-    let text = format!("{}y", "x".repeat(50));
+    let text = format!("{}y", repeat("x").take(50).collect::<String>());
     bench_assert_match(b, re, text.as_slice());
 }
 
 #[bench]
 fn match_class(b: &mut Bencher) {
     let re = regex!("[abcdw]");
-    let text = format!("{}w", "xxxx".repeat(20));
+    let text = format!("{}w", repeat("xxxx").take(20).collect::<String>());
     bench_assert_match(b, re, text.as_slice());
 }
 
@@ -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::<String>());
     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::<String>();
     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::<String>();
     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::<Vec<u8>>();
     for (i, b) in bytes.iter_mut().enumerate() {
index 3edcd0b5156419ef29dc33743b6643db963ae39d..35c29f646e4a01b1917cff23aa3c3214b298b6b6 100644 (file)
@@ -1782,9 +1782,9 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
         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);
                     }
index 6782b3a74813e668e9aa680018ca9f1fd1753ec6..2a670b308b6b213d364c9e1014dd87b4babf39fb 100644 (file)
@@ -1308,7 +1308,7 @@ fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
             }
         }
       }
-      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);
index da1bd09ceffddcbffc99c71daf513ad76bda9f2c..c2992a81d208334d8d55154f6fb22940be885d6f 100644 (file)
@@ -25,7 +25,7 @@
 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 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         }).collect();
 
         let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1;
-        let br = String::from_char(total_width, '+');
+        let br = repeat('+').take(total_width).collect::<String>();
         try!(write!(f, "{}\n", br));
         for row in pretty_printed_matrix.into_iter() {
             try!(write!(f, "+"));
index 2f62858071f6a9204f4e9119ba03bbae9d8c7a98..3d3eac7b6ed9fe1d38e5aa3c4617bcf62b3fa5f5 100644 (file)
@@ -1043,7 +1043,6 @@ fn rebuild_ty_params(&self,
                 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 @@ fn rebuild_ty_param_bounds(&self,
                     // 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 @@ fn rebuild_ty_param_bounds(&self,
                             path: new_path,
                             ref_id: tr.ref_id,
                         }
-                    })
+                    }, modifier)
                 }
             }
         })
index 6f63ae166fe417e7c798572b636f22edd6dbfd69..730da26eda3dccc50f2fd722ffc334596191d193 100644 (file)
@@ -122,7 +122,7 @@ fn visit_item(&mut self, item: &ast::Item) {
             // 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 @@ fn visit_item(&mut self, item: &ast::Item) {
 
             // 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 @@ fn check_sane_privacy(&self, item: &ast::Item) {
                 }
             }
 
-            ast::ItemTrait(_, _, _, _, ref methods) => {
+            ast::ItemTrait(_, _, _, ref methods) => {
                 for m in methods.iter() {
                     match *m {
                         ast::ProvidedMethod(ref m) => {
@@ -1242,7 +1242,7 @@ fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
 
             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 @@ fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
 
     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 @@ fn visit_item(&mut self, item: &ast::Item) {
             // 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
                 }
index 22dea3be1d4b65a236d5e19a19518a5517405f1d..4feafff3b9211bb1ed823a84906d5b715e9017df 100644 (file)
@@ -105,7 +105,7 @@ fn visit_item(&mut self, item: &ast::Item) {
                 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 @@ fn visit_generics(&mut self, generics: &ast::Generics) {
         }
     }
 
-    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| {
index 232646f64a7d1f720945c977623754b7d3f48366..617be82701a093d6fd3a1f71e0d1915ab61265c6 100644 (file)
@@ -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()
index ea4d5c820f8b8796afb5faca1cdc134553a3d350..7e28cd699a1a6ae4d34e2d2d06d7ab14441e3e12 100644 (file)
@@ -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()
           }
         },
 
index 322f001c31e1b9dfb3df084f459f11153147c642..bc7732157cefe3539bfa6b67607b500fe87950f2 100644 (file)
@@ -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()
           }
         },
 
index e7ce5b0a429bc4023ad1143647af8c19c15cc69a..3eea0a0dba4052eec331719899da153854c4c4a0 100644 (file)
@@ -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()
           }
         },
 
index 8be98a517757fab22750975fc91090135011843e..8bb64eae625f40651fe9cbfde43715a2a0e305cc 100644 (file)
@@ -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(),
index 97bc747916d03415a91772dbfbc9f7186758075d..0a5aa56055e1b4e7ea99727aaa7042f40da44d9d 100644 (file)
@@ -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(),
index aecab188264197e282f1e14bc849e40dc18d315e..985af35e1454cd90e1c06b9485e80f68bebad572 100644 (file)
@@ -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(),
index 305862d357a49367ca94fc19871137edd2288745..3cf0c31282052f848758a72790ad4f9ea8483f15 100644 (file)
@@ -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(),
index fe336601a81ac93b1c0865ed49cf534939fadd84..45669bc95859967028f6010e14a7780a3fae3e9e 100644 (file)
@@ -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(),
index bd3dd3246aa6d21a9aa5ad103de25402fb1e99c3..feef5b98dcbcf362fc92a4679a8b90ddc2abda3d 100644 (file)
@@ -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(),
index 45e02ecb98ca6a0e02ecf83c2ace5a7bb152d737..c8c5ddcbd0d008c588bd5894974a7bde8890973e 100644 (file)
@@ -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(),
index 1ba99b167c30a1a5b796b31055c6219bc84148b4..3571f7b26c02184b0dfd0bc01c154f980e56f518 100644 (file)
@@ -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(),
index 4e958d73a39da7341ca7eaa8a391ffb18916bc45..07e6cdfed2c672a074d308f1226ebd3b9d388bca 100644 (file)
@@ -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(),
index 9247e1da0a58d5fdc3496a1c6b09435eb69729fb..6ca74eb7fc07d2ee1566bc353ac4e903099ec3d9 100644 (file)
@@ -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(),
index 75dbff9428b3edd06c57ba0e31a4c5836fbc088e..bff3eaf6bc8fa283e31354a089e856108cde7058 100644 (file)
@@ -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(),
index 37801f3bf251944c9e211ab36da9acb9d48d3425..8d5603a3878dbc9f6cd976d2b3a60fadb3d9ca9a 100644 (file)
@@ -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(),
index ac04e6e14ba5c4256c810df7fa47d08c7642a16f..e0a67cd62504c3075a437e7b681b02ff73797bd7 100644 (file)
@@ -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(),
index 21c4fd424748f2f21dfc0b08ebd158708e573d01..52c07165900a9b87313a5e6e3044854c87abfb05 100644 (file)
@@ -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()
           }
 
index 88cd6743192fdbd1c7071c67e969e2f7b3782c5f..cbb288a533d6adba2a49bbdf07343dff20fb6091 100644 (file)
@@ -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()
           }
 
index e2791aff14e49bcef25018d580f4a222263c7ee4..e20404bf63891431031c6306c5f5eaf4fcaad563 100644 (file)
@@ -540,7 +540,7 @@ pub fn monitor<F:FnOnce()+Send>(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::<diagnostic::FatalError>() {
                 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
 
index c168709eec5b91c213d0e793917347fa87aa17f9..7f01bf087381bf4988fe72779959ec6f2a7bf811 100644 (file)
@@ -345,9 +345,6 @@ fn new(kind: RibKind) -> 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 @@ fn shadowable(&self, namespace: Namespace) -> Shadowable {
 
         target.unwrap().shadowable
     }
+
+    fn set_target_and_id(&mut self,
+                         namespace: Namespace,
+                         target: Option<Target>,
+                         id: NodeId) {
+        match namespace {
+            TypeNS  => {
+                self.type_target = target;
+                self.type_id = id;
+            }
+            ValueNS => {
+                self.value_target = target;
+                self.value_id = id;
+            }
+        }
+    }
 }
 
 /// The link from a module up to its nearest parent node.
@@ -1493,7 +1506,7 @@ fn build_reduced_graph_for_item(&mut self,
 
             ItemImpl(_, _, Some(_), _, _) => parent,
 
-            ItemTrait(_, _, _, _, ref items) => {
+            ItemTrait(_, _, _, ref items) => {
                 let name_bindings =
                     self.add_child(name,
                                    parent.clone(),
@@ -1719,11 +1732,7 @@ fn build_reduced_graph_for_view_item(&mut self, view_item: &ViewItem,
                                                     view_path.span,
                                                     id,
                                                     is_public,
-                                                    if shadowable == Shadowable::Never {
-                                                        Shadowable::Glob
-                                                    } else {
-                                                        shadowable
-                                                    });
+                                                    shadowable);
                     }
                 }
             }
@@ -2712,64 +2721,45 @@ fn get_binding(this: &mut Resolver,
         // 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 @@ fn get_binding(this: &mut Resolver,
 
     // Resolves a glob import. Note that this function cannot fail; it either
     // succeeds or bails out (as importing * from an empty module or a module
-    // that exports nothing is valid).
+    // that exports nothing is valid). containing_module is the module we are
+    // actually importing, i.e., `foo` in `use foo::*`.
     fn resolve_glob_import(&mut self,
                            module_: &Module,
                            containing_module: Rc<Module>,
@@ -2851,12 +2842,11 @@ fn resolve_glob_import(&mut self,
         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 @@ fn resolve_glob_import(&mut self,
                             // 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 @@ fn resolve_glob_import(&mut self,
                             // 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 @@ fn resolve_glob_import(&mut self,
         // 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 @@ fn resolve_glob_import(&mut self,
         }
 
         // 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 @@ fn merge_import_resolution(&mut self,
 
         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 @@ fn check_for_conflicting_import(&mut self,
             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 @@ fn upvarify(&self,
         }
     }
 
+    /// Searches the current set of local scopes and
+    /// applies translations for closures.
     fn search_ribs(&self,
                    ribs: &[Rib],
                    name: Name,
@@ -4029,6 +4027,27 @@ fn search_ribs(&self,
         None
     }
 
+    /// Searches the current set of local scopes for labels.
+    /// Stops after meeting a closure.
+    fn search_label(&self, name: Name) -> Option<DefLike> {
+        for rib in self.label_ribs.iter().rev() {
+            match rib.kind {
+                NormalRibKind => {
+                    // Continue
+                }
+                _ => {
+                    // Do not resolve labels across function boundary
+                    return None
+                }
+            }
+            let result = rib.bindings.get(&name).cloned();
+            if result.is_some() {
+                return result
+            }
+        }
+        None
+    }
+
     fn resolve_crate(&mut self, krate: &ast::Crate) {
         debug!("(resolving crate) starting");
 
@@ -4093,7 +4112,7 @@ fn resolve_item(&mut self, item: &Item) {
                                             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 @@ fn resolve_item(&mut self, item: &Item) {
                     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 @@ fn resolve_type_parameter(&mut self,
             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 @@ fn resolve_type_parameter_bound(&mut self,
                                     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 @@ fn resolve_expr(&mut self, expr: &Expr) {
 
             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,
index 513b955da3f5855104e5a1adb1db86610220f65b..99e11bf520205926d355518a2e2c17f1f01dd2ab 100644 (file)
@@ -98,7 +98,7 @@ fn new() -> 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 @@ fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, codemap::Span)>,
             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);
index f491bc84b62c476d158e71bc714d2c691b23ed27..51ea0af8e10eaa3ccccdfed1883069cf6c16bebc 100644 (file)
@@ -636,7 +636,7 @@ fn process_enum(&mut self,
                         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 @@ fn process_trait(&mut self,
         // 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 @@ fn process_mod(&mut self,
     }
 
     fn process_path(&mut self,
-                    ex: &ast::Expr,
-                    path: &ast::Path) {
+                    id: NodeId,
+                    span: Span,
+                    path: &ast::Path,
+                    ref_kind: Option<recorder::Row>) {
         if generated_code(path.span) {
             return
         }
 
         let def_map = self.analysis.ty_cx.def_map.borrow();
-        if !def_map.contains_key(&ex.id) {
-            self.sess.span_bug(ex.span,
-                               format!("def_map has no key for {} in visit_expr",
-                                       ex.id)[]);
+        if !def_map.contains_key(&id) {
+            self.sess.span_bug(span,
+                               format!("def_map has no key for {} in visit_expr", id)[]);
         }
-        let def = &(*def_map)[ex.id];
-        let sub_span = self.span.span_for_last_ident(ex.span);
+        let def = &(*def_map)[id];
+        let sub_span = self.span.span_for_last_ident(span);
         match *def {
             def::DefUpvar(..) |
             def::DefLocal(..) |
             def::DefStatic(..) |
             def::DefConst(..) |
-            def::DefVariant(..) => self.fmt.ref_str(recorder::VarRef,
-                                                    ex.span,
+            def::DefVariant(..) => self.fmt.ref_str(ref_kind.unwrap_or(recorder::VarRef),
+                                                    span,
                                                     sub_span,
                                                     def.def_id(),
                                                     self.cur_scope),
             def::DefStruct(def_id) => self.fmt.ref_str(recorder::StructRef,
-                                                       ex.span,
+                                                       span,
                                                        sub_span,
                                                        def_id,
-                                                        self.cur_scope),
+                                                       self.cur_scope),
             def::DefStaticMethod(declid, provenence) => {
-                let sub_span = self.span.sub_span_for_meth_name(ex.span);
+                let sub_span = self.span.sub_span_for_meth_name(span);
                 let defid = if declid.krate == ast::LOCAL_CRATE {
                     let ti = ty::impl_or_trait_item(&self.analysis.ty_cx,
                                                     declid);
@@ -828,34 +829,31 @@ fn process_path(&mut self,
                 } 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 @@ fn process_pat(&mut self, p:&ast::Pat) {
                     }
                 };
                 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 @@ fn visit_item(&mut self, item: &ast::Item) {
                                   &**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 @@ fn visit_item(&mut self, item: &ast::Item) {
     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 @@ fn visit_view_item(&mut self, i: &ast::ViewItem) {
         }
 
         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 @@ fn visit_view_item(&mut self, i: &ast::ViewItem) {
                         // '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 @@ fn visit_expr(&mut self, ex: &ast::Expr) {
                 // 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 @@ fn visit_pat(&mut self, p: &ast::Pat) {
     fn visit_arm(&mut self, arm: &ast::Arm) {
         assert!(self.collected_paths.len() == 0 && !self.collecting);
         self.collecting = true;
-
         for pattern in arm.pats.iter() {
             // collect paths from the arm's patterns
             self.visit_pat(&**pattern);
         }
-        self.collecting = false;
+
+        // This is to get around borrow checking, because we need mut self to call process_path.
+        let mut paths_to_process = vec![];
         // process collected paths
         for &(id, ref p, ref immut, ref_kind) in self.collected_paths.iter() {
-            let value = if *immut {
-                self.span.snippet(p.span).to_string()
-            } else {
-                "<mutable>".to_string()
-            };
-            let sub_span = self.span.span_for_first_ident(p.span);
             let def_map = self.analysis.ty_cx.def_map.borrow();
             if !def_map.contains_key(&id) {
                 self.sess.span_bug(p.span,
-                                   format!("def_map has no key for {} in visit_arm",
-                                           id)[]);
+                                   format!("def_map has no key for {} in visit_arm", id)[]);
             }
             let def = &(*def_map)[id];
             match *def {
-                def::DefLocal(id)  => self.fmt.variable_str(p.span,
-                                                            sub_span,
-                                                            id,
-                                                            path_to_string(p)[],
-                                                            value[],
-                                                            ""),
-                def::DefVariant(_,id,_) => self.fmt.ref_str(ref_kind,
-                                                            p.span,
-                                                            sub_span,
-                                                            id,
-                                                            self.cur_scope),
-                // FIXME(nrc) what is this doing here?
+                def::DefLocal(id)  => {
+                    let value = if *immut {
+                        self.span.snippet(p.span).to_string()
+                    } else {
+                        "<mutable>".to_string()
+                    };
+
+                    assert!(p.segments.len() == 1, "qualified path for local variable def in arm");
+                    self.fmt.variable_str(p.span,
+                                          Some(p.span),
+                                          id,
+                                          path_to_string(p)[],
+                                          value[],
+                                          "")
+                }
+                def::DefVariant(..) => {
+                    paths_to_process.push((id, p.span, p.clone(), Some(ref_kind)))
+                }
+                // FIXME(nrc) what are these doing here?
                 def::DefStatic(_, _) => {}
                 def::DefConst(..) => {}
-                _ => error!("unexpected definition kind when processing collected paths: {}",
-                            *def)
+                _ => error!("unexpected definition kind when processing collected paths: {}", *def)
             }
         }
+        for &(id, span, ref path, ref_kind) in paths_to_process.iter() {
+            self.process_path(id, span, path, ref_kind);
+        }
+        self.collecting = false;
         self.collected_paths.clear();
         visit::walk_expr_opt(self, &arm.guard);
         self.visit_expr(&*arm.body);
index b2dd9218f1797333420281fc6f6e7eabcac3f5eb..f62073e54e6d963e4345d811c0d4c1dc060e4191 100644 (file)
@@ -61,7 +61,7 @@ macro_rules! svec {
     })
 }
 
-#[deriving(Copy)]
+#[deriving(Copy,Show)]
 pub enum Row {
     Variable,
     Enum,
index e9d862d3781bbf47b21c72f3233667ebf820ae6a..244d0476832bdb7545699a8cc436dd1ca03cdb64 100644 (file)
@@ -294,8 +294,8 @@ pub fn sub_span_of_token(&self, span: Span, tok: Token) -> Option<Span> {
     }
 
     pub fn sub_span_after_keyword(&self,
-                              span: Span,
-                              keyword: keywords::Keyword) -> Option<Span> {
+                                  span: Span,
+                                  keyword: keywords::Keyword) -> Option<Span> {
         let mut toks = self.retokenise_span(span);
         loop {
             let ts = toks.real_token();
index dd5809730d6f53ef900c44e73d3c543359856d64..f0d738d839d7a01e281de85cfc35ae38926af7cc 100644 (file)
@@ -983,23 +983,14 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                           llfn: ValueRef,
                           llargs: &[ValueRef],
                           fn_ty: Ty<'tcx>,
-                          call_info: Option<NodeInfo>,
-                          // FIXME(15064) is_lang_item is a horrible hack, please remove it
-                          // at the soonest opportunity.
-                          is_lang_item: bool)
+                          call_info: Option<NodeInfo>)
                           -> (ValueRef, Block<'blk, 'tcx>) {
     let _icx = push_ctxt("invoke_");
     if bcx.unreachable.get() {
         return (C_null(Type::i8(bcx.ccx())), bcx);
     }
 
-    // FIXME(15064) Lang item methods may (in the reflect case) not have proper
-    // types, so doing an attribute lookup will fail.
-    let attributes = if is_lang_item {
-        llvm::AttrBuilder::new()
-    } else {
-        get_fn_llvm_attributes(bcx.ccx(), fn_ty)
-    };
+    let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
 
     match bcx.opt_node_id {
         None => {
@@ -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
index 1b9c9d221b909b0f5a28ea8b731d5f8b6bfde7ee..5249f59d78f750b28ab2a1c001a41adda06f27b7 100644 (file)
@@ -501,7 +501,7 @@ pub fn store(&self, val: ValueRef, ptr: ValueRef) {
         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 @@ pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) {
         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);
index e3fe749b49003a2cf2d12fd4a1a832633404cd36..a159cda9fbaed81819d511ae1e2040ef48a6b00f 100644 (file)
@@ -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;
 
index 1f61fed3998d1bfe28e299020d1b8fdab71e8bae..b15b75c6715b755ddeeb0f9c1b2beabbd3d83f98 100644 (file)
@@ -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.
index e276543264b0a553c6bd00ec2e3c5baea35b2775..e0a878c8261ef9f8a866ec02c491e0c22af3ceda 100644 (file)
@@ -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
index 4f9b8c5ea37c973cb9c3822cd4d49904b344a942..9e959ce4221e71f8f61052169507b4bb8f1c1f89 100644 (file)
@@ -20,7 +20,7 @@
 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 @@ pub fn get(&self) -> ValueRef {
     pub fn get_parent(self) -> Option<BasicBlock> {
         unsafe {
             match llvm::LLVMGetInstructionParent(self.get()) {
-                p if p.is_not_null() => Some(BasicBlock(p)),
+                p if !p.is_null() => Some(BasicBlock(p)),
                 _ => None
             }
         }
@@ -77,7 +77,7 @@ pub fn get_dominating_store(self, bcx: Block) -> Option<Value> {
     pub fn get_first_use(self) -> Option<Use> {
         unsafe {
             match llvm::LLVMGetFirstUse(self.get()) {
-                u if u.is_not_null() => Some(Use(u)),
+                u if !u.is_null() => Some(Use(u)),
                 _ => None
             }
         }
@@ -119,7 +119,7 @@ pub fn as_store_inst(self) -> Option<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 @@ pub fn get_user(self) -> Value {
     pub fn get_next_use(self) -> Option<Use> {
         unsafe {
             match llvm::LLVMGetNextUse(self.get()) {
-                u if u.is_not_null() => Some(Use(u)),
+                u if !u.is_null() => Some(Use(u)),
                 _ => None
             }
         }
index 81e6ec4df562714010173f4ee0f3fc91f19e3d37..d6f1f5fedc5817554a085a5ae922074b65774a01 100644 (file)
@@ -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);
             }
index fb23ad8e340cee03941b3242336e7ea7e9d9302c..c8c8211f29253ce3a5671f133a64e1b82503eaee 100644 (file)
@@ -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 {
index 793c5f5b4a058b0af0543e6d06688df4fdf76ad6..8d07f1e4355031c2c32f8d2c7b519bcd18faed1e 100644 (file)
@@ -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<ast::TraitRef>,
                               bounds: &mut ty::BuiltinBounds,
-                              desc: &str,
+                              ast_bounds: &[ast::TyParamBound],
                               span: Span)
                               where AC: AstConv<'tcx> {
+    // Try to find an unbound in bounds.
+    let mut unbound = None;
+    for ab in ast_bounds.iter() {
+        if let &ast::TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = ab  {
+            if unbound.is_none() {
+                assert!(ptr.bound_lifetimes.is_empty());
+                unbound = Some(ptr.trait_ref.clone());
+            } else {
+                this.tcx().sess.span_err(span, "type parameter has more than one relaxed default \
+                                                bound, only one is supported");
+            }
+        }
+    }
+
     let kind_id = this.tcx().lang_items.require(SizedTraitLangItem);
     match unbound {
-        &Some(ref tpb) => {
+        Some(ref tpb) => {
             // FIXME(#8559) currently requires the unbound to be built-in.
             let trait_def_id = ty::trait_ref_to_def_id(this.tcx(), tpb);
             match kind_id {
                 Ok(kind_id) if trait_def_id != kind_id => {
                     this.tcx().sess.span_warn(span,
-                                              format!("default bound relaxed \
-                                                       for a {}, but this \
-                                                       does nothing because \
-                                                       the given bound is not \
-                                                       a default. \
-                                                       Only `Sized?` is \
-                                                       supported",
-                                                      desc)[]);
+                                              "default bound relaxed for a type parameter, but \
+                                               this does nothing because the given bound is not \
+                                               a default. Only `?Sized` is supported");
                     ty::try_add_builtin_trait(this.tcx(),
                                               kind_id,
                                               bounds);
@@ -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 create_type_parameters_for_associated_types<'tcx, 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[],
-                                &param.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<ast::TraitRef>,
                            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(),
index bdd8c7c3da7c011b444af8df51793e4d6d46885d..30869186ba5e9ef7f67cd184c7cbcae15500d00b 100644 (file)
@@ -353,7 +353,7 @@ fn visit_item(&mut self, item: &ast::Item) {
         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);
index cdc51bb801c58a718df8f3ce76bfd3dd315618f7..3eda39f54a997e8a036a280d024bf73c92bed2bf 100644 (file)
@@ -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!(),
                 }
             }),
index 0308194527e9538a904986b188409160aebee3ad..b7845f23be2983ea92eb219cf8b6a5f37b39065b 100644 (file)
@@ -458,8 +458,6 @@ pub struct TyParam {
     pub did: ast::DefId,
     pub bounds: Vec<TyParamBound>,
     pub default: Option<Type>,
-    /// An optional default bound on the parameter which is unbound, like `Sized?`
-    pub default_unbound: Option<Type>
 }
 
 impl Clean<TyParam> for ast::TyParam {
@@ -469,7 +467,6 @@ fn clean(&self, cx: &DocContext) -> 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<TyParam> 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 @@ fn clean(&self, cx: &DocContext) -> TyParam {
 #[deriving(Clone, RustcEncodable, RustcDecodable, PartialEq)]
 pub enum TyParamBound {
     RegionBound(Lifetime),
-    TraitBound(PolyTrait)
+    TraitBound(PolyTrait, ast::TraitBoundModifier)
 }
 
 impl Clean<TyParamBound> for ast::TyParamBound {
     fn clean(&self, cx: &DocContext) -> TyParamBound {
         match *self {
             ast::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
-            ast::TraitTyParamBound(ref t) => TraitBound(t.clean(cx)),
+            ast::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
         }
     }
 }
@@ -600,7 +596,7 @@ fn clean(&self, cx: &DocContext) -> TyParamBound {
                 did: did,
             },
             lifetimes: vec![]
-        })
+        }, ast::TraitBoundModifier::None)
     }
 }
 
@@ -648,37 +644,20 @@ fn clean(&self, cx: &DocContext) -> TyParamBound {
         TraitBound(PolyTrait {
             trait_: ResolvedPath { path: path, typarams: None, did: self.def_id, },
             lifetimes: late_bounds
-        })
+        }, ast::TraitBoundModifier::None)
     }
 }
 
-// Returns (bounds, default_unbound)
-impl<'tcx> Clean<(Vec<TyParamBound>, Option<Type>)> for ty::ParamBounds<'tcx> {
-    fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Option<Type>) {
+impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> {
+    fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
         let mut v = Vec::new();
-        let mut has_sized_bound = false;
-        for b in self.builtin_bounds.iter() {
-            if b != ty::BoundSized {
-                v.push(b.clean(cx));
-            } else {
-                has_sized_bound = true;
-            }
-        }
         for t in self.trait_bounds.iter() {
             v.push(t.clean(cx));
         }
         for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) {
             v.push(RegionBound(r));
         }
-        if has_sized_bound {
-            (v, None)
-        } else {
-            let ty = match ty::BoundSized.clean(cx) {
-                TraitBound(polyt) => polyt.trait_,
-                _ => unreachable!()
-            };
-            (v, Some(ty))
-        }
+        v
     }
 }
 
@@ -689,7 +668,7 @@ fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
         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<TraitMethod>,
     pub generics: Generics,
     pub bounds: Vec<TyParamBound>,
-    /// An optional default bound not required for `Self`, like `Sized?`
-    pub default_unbound: Option<Type>
 }
 
 impl Clean<Item> for doctree::Trait {
@@ -1065,7 +1042,6 @@ fn clean(&self, cx: &DocContext) -> Item {
                 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 @@ fn clean(&self, cx: &DocContext) -> Item {
                 },
                 bounds: vec![],
                 default: None,
-                default_unbound: None
             }),
             visibility: None,
             def_id: self.def_id,
index 7f7c055062aaadde84dd878202eb667f7525f2b5..251ce5aefeb717429c5542d5d2ac10a0e7ae12b0 100644 (file)
@@ -178,7 +178,6 @@ pub struct Trait {
     pub whence: Span,
     pub vis: ast::Visibility,
     pub stab: Option<attr::Stability>,
-    pub default_unbound: Option<ast::TraitRef> // FIXME(tomjakubowski)
 }
 
 pub struct Impl {
index 25c4f4e01b620d0ea61a28554bb7c35ea60a438a..585183e2af75ed27ae2d22307000c5293cc52a23 100644 (file)
@@ -97,9 +97,6 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                 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 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         if gens.where_predicates.len() == 0 {
             return Ok(());
         }
-        try!(f.write(" where ".as_bytes()));
+        try!(f.write(" <span class='where'>where ".as_bytes()));
         for (i, pred) in gens.where_predicates.iter().enumerate() {
             if i > 0 {
                 try!(f.write(", ".as_bytes()));
@@ -149,6 +146,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                 }
             }
         }
+        try!(f.write("</span>".as_bytes()));
         Ok(())
     }
 }
@@ -182,8 +180,12 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
             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 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                            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());
                                     }
index 304dbe201e8fd5021945996168a5a4a626127a62..bfb03cb2589c2a3366ed6b48d7b3805c50abb5c5 100644 (file)
@@ -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(' ');
index dc62273364c20ebbc1507e7419eb60900a2b5abf..9d4f341a30e25fa018dacb1e0fe9f508cd3c1e09 100644 (file)
@@ -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; }
index 4374ce5deef4ecde2d6fbb305005437395b07244..e71711aa8d6e77d80efdb56cf74d6e0aec444f1f 100644 (file)
@@ -322,7 +322,7 @@ pub fn visit_item(&mut self, item: &ast::Item,
                 };
                 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 @@ pub fn visit_item(&mut self, item: &ast::Item,
                     whence: item.span,
                     vis: item.vis,
                     stab: self.stability(item.id),
-                    default_unbound: def_ub.clone()
                 };
                 om.traits.push(t);
             },
index f1dffa55bb01a29560115192cdf81f35fdc9120b..fae73cc834fd243e804df191ed6c07a3d1fdffbe 100644 (file)
@@ -392,10 +392,10 @@ fn test_from_base64_invalid_padding() {
 
     #[test]
     fn test_base64_random() {
-        use std::rand::{task_rng, random, Rng};
+        use std::rand::{thread_rng, random, Rng};
 
         for _ in range(0u, 1000) {
-            let times = task_rng().gen_range(1u, 100);
+            let times = thread_rng().gen_range(1u, 100);
             let v = Vec::from_fn(times, |_| random::<u8>());
             assert_eq!(v.to_base64(STANDARD)
                         .from_base64()
index 830d96fe172bcb5a8688006b24fd68f70d85ad2a..3f0d59c319a69e7e44165573b698555b101129d5 100644 (file)
@@ -29,7 +29,7 @@
 //! * `String`: equivalent to rust's `String`
 //! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
 //!   same array
-//! * `Object`: equivalent to rust's `Treemap<String, json::Json>`
+//! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
 //! * `Null`
 //!
 //! An object is a series of string keys mapping to values, in `"key": value` format.
@@ -2517,7 +2517,7 @@ fn mk_object(items: &[(string::String, Json)]) -> Json {
     #[test]
     fn test_from_str_trait() {
         let s = "null";
-        assert!(::std::str::from_str::<Json>(s).unwrap() == from_str(s).unwrap());
+        assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
     }
 
     #[test]
@@ -3729,8 +3729,8 @@ fn test_to_json() {
         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 @@ fn test_to_json() {
         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);
index 5dd76047779a0eb45c86d5ba45a4f2bf03aad69c..a46b8a9ad9024c0922f3796c08d58dc376ccc326 100644 (file)
 /// - `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`
index ffe19203769d4c6386be784c1b10ce2bdd6d5e07..f28abcc10cfd8dcf0d651005566e08a61a67834c 100644 (file)
@@ -537,7 +537,8 @@ pub unsafe fn from_c_multistring<F>(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;
index f4338815f759bcd7cd91eb1c30ec020ddf2e615e..0aa51ee66ed63dc30324fcd75b43ddc5d8b7d13b 100644 (file)
@@ -40,7 +40,7 @@
 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;
index d749cd77cef2dc0b385ae47a0d1ea9ba5ab2c226..7b7473b2c993c27d3cd13d6e9cd86034f3eed7ab 100644 (file)
@@ -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 @@ fn second<A, B>((_, b): (A, B)) -> B { b }
     /// }
     /// ```
     #[unstable = "matches collection reform specification, waiting for dust to settle"]
-    pub fn iter(&self) -> Entries<K, V> {
-        Entries { inner: self.table.iter() }
+    pub fn iter(&self) -> Iter<K, V> {
+        Iter { inner: self.table.iter() }
     }
 
     /// An iterator visiting all key-value pairs in arbitrary order,
@@ -1305,8 +1313,8 @@ fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V {
 }
 
 /// HashMap iterator
-pub struct Entries<'a, K: 'a, V: 'a> {
-    inner: table::Entries<'a, K, V>
+pub struct Iter<'a, K: 'a, V: 'a> {
+    inner: table::Iter<'a, K, V>
 }
 
 /// HashMap mutable values iterator
@@ -1326,12 +1334,12 @@ pub struct IntoIter<K, V> {
 
 /// 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<K, V, M> {
     NoElem(EmptyBucket<K, V, M>),
 }
 
-impl<'a, K, V> Iterator<(&'a K, &'a V)> for Entries<'a, K, V> {
+impl<'a, K, V> Iterator<(&'a K, &'a V)> for Iter<'a, K, V> {
     #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
     #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
 }
index 3ae3a8ffbad3bfe3399559851dbbecdbec3c1018..f76b8ac3326f5bec2d5d5ddb743d199bc74a221d 100644 (file)
@@ -23,7 +23,7 @@
 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 @@ fn raw_buckets(&self) -> RawBuckets<K, V> {
         }
     }
 
-    pub fn iter(&self) -> Entries<K, V> {
-        Entries {
+    pub fn iter(&self) -> Iter<K, V> {
+        Iter {
             iter: self.raw_buckets(),
             elems_left: self.size(),
         }
@@ -770,7 +770,7 @@ fn next(&mut self) -> Option<(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;
index c85bea87218ff6be2aa279890ad08dd1c4ed76db..a405627aecc45a9be9e9a1ea705bf8c4524c428e 100644 (file)
 // senders. Under the hood, however, there are actually three flavors of
 // channels in play.
 //
-// * Oneshots - these channels are highly optimized for the one-send use case.
+// * Flavor::Oneshots - these channels are highly optimized for the one-send use case.
 //              They contain as few atomics as possible and involve one and
 //              exactly one allocation.
 // * Streams - these channels are optimized for the non-shared use case. They
 
 pub use self::TryRecvError::*;
 pub use self::TrySendError::*;
-use self::Flavor::*;
 
 use alloc::arc::Arc;
 use core::kinds;
@@ -337,7 +336,8 @@ mod $name {
             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 @@ fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> {
 #[unstable]
 pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) {
     let a = Arc::new(RacyCell::new(oneshot::Packet::new()));
-    (Sender::new(Oneshot(a.clone())), Receiver::new(Oneshot(a)))
+    (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a)))
 }
 
 /// Creates a new synchronous, bounded channel.
@@ -518,7 +518,7 @@ pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) {
               of channel that is is creating"]
 pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) {
     let a = Arc::new(RacyCell::new(sync::Packet::new(bound)));
-    (SyncSender::new(a.clone()), Receiver::new(Sync(a)))
+    (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a)))
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -592,7 +592,7 @@ pub fn send(&self, t: T) {
     #[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 @@ pub fn send_opt(&self, t: T) -> Result<(), T> {
                     } 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 @@ pub fn send_opt(&self, t: T) -> Result<(), T> {
                     }
                 }
             }
-            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 @@ pub fn send_opt(&self, t: T) -> Result<(), T> {
 impl<T: Send> Clone for Sender<T> {
     fn clone(&self) -> Sender<T> {
         let (packet, sleeper, guard) = match *unsafe { self.inner() } {
-            Oneshot(ref p) => {
+            Flavor::Oneshot(ref p) => {
                 let a = Arc::new(RacyCell::new(shared::Packet::new()));
                 unsafe {
                     let guard = (*a.get()).postinit_lock();
-                    match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) {
+                    match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) {
                         oneshot::UpSuccess |
                         oneshot::UpDisconnected => (a, None, guard),
                         oneshot::UpWoke(task) => (a, Some(task), guard)
                     }
                 }
             }
-            Stream(ref p) => {
+            Flavor::Stream(ref p) => {
                 let a = Arc::new(RacyCell::new(shared::Packet::new()));
                 unsafe {
                     let guard = (*a.get()).postinit_lock();
-                    match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) {
+                    match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) {
                         stream::UpSuccess |
                         stream::UpDisconnected => (a, None, guard),
                         stream::UpWoke(task) => (a, Some(task), guard),
                     }
                 }
             }
-            Shared(ref p) => {
+            Flavor::Shared(ref p) => {
                 unsafe { (*p.get()).clone_chan(); }
-                return Sender::new(Shared(p.clone()));
+                return Sender::new(Flavor::Shared(p.clone()));
             }
-            Sync(..) => unreachable!(),
+            Flavor::Sync(..) => unreachable!(),
         };
 
         unsafe {
             (*packet.get()).inherit_blocker(sleeper, guard);
 
-            let tmp = Sender::new(Shared(packet.clone()));
+            let tmp = Sender::new(Flavor::Shared(packet.clone()));
             mem::swap(self.inner_mut(), tmp.inner_mut());
         }
-        Sender::new(Shared(packet))
+        Sender::new(Flavor::Shared(packet))
     }
 }
 
@@ -678,10 +678,10 @@ fn clone(&self) -> Sender<T> {
 impl<T: Send> Drop for Sender<T> {
     fn drop(&mut self) {
         match *unsafe { self.inner_mut() } {
-            Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); },
-            Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); },
-            Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); },
-            Sync(..) => unreachable!(),
+            Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); },
+            Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); },
+            Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); },
+            Flavor::Sync(..) => unreachable!(),
         }
     }
 }
@@ -827,7 +827,7 @@ pub fn recv(&self) -> T {
     pub fn try_recv(&self) -> Result<T, TryRecvError> {
         loop {
             let new_port = match *unsafe { self.inner() } {
-                Oneshot(ref p) => {
+                Flavor::Oneshot(ref p) => {
                     match unsafe { (*p.get()).try_recv() } {
                         Ok(t) => return Ok(t),
                         Err(oneshot::Empty) => return Err(Empty),
@@ -835,7 +835,7 @@ pub fn try_recv(&self) -> Result<T, TryRecvError> {
                         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 @@ pub fn try_recv(&self) -> Result<T, TryRecvError> {
                         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 @@ pub fn try_recv(&self) -> Result<T, TryRecvError> {
     pub fn recv_opt(&self) -> Result<T, ()> {
         loop {
             let new_port = match *unsafe { self.inner() } {
-                Oneshot(ref p) => {
+                Flavor::Oneshot(ref p) => {
                     match unsafe { (*p.get()).recv() } {
                         Ok(t) => return Ok(t),
                         Err(oneshot::Empty) => return unreachable!(),
@@ -889,7 +889,7 @@ pub fn recv_opt(&self) -> Result<T, ()> {
                         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 @@ pub fn recv_opt(&self) -> Result<T, ()> {
                         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<T: Send> select::Packet for Receiver<T> {
     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 @@ fn can_recv(&self) -> bool {
     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 @@ fn abort_selection(&self) -> bool {
         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 @@ fn next(&mut self) -> Option<T> { self.rx.recv_opt().ok() }
 impl<T: Send> Drop for Receiver<T> {
     fn drop(&mut self) {
         match *unsafe { self.inner_mut() } {
-            Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); },
-            Stream(ref mut p) => unsafe { (*p.get()).drop_port(); },
-            Shared(ref mut p) => unsafe { (*p.get()).drop_port(); },
-            Sync(ref mut p) => unsafe { (*p.get()).drop_port(); },
+            Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); },
+            Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_port(); },
+            Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_port(); },
+            Flavor::Sync(ref mut p) => unsafe { (*p.get()).drop_port(); },
         }
     }
 }
@@ -1047,7 +1047,7 @@ unsafe impl<T> kinds::Sync for RacyCell<T> { } // 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 {
index 1022694e634f607a64418f79f62f93ad61dd2dce..3f23ec5dc665966b5aa499a0696e3f3e5d7f9e34 100644 (file)
@@ -86,7 +86,7 @@ pub fn new() -> Packet<T> {
     // 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 @@ pub fn abort_selection(&mut self, _was_upgrade: bool) -> bool {
         // 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
index 88338849965b0589177f9aeda001a9c6e16ee44b..82ec1814ebde70e05ac4f957d702d55e6b91c7b8 100644 (file)
@@ -121,9 +121,9 @@ fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
         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 @@ pub fn new(cap: uint) -> Packet<T> {
     fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
         let mut node = Node { token: None, next: 0 as *mut Node };
         loop {
-            let mut guard = self.lock.lock();
+            let mut guard = self.lock.lock().unwrap();
             // are we ready to go?
             if guard.disconnected || guard.buf.size() < guard.buf.cap() {
                 return guard;
@@ -202,7 +202,7 @@ pub fn send(&self, t: T) -> Result<(), T> {
     }
 
     pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
-        let mut guard = self.lock.lock();
+        let mut guard = self.lock.lock().unwrap();
         if guard.disconnected {
             Err(super::RecvDisconnected(t))
         } else if guard.buf.size() == guard.buf.cap() {
@@ -239,7 +239,7 @@ pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
     // When reading this, remember that there can only ever be one receiver at
     // time.
     pub fn recv(&self) -> Result<T, ()> {
-        let mut guard = self.lock.lock();
+        let mut guard = self.lock.lock().unwrap();
 
         // Wait for the buffer to have something in it. No need for a while loop
         // because we're the only receiver.
@@ -258,7 +258,7 @@ pub fn recv(&self) -> Result<T, ()> {
     }
 
     pub fn try_recv(&self) -> Result<T, Failure> {
-        let mut guard = self.lock.lock();
+        let mut guard = self.lock.lock().unwrap();
 
         // Easy cases first
         if guard.disconnected { return Err(Disconnected) }
@@ -315,7 +315,7 @@ pub fn drop_chan(&self) {
         }
 
         // 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 @@ pub fn drop_chan(&self) {
     }
 
     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 @@ pub fn drop_port(&self) {
     // 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 @@ pub fn start_selection(&self, token: SignalToken) -> StartResult {
     //
     // 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 @@ pub fn abort_selection(&self) -> bool {
 impl<T: Send> Drop for Packet<T> {
     fn drop(&mut self) {
         assert_eq!(self.channels.load(atomic::SeqCst), 0);
-        let mut guard = self.lock.lock();
+        let mut guard = self.lock.lock().unwrap();
         assert!(guard.queue.dequeue().is_none());
         assert!(guard.canceled.is_none());
     }
index cd7d9aacc90109bb8a33d2d1f6852d37bd4a40a5..9a46a500a4b4799199ccc73edbdaf75106aef405 100644 (file)
@@ -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 @@ fn description(&self) -> &str {
 
     fn detail(&self) -> Option<String> { Some(self.to_string()) }
 }
+
+impl Error for FromUtf8Error {
+    fn description(&self) -> &str { "invalid utf-8" }
+    fn detail(&self) -> Option<String> { Some(self.to_string()) }
+}
+
+impl Error for FromUtf16Error {
+    fn description(&self) -> &str { "invalid utf-16" }
+}
index 52e3c718b2d56d4222d21db92714161fbb71a597..737fef23c74668764b564c5e10add1858f912b43 100644 (file)
@@ -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 {
index c1f1a5b786985d96dd936701e89b473f1bd7eea5..e8765e3c2317e5d87d1fa8a04fa3bf0572dcd840 100644 (file)
@@ -22,7 +22,7 @@
 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};
 
index f2db2875ebf2ca44f1da07f55630ceba7cf813a5..caa6590bb28212bd7cb8dc192d1c4bed0bbc0c56 100644 (file)
@@ -1148,6 +1148,19 @@ fn file_test_walk_dir() {
         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();
index 20b1162d859c778e71c740c3c09157919b345aa7..79327a29615ae52e47fc09603b6e1926a1bfd5d0 100644 (file)
@@ -400,8 +400,8 @@ fn fill_buf(&mut self) -> IoResult<&[u8]> {
 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;
 
index e1f5efae79fc7e45055ed419e52299a59db570ec..7a25360e695e40575aa4ed1014a0ce031eb454b8 100644 (file)
@@ -935,7 +935,7 @@ fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (*self).read(buf) }
 // API yet. If so, it should be a method on Vec.
 unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
     use raw::Slice;
-    use ptr::RawPtr;
+    use ptr::PtrExt;
 
     assert!(start <= end);
     assert!(end <= v.capacity());
@@ -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 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 #[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)]
index 4afc72cde711e46a6128f7e0bba0c1b388c9d5e2..93f37a8c98ff86a6401b47eb8b21a2e88e7550aa 100644 (file)
@@ -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;
 
index 6adb5387f2ef5e796d23a378c6c9426535e66c59..24cf06973cc6939f982f6ce6725d42003dfe6557 100644 (file)
@@ -484,9 +484,12 @@ fn as_inner(&self) -> &TcpAcceptorImp {
 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)]
index 5bf47dceb5a0e2c7c8e600343955601c1b620aac..1431067d4c6a3879eb19997f735cb0b645287817 100644 (file)
@@ -250,9 +250,9 @@ fn write(&mut self, buf: &[u8]) -> IoResult<()> {
 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)]
index 93aa627ffba13f7f2d3e3b384d8405f2cebad06f..b127507f048d22ff0d7751feb212277d075979f4 100644 (file)
@@ -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 @@ fn dont_close_fd_on_command_spawn() {
     #[test]
     #[cfg(windows)]
     fn env_map_keys_ci() {
+        use c_str::ToCStr;
         use super::EnvKey;
         let mut cmd = Command::new("");
         cmd.env("path", "foo");
index 6bd721599f341df1d2ed49777ed3ad419717f31a..6c8e4eea40fdc442b5f799b2ceb140e83eedd500 100644 (file)
@@ -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 @@ pub fn lock<'a>(&'a mut self) -> StdinReaderGuard<'a> {
     /// The read is performed atomically - concurrent read calls in other
     /// threads will not interleave with this one.
     pub fn read_line(&mut self) -> IoResult<String> {
-        self.inner.lock().0.read_line()
+        self.inner.lock().unwrap().0.read_line()
     }
 
     /// Like `Buffer::read_until`.
@@ -163,7 +163,7 @@ pub fn read_line(&mut self) -> IoResult<String> {
     /// The read is performed atomically - concurrent read calls in other
     /// threads will not interleave with this one.
     pub fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
-        self.inner.lock().0.read_until(byte)
+        self.inner.lock().unwrap().0.read_until(byte)
     }
 
     /// Like `Buffer::read_char`.
@@ -171,13 +171,13 @@ pub fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
     /// The read is performed atomically - concurrent read calls in other
     /// threads will not interleave with this one.
     pub fn read_char(&mut self) -> IoResult<char> {
-        self.inner.lock().0.read_char()
+        self.inner.lock().unwrap().0.read_char()
     }
 }
 
 impl Reader for StdinReader {
     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
-        self.inner.lock().0.read(buf)
+        self.inner.lock().unwrap().0.read(buf)
     }
 
     // We have to manually delegate all of these because the default impls call
@@ -185,23 +185,23 @@ fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
     // incur the costs of repeated locking).
 
     fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
-        self.inner.lock().0.read_at_least(min, buf)
+        self.inner.lock().unwrap().0.read_at_least(min, buf)
     }
 
     fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
-        self.inner.lock().0.push_at_least(min, len, buf)
+        self.inner.lock().unwrap().0.push_at_least(min, len, buf)
     }
 
     fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
-        self.inner.lock().0.read_to_end()
+        self.inner.lock().unwrap().0.read_to_end()
     }
 
     fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
-        self.inner.lock().0.read_le_uint_n(nbytes)
+        self.inner.lock().unwrap().0.read_le_uint_n(nbytes)
     }
 
     fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
-        self.inner.lock().0.read_be_uint_n(nbytes)
+        self.inner.lock().unwrap().0.read_be_uint_n(nbytes)
     }
 }
 
index 43893ca0126532f494a471328b60052732d22936..90d7c1388a196e56800786c23fa3d20627b8dede 100644 (file)
@@ -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() {
index 7c8763979bb36e3840491c1ce849f5439a44b41a..48ff1a364e93c7d73f750df61d6597ca3a5bf27e 100644 (file)
@@ -147,8 +147,10 @@ pub fn test_num<T>(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;
index ceb9a4102f6353c385743e0a68f40b1650aa2566..989f44f7b8e4239326adf25ac0ec1be2cf154474 100644 (file)
@@ -46,7 +46,8 @@
 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<String> {
         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 @@ pub fn last_os_error() {
     }
 
     fn make_rand_name() -> String {
-        let mut rng = rand::task_rng();
+        let mut rng = rand::thread_rng();
         let n = format!("TEST{}", rng.gen_ascii_chars().take(10u)
                                      .collect::<String>());
         assert!(getenv(n.as_slice()).is_none());
index d941665f0482f30b876cb8de6c5936664d2f2c55..60f147eac9b2b490be0e4dc9086838f9065a8c65 100644 (file)
@@ -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) {
index 1d17ae987b208135f865c423597a0f8a6198ab6d..879a96e802643429170357e93a876ab822d54dc1 100644 (file)
@@ -21,7 +21,7 @@
 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 @@ fn normalize__(s: &str, prefix: Option<PathPrefix>) -> Option<String> {
                             }
                         }
                     } 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() +
index d1540f98a2355651f7a2bc2738d49f6120989aa2..fc59f06ae6cf3ef5d3b143d380c606fd148930a1 100644 (file)
@@ -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};
index c590c0f575ee639053d000769f8c75bcc65fb8eb..d4f72a53aec1b7651928ec72a4f26add13014bee 100644 (file)
 //! 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::<int>(), rng.gen::<uint>())
 //! }
@@ -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;
 //!     // 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<StdRng> for TaskRngReseeder {
+impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
     fn reseed(&mut self, rng: &mut StdRng) {
         *rng = match StdRng::new() {
             Ok(r) => r,
-            Err(e) => panic!("could not reseed task_rng: {}", e)
+            Err(e) => panic!("could not reseed thread_rng: {}", e)
         }
     }
 }
-static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
-type TaskRngInner = reseeding::ReseedingRng<StdRng, TaskRngReseeder>;
+static THREAD_RNG_RESEED_THRESHOLD: uint = 32_768;
+type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
 
-/// The task-local RNG.
-pub struct TaskRng {
-    rng: Rc<RefCell<TaskRngInner>>,
+/// The thread-local RNG.
+pub struct ThreadRng {
+    rng: Rc<RefCell<ThreadRngInner>>,
 }
 
-/// Retrieve the lazily-initialized task-local random number
+/// Retrieve the lazily-initialized thread-local random number
 /// generator, seeded by the system. Intended to be used in method
-/// chaining style, e.g. `task_rng().gen::<int>()`.
+/// chaining style, e.g. `thread_rng().gen::<int>()`.
 ///
 /// The RNG provided will reseed itself from the operating system
 /// after generating a certain amount of randomness.
@@ -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<RefCell<TaskRngInner>> = {
+    thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
         let r = match StdRng::new() {
             Ok(r) => r,
-            Err(e) => panic!("could not initialize task_rng: {}", e)
+            Err(e) => panic!("could not initialize thread_rng: {}", e)
         };
         let rng = reseeding::ReseedingRng::new(r,
-                                               TASK_RNG_RESEED_THRESHOLD,
-                                               TaskRngReseeder);
+                                               THREAD_RNG_RESEED_THRESHOLD,
+                                               ThreadRngReseeder);
         Rc::new(RefCell::new(rng))
     });
 
-    TaskRng { rng: TASK_RNG_KEY.with(|t| t.clone()) }
+    ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
 }
 
-impl Rng for TaskRng {
+impl Rng for ThreadRng {
     fn next_u32(&mut self) -> u32 {
         self.rng.borrow_mut().next_u32()
     }
@@ -368,7 +368,7 @@ fn fill_bytes(&mut self, bytes: &mut [u8]) {
     }
 }
 
-/// 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 @@ fn fill_bytes(&mut self, bytes: &mut [u8]) {
 /// ```
 #[inline]
 pub fn random<T: Rand>() -> T {
-    task_rng().gen()
+    thread_rng().gen()
 }
 
 /// Randomly sample up to `amount` elements from an iterator.
@@ -398,9 +398,9 @@ pub fn random<T: Rand>() -> 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<T, I: Iterator<T>, 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 @@ fn test_fill_bytes_default() {
 
     #[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 @@ fn test_gen_range() {
     #[test]
     #[should_fail]
     fn test_gen_range_panic_int() {
-        let mut r = task_rng();
+        let mut r = thread_rng();
         r.gen_range(5i, -2);
     }
 
     #[test]
     #[should_fail]
     fn test_gen_range_panic_uint() {
-        let mut r = task_rng();
+        let mut r = thread_rng();
         r.gen_range(5u, 2u);
     }
 
     #[test]
     fn test_gen_f64() {
-        let mut r = task_rng();
+        let mut r = thread_rng();
         let a = r.gen::<f64>();
         let b = r.gen::<f64>();
         debug!("{}", (a, b));
@@ -494,14 +494,14 @@ fn test_gen_f64() {
 
     #[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 @@ fn test_gen_ascii_str() {
 
     #[test]
     fn test_gen_vec() {
-        let mut r = task_rng();
+        let mut r = thread_rng();
         assert_eq!(r.gen_iter::<u8>().take(0).count(), 0u);
         assert_eq!(r.gen_iter::<u8>().take(10).count(), 10u);
         assert_eq!(r.gen_iter::<f64>().take(16).count(), 16u);
@@ -517,7 +517,7 @@ fn test_gen_vec() {
 
     #[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 @@ fn test_choose() {
 
     #[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 @@ fn test_shuffle() {
     }
 
     #[test]
-    fn test_task_rng() {
-        let mut r = task_rng();
+    fn test_thread_rng() {
+        let mut r = thread_rng();
         r.gen::<int>();
         let mut v = [1i, 1, 1];
         r.shuffle(&mut v);
@@ -574,7 +574,7 @@ fn test_sample() {
         let min_val = 1i;
         let max_val = 100i;
 
-        let mut r = task_rng();
+        let mut r = thread_rng();
         let vals = range(min_val, max_val).collect::<Vec<int>>();
         let small_sample = sample(&mut r, vals.iter(), 5);
         let large_sample = sample(&mut r, vals.iter(), vals.len() + 5);
@@ -589,7 +589,7 @@ fn test_sample() {
 
     #[test]
     fn test_std_rng_seeded() {
-        let s = task_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
+        let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
         let mut ra: StdRng = SeedableRng::from_seed(s.as_slice());
         let mut rb: StdRng = SeedableRng::from_seed(s.as_slice());
         assert!(order::equals(ra.gen_ascii_chars().take(100),
@@ -598,7 +598,7 @@ fn test_std_rng_seeded() {
 
     #[test]
     fn test_std_rng_reseed() {
-        let s = task_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
+        let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
         let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
         let string1 = r.gen_ascii_chars().take(100).collect::<String>();
 
index 775e9bb526f7cbc84a300e47b4385b386e6d1654..3eeb0ad3968fe9b091e77cc9f4154d5466a98c4a 100644 (file)
@@ -60,19 +60,19 @@ fn demangle_dollars() {
         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");
     }
 }
index d64336569c6e9e98eac3453279a6cf965af66c19..e877dd5c6aab813ba5689070940299b667d5df1a 100644 (file)
@@ -53,7 +53,7 @@
 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.
index 98940a2b381c7b40600920d4ab9391be0e30e9d9..773322e4f57f18d5850f3cede5896a037bb5d85b 100644 (file)
@@ -36,7 +36,7 @@
 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<Thunk<Result>>,
-    /// A name for the task-to-be, for identification in panic messages
+    /// A name for the thread-to-be, for identification in panic messages
     pub name: Option<SendStr>,
-    /// The size of the stack for the spawned task
+    /// The size of the stack for the spawned thread
     pub stack_size: Option<uint>,
 }
 
-/// Indicates the manner in which a task exited.
+/// Indicates the manner in which a thread exited.
 ///
-/// A task that completes without panicking is considered to exit successfully.
+/// A thread that completes without panicking is considered to exit successfully.
 ///
 /// If you wish for this result's delivery to block until all
-/// children tasks complete, recommend using a result future.
+/// children threads complete, recommend using a result future.
 pub type Result = ::core::result::Result<(), Box<Any + Send>>;
 
-/// A handle to a blocked task. Usually this means having the Box<Task>
-/// pointer by ownership, but if the task is killable, a killer can steal it
+/// A handle to a blocked thread. Usually this means having the Box<Task>
+/// pointer by ownership, but if the thread is killable, a killer can steal it
 /// at any time.
 pub enum BlockedTask {
     Owned(Box<Task>),
     Shared(Arc<AtomicUint>),
 }
 
-/// Per-task state related to task death, killing, panic, etc.
+/// Per-thread state related to thread death, killing, panic, etc.
 pub struct Death {
     pub on_exit: Option<Thunk<Result>>,
 }
@@ -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<uint>) -> Task {
         Task {
             unwinder: Unwinder::new(),
@@ -153,17 +153,17 @@ fn spawn_thunk(opts: TaskOpts, f: Thunk) {
         })
     }
 
-    /// 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 @@ fn spawn_thunk(opts: TaskOpts, f: Thunk) {
     /// guaranteed to return if it panicks. Care should be taken to ensure that
     /// stack references made by `f` are handled appropriately.
     ///
-    /// It is invalid to call this function with a task that has been previously
+    /// It is invalid to call this function with a thread that has been previously
     /// destroyed via a failed call to `run`.
     pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> {
-        assert!(!self.is_destroyed(), "cannot re-use a destroyed task");
+        assert!(!self.is_destroyed(), "cannot re-use a destroyed thread");
 
         // First, make sure that no one else is in TLS. This does not allow
         // recursive invocations of run(). If there's no one else, then
         // relinquish ownership of ourselves back into TLS.
         if Local::exists(None::<Task>) {
-            panic!("cannot run a task recursively inside another");
+            panic!("cannot run a thread recursively inside another");
         }
         self.state = Armed;
         Local::put(self);
 
         // There are two primary reasons that general try/catch is unsafe. The
         // first is that we do not support nested try/catch. The above check for
-        // an existing task in TLS is sufficient for this invariant to be
+        // an existing thread in TLS is sufficient for this invariant to be
         // upheld. The second is that unwinding while unwinding is not defined.
-        // We take care of that by having an 'unwinding' flag in the task
+        // We take care of that by having an 'unwinding' flag in the thread
         // itself. For these reasons, this unsafety should be ok.
         let result = unsafe { unwind::try(f) };
 
-        // After running the closure given return the task back out if it ran
-        // successfully, or clean up the task if it panicked.
+        // After running the closure given return the thread back out if it ran
+        // successfully, or clean up the thread if it panicked.
         let task: Box<Task> = Local::take();
         match result {
             Ok(()) => task,
@@ -203,13 +203,13 @@ pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> {
         }
     }
 
-    /// Destroy all associated resources of this task.
+    /// Destroy all associated resources of this thread.
     ///
-    /// This function will perform any necessary clean up to prepare the task
+    /// This function will perform any necessary clean up to prepare the thread
     /// for destruction. It is required that this is called before a `Task`
     /// falls out of scope.
     ///
-    /// The returned task cannot be used for running any more code, but it may
+    /// The returned thread cannot be used for running any more code, but it may
     /// be used to extract the runtime as necessary.
     pub fn destroy(self: Box<Task>) -> Box<Task> {
         if self.is_destroyed() {
@@ -219,14 +219,14 @@ pub fn destroy(self: Box<Task>) -> Box<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<Task>, result: Result) -> Box<Task> {
         // After taking care of the data above, we need to transmit the result
-        // of this task.
+        // of this thread.
         let what_to_do = self.death.on_exit.take();
         Local::put(self);
 
@@ -235,15 +235,15 @@ fn cleanup(mut self: Box<Task>, result: Result) -> Box<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<Task> = Local::take();
         task.state = Destroyed;
@@ -253,7 +253,7 @@ fn cleanup(mut self: Box<Task>, result: Result) -> Box<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 @@ pub fn is_destroyed(&self) -> bool { self.state == Destroyed }
     // shared state. Additionally, all of the violations are protected with a
     // mutex, so in theory there are no races.
     //
-    // The first thing we need to do is to get a pointer to the task's internal
-    // mutex. This address will not be changing (because the task is allocated
-    // on the heap). We must have this handle separately because the task will
+    // The first thing we need to do is to get a pointer to the thread's internal
+    // mutex. This address will not be changing (because the thread is allocated
+    // on the heap). We must have this handle separately because the thread will
     // have its ownership transferred to the given closure. We're guaranteed,
     // however, that this memory will remain valid because *this* is the current
-    // task's execution thread.
+    // thread's execution thread.
     //
-    // The next weird part is where ownership of the task actually goes. We
+    // The next weird part is where ownership of the thread actually goes. We
     // relinquish it to the `f` blocking function, but upon returning this
-    // function needs to replace the task back in TLS. There is no communication
-    // from the wakeup thread back to this thread about the task pointer, and
-    // there's really no need to. In order to get around this, we cast the task
+    // function needs to replace the thread back in TLS. There is no communication
+    // from the wakeup thread back to this thread about the thread pointer, and
+    // there's really no need to. In order to get around this, we cast the thread
     // to a `uint` which is then used at the end of this function to cast back
     // to a `Box<Task>` object. Naturally, this looks like it violates
     // ownership semantics in that there may be two `Box<Task>` objects.
     //
     // The fun part is that the wakeup half of this implementation knows to
-    // "forget" the task on the other end. This means that the awakening half of
+    // "forget" the thread on the other end. This means that the awakening half of
     // things silently relinquishes ownership back to this thread, but not in a
-    // way that the compiler can understand. The task's memory is always valid
-    // for both tasks because these operations are all done inside of a mutex.
+    // way that the compiler can understand. The thread's memory is always valid
+    // for both threads because these operations are all done inside of a mutex.
     //
     // You'll also find that if blocking fails (the `f` function hands the
     // BlockedTask back to us), we will `mem::forget` the handles. The
-    // reasoning for this is the same logic as above in that the task silently
+    // reasoning for this is the same logic as above in that the thread silently
     // transfers ownership via the `uint`, not through normal compiler
     // semantics.
     //
@@ -319,11 +319,11 @@ pub fn deschedule<F>(mut self: Box<Task>, times: uint, mut f: F) where
                 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 @@ pub fn deschedule<F>(mut self: Box<Task>, times: uint, mut f: F) where
                     guard.wait();
                 }
             }
-            // put the task back in TLS, and everything is as it once was.
+            // put the thread back in TLS, and everything is as it once was.
             Local::put(mem::transmute(me));
         }
     }
 
-    /// Wakes up a previously blocked task. This function can only be
-    /// called on tasks that were previously blocked in `deschedule`.
+    /// Wakes up a previously blocked thread. This function can only be
+    /// called on threads that were previously blocked in `deschedule`.
     //
-    // See the comments on `deschedule` for why the task is forgotten here, and
+    // See the comments on `deschedule` for why the thread is forgotten here, and
     // why it's valid to do so.
     pub fn reawaken(mut self: Box<Task>) {
         unsafe {
@@ -362,21 +362,21 @@ pub fn reawaken(mut self: Box<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<uint> {
         if self.stack_guard != 0 {
             Some(self.stack_guard)
@@ -385,9 +385,9 @@ pub fn stack_guard(&self) -> Option<uint> {
         }
     }
 
-    /// 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 @@ pub fn drop(mut self) {
 
 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 @@ fn next(&mut self) -> Option<BlockedTask> {
 }
 
 impl BlockedTask {
-    /// Returns Some if the task was successfully woken; None if already killed.
+    /// Returns Some if the thread was successfully woken; None if already killed.
     pub fn wake(self) -> Option<Box<Task>> {
         match self {
             Owned(task) => Some(task),
@@ -427,7 +427,7 @@ pub fn wake(self) -> Option<Box<Task>> {
         }
     }
 
-    /// Reawakens this task if ownership is acquired. If finer-grained control
+    /// Reawakens this thread if ownership is acquired. If finer-grained control
     /// is desired, use `wake` instead.
     pub fn reawaken(self) {
         self.wake().map(|t| t.reawaken());
@@ -438,12 +438,12 @@ pub fn reawaken(self) {
     #[cfg(not(test))] pub fn trash(self) { }
     #[cfg(test)]      pub fn trash(self) { assert!(self.wake().is_none()); }
 
-    /// Create a blocked task, unless the task was already killed.
+    /// Create a blocked thread, unless the thread was already killed.
     pub fn block(task: Box<Task>) -> BlockedTask {
         Owned(task)
     }
 
-    /// Converts one blocked task handle to a list of many handles to the same.
+    /// Converts one blocked thread handle to a list of many handles to the same.
     pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> {
         let arc = match self {
             Owned(task) => {
@@ -543,7 +543,7 @@ fn drop_new_task_ok() {
         drop(Task::new(None, None));
     }
 
-    // Task blocking tests
+    // Thread blocking tests
 
     #[test]
     fn block_and_wake() {
index 261a8335173d0a1315b2d42144f3fd9de69ac38e..9b57dcc9e18bfc941cb4657cf198738ff620097d 100644 (file)
@@ -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 @@ struct Exception {
 ///
 /// * This is not safe to call in a nested fashion. The unwinding
 ///   interface for Rust is designed to have at most one try/catch block per
-///   task, not multiple. No runtime checking is currently performed to uphold
+///   thread, not multiple. No runtime checking is currently performed to uphold
 ///   this invariant, so this function is not safe. A nested try/catch block
 ///   may result in corruption of the outer try/catch block's state, especially
-///   if this is used within a task itself.
+///   if this is used within a thread itself.
 ///
-/// * It is not sound to trigger unwinding while already unwinding. Rust tasks
+/// * It is not sound to trigger unwinding while already unwinding. Rust threads
 ///   have runtime checks in place to ensure this invariant, but it is not
-///   guaranteed that a rust task is in place when invoking this function.
+///   guaranteed that a rust thread is in place when invoking this function.
 ///   Unwinding twice can lead to resource leaks where some destructors are not
 ///   run.
 pub unsafe fn try<F: FnOnce()>(f: F) -> Result<(), Box<Any + Send>> {
@@ -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<M: Any + Send>(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<Any + Send>, 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<Any + Send>, 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<Any + Send>, 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.
index 26778ef70b3cad5782e617a498d87096fe6a1873..bdf947438f36bd617093a36cf57868eab2a9e488 100644 (file)
@@ -180,7 +180,7 @@ fn drop(&mut self) {
 
 #[cfg(test)]
 mod test {
-    use prelude::*;
+    use prelude::{Some, None};
     use super::*;
 
     #[test]
index 6cdb199819aff60f61a996ad3426f503c621738f..4091f0df39597d2b7fc683f257baf197574e4877 100644 (file)
@@ -69,7 +69,7 @@ pub fn new(n: uint) -> 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 @@ pub fn wait(&self) {
             // 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;
index f1940bfd829b769934d46c33068f2420f2634cf8..15faf5be258f594816a289fda4d0e9f9fe8104a1 100644 (file)
 use prelude::*;
 
 use sync::atomic::{mod, AtomicUint};
-use sync::{mutex, StaticMutexGuard};
+use sync::poison::{mod, LockResult};
 use sys_common::condvar as sys;
 use sys_common::mutex as sys_mutex;
 use time::Duration;
+use sync::{mutex, MutexGuard};
 
 /// A Condition Variable
 ///
 /// // Inside of our lock, spawn a new thread, and then wait for it to start
 /// Thread::spawn(move|| {
 ///     let &(ref lock, ref cvar) = &*pair2;
-///     let mut started = lock.lock();
+///     let mut started = lock.lock().unwrap();
 ///     *started = true;
 ///     cvar.notify_one();
 /// }).detach();
 ///
 /// // wait for the thread to start up
 /// let &(ref lock, ref cvar) = &*pair;
-/// let started = lock.lock();
+/// let mut started = lock.lock().unwrap();
 /// while !*started {
-///     cvar.wait(&started);
+///     started = cvar.wait(started).unwrap();
 /// }
 /// ```
+#[stable]
 pub struct Condvar { inner: Box<StaticCondvar> }
 
 unsafe impl Send for Condvar {}
@@ -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 @@ pub fn new() -> 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 @@ pub fn new() -> 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<T: AsMutexGuard>(&self, mutex_guard: &T) {
+    #[stable]
+    pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>)
+                       -> LockResult<MutexGuard<'a, T>> {
         unsafe {
             let me: &'static Condvar = &*(self as *const _);
-            me.inner.wait(mutex_guard)
+            me.inner.wait(guard)
         }
     }
 
@@ -156,11 +159,11 @@ pub fn wait<T: AsMutexGuard>(&self, mutex_guard: &T) {
     // provide. There are also additional concerns about the unix-specific
     // implementation which may need to be addressed.
     #[allow(dead_code)]
-    fn wait_timeout<T: AsMutexGuard>(&self, mutex_guard: &T,
-                                     dur: Duration) -> bool {
+    fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>, dur: Duration)
+                           -> LockResult<(MutexGuard<'a, T>, bool)> {
         unsafe {
             let me: &'static Condvar = &*(self as *const _);
-            me.inner.wait_timeout(mutex_guard, dur)
+            me.inner.wait_timeout(guard, dur)
         }
     }
 
@@ -171,6 +174,7 @@ fn wait_timeout<T: AsMutexGuard>(&self, mutex_guard: &T,
     /// `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 @@ pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } }
     /// 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<T: AsMutexGuard>(&'static self, mutex_guard: &T) {
-        unsafe {
-            let lock = mutex_guard.as_mutex_guard();
-            let sys = mutex::guard_lock(lock);
-            self.verify(sys);
-            self.inner.wait(sys);
-            (*mutex::guard_poison(lock)).check("mutex");
+    #[unstable = "may be merged with Condvar in the future"]
+    pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
+                       -> LockResult<MutexGuard<'a, T>> {
+        let poisoned = unsafe {
+            let lock = mutex::guard_lock(&guard);
+            self.verify(lock);
+            self.inner.wait(lock);
+            mutex::guard_poison(&guard).get()
+        };
+        if poisoned {
+            Err(poison::new_poison_error(guard))
+        } else {
+            Ok(guard)
         }
     }
 
@@ -209,26 +220,31 @@ pub fn wait<T: AsMutexGuard>(&'static self, mutex_guard: &T) {
     ///
     /// See `Condvar::wait_timeout`.
     #[allow(dead_code)] // may want to stabilize this later, see wait_timeout above
-    fn wait_timeout<T: AsMutexGuard>(&'static self, mutex_guard: &T,
-                                     dur: Duration) -> bool {
-        unsafe {
-            let lock = mutex_guard.as_mutex_guard();
-            let sys = mutex::guard_lock(lock);
-            self.verify(sys);
-            let ret = self.inner.wait_timeout(sys, dur);
-            (*mutex::guard_poison(lock)).check("mutex");
-            return ret;
+    fn wait_timeout<'a, T>(&'static self, guard: MutexGuard<'a, T>, dur: Duration)
+                           -> LockResult<(MutexGuard<'a, T>, bool)> {
+        let (poisoned, success) = unsafe {
+            let lock = mutex::guard_lock(&guard);
+            self.verify(lock);
+            let success = self.inner.wait_timeout(lock, dur);
+            (mutex::guard_poison(&guard).get(), success)
+        };
+        if poisoned {
+            Err(poison::new_poison_error((guard, success)))
+        } else {
+            Ok((guard, success))
         }
     }
 
     /// Wake up one blocked thread on this condvar.
     ///
     /// See `Condvar::notify_one`.
+    #[unstable = "may be merged with Condvar in the future"]
     pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } }
 
     /// Wake up all blocked threads on this condvar.
     ///
     /// See `Condvar::notify_all`.
+    #[unstable = "may be merged with Condvar in the future"]
     pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
 
     /// Deallocate all resources associated with this static condvar.
@@ -237,6 +253,7 @@ pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } }
     /// 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 @@ fn notify_one() {
         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 @@ fn notify_all() {
             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 @@ fn notify_all() {
 
         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 @@ fn wait_timeout() {
         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 @@ fn two_mutexes() {
         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();
 
     }
 }
index 7605a6a96a005d150713a774ff97d2fda90abeff..092acc7ff25698fc1e33b0a0ed362add32665856 100644 (file)
 
 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;
index 4d2fbfc4055f4163b5df12e0f63b9b1f3517c7d0..52004bb4a8f5f4a99f59658424c13ed59af0cb91 100644 (file)
@@ -12,7 +12,7 @@
 
 use cell::UnsafeCell;
 use kinds::marker;
-use sync::{poison, AsMutexGuard};
+use sync::poison::{mod, TryLockError, TryLockResult, LockResult};
 use sys_common::mutex as sys;
 
 /// A mutual exclusion primitive useful for protecting shared data
 ///
 /// # Poisoning
 ///
-/// In order to prevent access to otherwise invalid data, each mutex will
-/// propagate any panics which occur while the lock is held. Once a thread has
-/// panicked while holding the lock, then all other threads will immediately
-/// panic as well once they hold the lock.
+/// The mutexes in this module implement a strategy called "poisoning" where a
+/// mutex is considered poisoned whenever a thread panics while holding the
+/// lock. Once a mutex is poisoned, all other tasks are unable to access the
+/// data by default as it is likely tainted (some invariant is not being
+/// upheld).
 ///
-/// # Example
+/// For a mutex, this means that the `lock` and `try_lock` methods return a
+/// `Result` which indicates whether a mutex has been poisoned or not. Most
+/// usage of a mutex will simply `unwrap()` these results, propagating panics
+/// among threads to ensure that a possibly invalid invariant is not witnessed.
+///
+/// A poisoned mutex, however, does not prevent all access to the underlying
+/// data. The `PoisonError` type has an `into_guard` method which will return
+/// the guard that would have otherwise been returned on a successful lock. This
+/// allows access to the data, despite the lock being poisoned.
+///
+/// # Examples
 ///
 /// ```rust
 /// use std::sync::{Arc, Mutex};
 /// let (tx, rx) = channel();
 /// for _ in range(0u, 10) {
 ///     let (data, tx) = (data.clone(), tx.clone());
-///     Thread::spawn(move|| {
+///     Thread::spawn(move || {
 ///         // The shared static can only be accessed once the lock is held.
 ///         // Our non-atomic increment is safe because we're the only thread
 ///         // which can access the shared state when the lock is held.
-///         let mut data = data.lock();
+///         //
+///         // We unwrap() the return value to assert that we are not expecting
+///         // tasks to ever fail while holding the lock.
+///         let mut data = data.lock().unwrap();
 ///         *data += 1;
 ///         if *data == N {
 ///             tx.send(());
 ///
 /// rx.recv();
 /// ```
+///
+/// To recover from a poisoned mutex:
+///
+/// ```rust
+/// use std::sync::{Arc, Mutex};
+/// use std::thread::Thread;
+///
+/// let lock = Arc::new(Mutex::new(0u));
+/// let lock2 = lock.clone();
+///
+/// let _ = Thread::spawn(move || -> () {
+///     // This thread will acquire the mutex first, unwrapping the result of
+///     // `lock` because the lock has not been poisoned.
+///     let _lock = lock2.lock().unwrap();
+///
+///     // This panic while holding the lock (`_guard` is in scope) will poison
+///     // the mutex.
+///     panic!();
+/// }).join();
+///
+/// // The lock is poisoned by this point, but the returned result can be
+/// // pattern matched on to return the underlying guard on both branches.
+/// let mut guard = match lock.lock() {
+///     Ok(guard) => guard,
+///     Err(poisoned) => poisoned.into_guard(),
+/// };
+///
+/// *guard += 1;
+/// ```
+#[stable]
 pub struct Mutex<T> {
     // Note that this static mutex is in a *box*, not inlined into the struct
     // itself. Once a native mutex has been used once, its address can never
@@ -93,14 +137,15 @@ unsafe impl<T:Send> Sync for Mutex<T> { }
 /// static LOCK: StaticMutex = MUTEX_INIT;
 ///
 /// {
-///     let _g = LOCK.lock();
+///     let _g = LOCK.lock().unwrap();
 ///     // do some productive work
 /// }
 /// // lock is unlocked here.
 /// ```
+#[unstable = "may be merged with Mutex in the future"]
 pub struct StaticMutex {
     lock: sys::Mutex,
-    poison: UnsafeCell<poison::Flag>,
+    poison: poison::Flag,
 }
 
 unsafe impl Sync for StaticMutex {}
@@ -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<T>,
-    __guard: StaticMutexGuard,
-}
-
-/// An RAII implementation of a "scoped lock" of a static mutex. When this
-/// structure is dropped (falls out of scope), the lock will be unlocked.
-#[must_use]
-pub struct StaticMutexGuard {
-    lock: &'static sys::Mutex,
-    marker: marker::NoSend,
-    poison: poison::Guard<'static>,
+    __lock: &'a StaticMutex,
+    __data: &'a UnsafeCell<T>,
+    __poison: poison::Guard,
+    __marker: marker::NoSend,
 }
 
 /// Static initialization of a mutex. This constant can be used to initialize
 /// other mutex constants.
+#[unstable = "may be merged with Mutex in the future"]
 pub const MUTEX_INIT: StaticMutex = StaticMutex {
     lock: sys::MUTEX_INIT,
-    poison: UnsafeCell { value: poison::Flag { failed: false } },
+    poison: poison::FLAG_INIT,
 };
 
 impl<T: Send> Mutex<T> {
     /// Creates a new mutex in an unlocked state ready for use.
+    #[stable]
     pub fn new(t: T) -> Mutex<T> {
         Mutex {
             inner: box MUTEX_INIT,
@@ -150,15 +191,14 @@ pub fn new(t: T) -> Mutex<T> {
     /// held. An RAII guard is returned to allow scoped unlock of the lock. When
     /// the guard goes out of scope, the mutex will be unlocked.
     ///
-    /// # Panics
+    /// # Failure
     ///
     /// If another user of this mutex panicked while holding the mutex, then
-    /// this call will immediately panic once the mutex is acquired.
-    pub fn lock(&self) -> MutexGuard<T> {
-        unsafe {
-            let lock: &'static StaticMutex = &*(&*self.inner as *const _);
-            MutexGuard::new(self, lock.lock())
-        }
+    /// this call will return an error once the mutex is acquired.
+    #[stable]
+    pub fn lock(&self) -> LockResult<MutexGuard<T>> {
+        unsafe { self.inner.lock.lock() }
+        MutexGuard::new(&*self.inner, &self.data)
     }
 
     /// Attempts to acquire this lock.
@@ -169,17 +209,17 @@ pub fn lock(&self) -> MutexGuard<T> {
     ///
     /// This function does not block.
     ///
-    /// # Panics
+    /// # Failure
     ///
     /// If another user of this mutex panicked while holding the mutex, then
-    /// this call will immediately panic if the mutex would otherwise be
+    /// this call will return failure if the mutex would otherwise be
     /// acquired.
-    pub fn try_lock(&self) -> Option<MutexGuard<T>> {
-        unsafe {
-            let lock: &'static StaticMutex = &*(&*self.inner as *const _);
-            lock.try_lock().map(|guard| {
-                MutexGuard::new(self, guard)
-            })
+    #[stable]
+    pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
+        if unsafe { self.inner.lock.try_lock() } {
+            Ok(try!(MutexGuard::new(&*self.inner, &self.data)))
+        } else {
+            Err(TryLockError::WouldBlock)
         }
     }
 }
@@ -194,19 +234,27 @@ fn drop(&mut self) {
     }
 }
 
+struct Dummy(UnsafeCell<()>);
+unsafe impl Sync for Dummy {}
+static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
+
 impl StaticMutex {
     /// Acquires this lock, see `Mutex::lock`
-    pub fn lock(&'static self) -> StaticMutexGuard {
+    #[inline]
+    #[unstable = "may be merged with Mutex in the future"]
+    pub fn lock(&'static self) -> LockResult<MutexGuard<()>> {
         unsafe { self.lock.lock() }
-        StaticMutexGuard::new(self)
+        MutexGuard::new(self, &DUMMY.0)
     }
 
     /// Attempts to grab this lock, see `Mutex::try_lock`
-    pub fn try_lock(&'static self) -> Option<StaticMutexGuard> {
+    #[inline]
+    #[unstable = "may be merged with Mutex in the future"]
+    pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> {
         if unsafe { self.lock.try_lock() } {
-            Some(StaticMutexGuard::new(self))
+            Ok(try!(MutexGuard::new(self, &DUMMY.0)))
         } else {
-            None
+            Err(TryLockError::WouldBlock)
         }
     }
 
@@ -220,61 +268,54 @@ pub fn try_lock(&'static self) -> Option<StaticMutexGuard> {
     /// *all* platforms. It may be the case that some platforms do not leak
     /// memory if this method is not called, but this is not guaranteed to be
     /// true on all platforms.
+    #[unstable = "may be merged with Mutex in the future"]
     pub unsafe fn destroy(&'static self) {
         self.lock.destroy()
     }
 }
 
 impl<'mutex, T> MutexGuard<'mutex, T> {
-    fn new(lock: &Mutex<T>, guard: StaticMutexGuard) -> MutexGuard<T> {
-        MutexGuard { __lock: lock, __guard: guard }
+    fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>)
+           -> LockResult<MutexGuard<'mutex, T>> {
+        poison::map_result(lock.poison.borrow(), |guard| {
+            MutexGuard {
+                __lock: lock,
+                __data: data,
+                __poison: guard,
+                __marker: marker::NoSend,
+            }
+        })
     }
 }
 
-impl<'mutex, T> AsMutexGuard for MutexGuard<'mutex, T> {
-    unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { &self.__guard }
-}
-
 impl<'mutex, T> Deref<T> for MutexGuard<'mutex, T> {
-    fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.__lock.data.get() } }
+    fn deref<'a>(&'a self) -> &'a T {
+        unsafe { &*self.__data.get() }
+    }
 }
 impl<'mutex, T> DerefMut<T> for MutexGuard<'mutex, T> {
     fn deref_mut<'a>(&'a mut self) -> &'a mut T {
-        unsafe { &mut *self.__lock.data.get() }
+        unsafe { &mut *self.__data.get() }
     }
 }
 
-impl StaticMutexGuard {
-    fn new(lock: &'static StaticMutex) -> StaticMutexGuard {
+#[unsafe_destructor]
+impl<'a, T> Drop for MutexGuard<'a, T> {
+    #[inline]
+    fn drop(&mut self) {
         unsafe {
-            let guard = StaticMutexGuard {
-                lock: &lock.lock,
-                marker: marker::NoSend,
-                poison: (*lock.poison.get()).borrow(),
-            };
-            guard.poison.check("mutex");
-            return guard;
+            self.__lock.poison.done(&self.__poison);
+            self.__lock.lock.unlock();
         }
     }
 }
 
-pub fn guard_lock(guard: &StaticMutexGuard) -> &sys::Mutex { guard.lock }
-pub fn guard_poison(guard: &StaticMutexGuard) -> &poison::Guard {
-    &guard.poison
+pub fn guard_lock<'a, T>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
+    &guard.__lock.lock
 }
 
-impl AsMutexGuard for StaticMutexGuard {
-    unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { self }
-}
-
-#[unsafe_destructor]
-impl Drop for StaticMutexGuard {
-    fn drop(&mut self) {
-        unsafe {
-            self.poison.done();
-            self.lock.unlock();
-        }
-    }
+pub fn guard_poison<'a, T>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
+    &guard.__lock.poison
 }
 
 #[cfg(test)]
@@ -292,16 +333,16 @@ unsafe impl<T> Sync for Packet<T> {}
     #[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 @@ fn lots_and_lots() {
         fn inc() {
             for _ in range(0, J) {
                 unsafe {
-                    let _g = M.lock();
+                    let _g = M.lock().unwrap();
                     CNT += 1;
                 }
             }
@@ -343,7 +384,7 @@ fn inc() {
     #[test]
     fn try_lock() {
         let m = Mutex::new(());
-        assert!(m.try_lock().is_some());
+        *m.try_lock().unwrap() = ();
     }
 
     #[test]
@@ -355,22 +396,21 @@ fn test_mutex_arc_condvar() {
             // 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 @@ fn test_arc_condvar_poison() {
         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 @@ fn test_mutex_arc_nested() {
         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 @@ struct Unwinder {
             }
             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);
     }
 }
index ad08e9873faad1ef0393bd3969c6de682e8b6306..edf16d99f4966d1e7e6a02462524fc5730f4aa4f 100644 (file)
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+use prelude::*;
+
+use cell::UnsafeCell;
+use error::FromError;
+use fmt;
 use thread::Thread;
 
-pub struct Flag { pub failed: bool }
+pub struct Flag { failed: UnsafeCell<bool> }
+pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } };
 
 impl Flag {
-    pub fn borrow(&mut self) -> Guard {
-        Guard { flag: &mut self.failed, panicking: Thread::panicking() }
+    #[inline]
+    pub fn borrow(&self) -> LockResult<Guard> {
+        let ret = Guard { panicking: Thread::panicking() };
+        if unsafe { *self.failed.get() } {
+            Err(new_poison_error(ret))
+        } else {
+            Ok(ret)
+        }
+    }
+
+    #[inline]
+    pub fn done(&self, guard: &Guard) {
+        if !guard.panicking && Thread::panicking() {
+            unsafe { *self.failed.get() = true; }
+        }
+    }
+
+    #[inline]
+    pub fn get(&self) -> bool {
+        unsafe { *self.failed.get() }
     }
 }
 
-pub struct Guard<'a> {
-    flag: &'a mut bool,
+#[allow(missing_copy_implementations)]
+pub struct Guard {
     panicking: bool,
 }
 
-impl<'a> Guard<'a> {
-    pub fn check(&self, name: &str) {
-        if *self.flag {
-            panic!("poisoned {} - another task failed inside", name);
-        }
+/// A type of error which can be returned whenever a lock is acquired.
+///
+/// Both Mutexes and RWLocks are poisoned whenever a task fails while the lock
+/// is held. The precise semantics for when a lock is poisoned is documented on
+/// each lock, but once a lock is poisoned then all future acquisitions will
+/// return this error.
+#[stable]
+pub struct PoisonError<T> {
+    guard: T,
+}
+
+/// An enumeration of possible errors which can occur while calling the
+/// `try_lock` method.
+#[stable]
+pub enum TryLockError<T> {
+    /// The lock could not be acquired because another task failed while holding
+    /// the lock.
+    #[stable]
+    Poisoned(PoisonError<T>),
+    /// The lock could not be acquired at this time because the operation would
+    /// otherwise block.
+    #[stable]
+    WouldBlock,
+}
+
+/// A type alias for the result of a lock method which can be poisoned.
+///
+/// The `Ok` variant of this result indicates that the primitive was not
+/// poisoned, and the `Guard` is contained within. The `Err` variant indicates
+/// that the primitive was poisoned. Note that the `Err` variant *also* carries
+/// the associated guard, and it can be acquired through the `into_inner`
+/// method.
+#[stable]
+pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
+
+/// A type alias for the result of a nonblocking locking method.
+///
+/// For more information, see `LockResult`. A `TryLockResult` doesn't
+/// necessarily hold the associated guard in the `Err` type as the lock may not
+/// have been acquired for other reasons.
+#[stable]
+pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
+
+impl<T> fmt::Show for PoisonError<T> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        "poisoned lock: another task failed inside".fmt(f)
+    }
+}
+
+impl<T> PoisonError<T> {
+    /// Consumes this error indicating that a lock is poisoned, returning the
+    /// underlying guard to allow access regardless.
+    #[stable]
+    pub fn into_guard(self) -> T { self.guard }
+}
+
+impl<T> FromError<PoisonError<T>> for TryLockError<T> {
+    fn from_error(err: PoisonError<T>) -> TryLockError<T> {
+        TryLockError::Poisoned(err)
     }
+}
 
-    pub fn done(&mut self) {
-        if !self.panicking && Thread::panicking() {
-            *self.flag = true;
+impl<T> fmt::Show for TryLockError<T> {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        match *self {
+            TryLockError::Poisoned(ref p) => p.fmt(f),
+            TryLockError::WouldBlock => {
+                "try_lock failed because the operation would block".fmt(f)
+            }
         }
     }
 }
+
+pub fn new_poison_error<T>(guard: T) -> PoisonError<T> {
+    PoisonError { guard: guard }
+}
+
+pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
+                           -> LockResult<U>
+                           where F: FnOnce(T) -> U {
+    match result {
+        Ok(t) => Ok(f(t)),
+        Err(PoisonError { guard }) => Err(new_poison_error(f(guard)))
+    }
+}
index 76d05d9bfd419ad796ffb8f4ad4d050c822b0a13..7f3c77c97adefdeb10c055ca31d74de7c5d9eaf7 100644 (file)
 
 use prelude::*;
 
-use kinds::marker;
 use cell::UnsafeCell;
+use kinds::marker;
+use sync::poison::{mod, LockResult, TryLockError, TryLockResult};
 use sys_common::rwlock as sys;
-use sync::poison;
 
 /// A reader-writer lock
 ///
 /// locking methods implement `Deref` (and `DerefMut` for the `write` methods)
 /// to allow access to the contained of the lock.
 ///
+/// # Poisoning
+///
 /// RWLocks, like Mutexes, will become poisoned on panics. Note, however, that
 /// an RWLock may only be poisoned if a panic occurs while it is locked
 /// exclusively (write mode). If a panic occurs in any reader, then the lock
 /// will not be poisoned.
 ///
-/// # Example
+/// # Examples
 ///
 /// ```
 /// use std::sync::RWLock;
 ///
 /// // many reader locks can be held at once
 /// {
-///     let r1 = lock.read();
-///     let r2 = lock.read();
+///     let r1 = lock.read().unwrap();
+///     let r2 = lock.read().unwrap();
 ///     assert_eq!(*r1, 5);
 ///     assert_eq!(*r2, 5);
 /// } // read locks are dropped at this point
 ///
 /// // only one write lock may be held, however
 /// {
-///     let mut w = lock.write();
+///     let mut w = lock.write().unwrap();
 ///     *w += 1;
 ///     assert_eq!(*w, 6);
 /// } // write lock is dropped here
 /// ```
+#[stable]
 pub struct RWLock<T> {
     inner: Box<StaticRWLock>,
     data: UnsafeCell<T>,
@@ -77,64 +80,55 @@ unsafe impl<T> Sync for RWLock<T> {}
 /// static LOCK: StaticRWLock = RWLOCK_INIT;
 ///
 /// {
-///     let _g = LOCK.read();
+///     let _g = LOCK.read().unwrap();
 ///     // ... shared read access
 /// }
 /// {
-///     let _g = LOCK.write();
+///     let _g = LOCK.write().unwrap();
 ///     // ... exclusive write access
 /// }
 /// unsafe { LOCK.destroy() } // free all resources
 /// ```
+#[unstable = "may be merged with RWLock in the future"]
 pub struct StaticRWLock {
-    inner: sys::RWLock,
-    poison: UnsafeCell<poison::Flag>,
+    lock: sys::RWLock,
+    poison: poison::Flag,
 }
 
 unsafe impl Send for StaticRWLock {}
 unsafe impl Sync for StaticRWLock {}
 
 /// Constant initialization for a statically-initialized rwlock.
+#[unstable = "may be merged with RWLock in the future"]
 pub const RWLOCK_INIT: StaticRWLock = StaticRWLock {
-    inner: sys::RWLOCK_INIT,
-    poison: UnsafeCell { value: poison::Flag { failed: false } },
+    lock: sys::RWLOCK_INIT,
+    poison: poison::FLAG_INIT,
 };
 
 /// RAII structure used to release the shared read access of a lock when
 /// dropped.
 #[must_use]
+#[stable]
 pub struct RWLockReadGuard<'a, T: 'a> {
-    __lock: &'a RWLock<T>,
-    __guard: StaticRWLockReadGuard,
+    __lock: &'a StaticRWLock,
+    __data: &'a UnsafeCell<T>,
+    __marker: marker::NoSend,
 }
 
 /// RAII structure used to release the exclusive write access of a lock when
 /// dropped.
 #[must_use]
+#[stable]
 pub struct RWLockWriteGuard<'a, T: 'a> {
-    __lock: &'a RWLock<T>,
-    __guard: StaticRWLockWriteGuard,
-}
-
-/// RAII structure used to release the shared read access of a lock when
-/// dropped.
-#[must_use]
-pub struct StaticRWLockReadGuard {
-    lock: &'static sys::RWLock,
-    marker: marker::NoSend,
-}
-
-/// RAII structure used to release the exclusive write access of a lock when
-/// dropped.
-#[must_use]
-pub struct StaticRWLockWriteGuard {
-    lock: &'static sys::RWLock,
-    marker: marker::NoSend,
-    poison: poison::Guard<'static>,
+    __lock: &'a StaticRWLock,
+    __data: &'a UnsafeCell<T>,
+    __poison: poison::Guard,
+    __marker: marker::NoSend,
 }
 
 impl<T: Send + Sync> RWLock<T> {
     /// Creates a new instance of an RWLock which is unlocked and read to go.
+    #[stable]
     pub fn new(t: T) -> RWLock<T> {
         RWLock { inner: box RWLOCK_INIT, data: UnsafeCell::new(t) }
     }
@@ -151,17 +145,16 @@ pub fn new(t: T) -> RWLock<T> {
     /// Returns an RAII guard which will release this thread's shared access
     /// once it is dropped.
     ///
-    /// # Panics
+    /// # Failure
     ///
-    /// This function will panic if the RWLock is poisoned. An RWLock is
-    /// poisoned whenever a writer panics while holding an exclusive lock. The
-    /// panic will occur immediately after the lock has been acquired.
+    /// This function will return an error if the RWLock is poisoned. An RWLock
+    /// is poisoned whenever a writer panics while holding an exclusive lock.
+    /// The failure will occur immediately after the lock has been acquired.
     #[inline]
-    pub fn read(&self) -> RWLockReadGuard<T> {
-        unsafe {
-            let lock: &'static StaticRWLock = &*(&*self.inner as *const _);
-            RWLockReadGuard::new(self, lock.read())
-        }
+    #[stable]
+    pub fn read(&self) -> LockResult<RWLockReadGuard<T>> {
+        unsafe { self.inner.lock.read() }
+        RWLockReadGuard::new(&*self.inner, &self.data)
     }
 
     /// Attempt to acquire this lock with shared read access.
@@ -173,18 +166,19 @@ pub fn read(&self) -> RWLockReadGuard<T> {
     /// guarantees with respect to the ordering of whether contentious readers
     /// or writers will acquire the lock first.
     ///
-    /// # Panics
+    /// # Failure
     ///
-    /// This function will panic if the RWLock is poisoned. An RWLock is
-    /// poisoned whenever a writer panics while holding an exclusive lock. A
-    /// panic will only occur if the lock is acquired.
+    /// This function will return an error if the RWLock is poisoned. An RWLock
+    /// is poisoned whenever a writer panics while holding an exclusive lock. An
+    /// error will only be returned if the lock would have otherwise been
+    /// acquired.
     #[inline]
-    pub fn try_read(&self) -> Option<RWLockReadGuard<T>> {
-        unsafe {
-            let lock: &'static StaticRWLock = &*(&*self.inner as *const _);
-            lock.try_read().map(|guard| {
-                RWLockReadGuard::new(self, guard)
-            })
+    #[stable]
+    pub fn try_read(&self) -> TryLockResult<RWLockReadGuard<T>> {
+        if unsafe { self.inner.lock.try_read() } {
+            Ok(try!(RWLockReadGuard::new(&*self.inner, &self.data)))
+        } else {
+            Err(TryLockError::WouldBlock)
         }
     }
 
@@ -197,17 +191,16 @@ pub fn try_read(&self) -> Option<RWLockReadGuard<T>> {
     /// Returns an RAII guard which will drop the write access of this rwlock
     /// when dropped.
     ///
-    /// # Panics
+    /// # Failure
     ///
-    /// This function will panic if the RWLock is poisoned. An RWLock is
-    /// poisoned whenever a writer panics while holding an exclusive lock. The
-    /// panic will occur when the lock is acquired.
+    /// This function will return an error if the RWLock is poisoned. An RWLock
+    /// is poisoned whenever a writer panics while holding an exclusive lock.
+    /// An error will be returned when the lock is acquired.
     #[inline]
-    pub fn write(&self) -> RWLockWriteGuard<T> {
-        unsafe {
-            let lock: &'static StaticRWLock = &*(&*self.inner as *const _);
-            RWLockWriteGuard::new(self, lock.write())
-        }
+    #[stable]
+    pub fn write(&self) -> LockResult<RWLockWriteGuard<T>> {
+        unsafe { self.inner.lock.write() }
+        RWLockWriteGuard::new(&*self.inner, &self.data)
     }
 
     /// Attempt to lock this rwlock with exclusive write access.
@@ -216,18 +209,19 @@ pub fn write(&self) -> RWLockWriteGuard<T> {
     /// to `write` would otherwise block. If successful, an RAII guard is
     /// returned.
     ///
-    /// # Panics
+    /// # Failure
     ///
-    /// This function will panic if the RWLock is poisoned. An RWLock is
-    /// poisoned whenever a writer panics while holding an exclusive lock. A
-    /// panic will only occur if the lock is acquired.
+    /// This function will return an error if the RWLock is poisoned. An RWLock
+    /// is poisoned whenever a writer panics while holding an exclusive lock. An
+    /// error will only be returned if the lock would have otherwise been
+    /// acquired.
     #[inline]
-    pub fn try_write(&self) -> Option<RWLockWriteGuard<T>> {
-        unsafe {
-            let lock: &'static StaticRWLock = &*(&*self.inner as *const _);
-            lock.try_write().map(|guard| {
-                RWLockWriteGuard::new(self, guard)
-            })
+    #[stable]
+    pub fn try_write(&self) -> TryLockResult<RWLockWriteGuard<T>> {
+        if unsafe { self.inner.lock.try_read() } {
+            Ok(try!(RWLockWriteGuard::new(&*self.inner, &self.data)))
+        } else {
+            Err(TryLockError::WouldBlock)
         }
     }
 }
@@ -235,30 +229,37 @@ pub fn try_write(&self) -> Option<RWLockWriteGuard<T>> {
 #[unsafe_destructor]
 impl<T> Drop for RWLock<T> {
     fn drop(&mut self) {
-        unsafe { self.inner.inner.destroy() }
+        unsafe { self.inner.lock.destroy() }
     }
 }
 
+struct Dummy(UnsafeCell<()>);
+unsafe impl Sync for Dummy {}
+static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
+
 impl StaticRWLock {
     /// Locks this rwlock with shared read access, blocking the current thread
     /// until it can be acquired.
     ///
     /// See `RWLock::read`.
     #[inline]
-    pub fn read(&'static self) -> StaticRWLockReadGuard {
-        unsafe { self.inner.read() }
-        StaticRWLockReadGuard::new(self)
+    #[unstable = "may be merged with RWLock in the future"]
+    pub fn read(&'static self) -> LockResult<RWLockReadGuard<'static, ()>> {
+        unsafe { self.lock.read() }
+        RWLockReadGuard::new(self, &DUMMY.0)
     }
 
     /// Attempt to acquire this lock with shared read access.
     ///
     /// See `RWLock::try_read`.
     #[inline]
-    pub fn try_read(&'static self) -> Option<StaticRWLockReadGuard> {
-        if unsafe { self.inner.try_read() } {
-            Some(StaticRWLockReadGuard::new(self))
+    #[unstable = "may be merged with RWLock in the future"]
+    pub fn try_read(&'static self)
+                    -> TryLockResult<RWLockReadGuard<'static, ()>> {
+        if unsafe { self.lock.try_read() } {
+            Ok(try!(RWLockReadGuard::new(self, &DUMMY.0)))
         } else {
-            None
+            Err(TryLockError::WouldBlock)
         }
     }
 
@@ -267,20 +268,23 @@ pub fn try_read(&'static self) -> Option<StaticRWLockReadGuard> {
     ///
     /// See `RWLock::write`.
     #[inline]
-    pub fn write(&'static self) -> StaticRWLockWriteGuard {
-        unsafe { self.inner.write() }
-        StaticRWLockWriteGuard::new(self)
+    #[unstable = "may be merged with RWLock in the future"]
+    pub fn write(&'static self) -> LockResult<RWLockWriteGuard<'static, ()>> {
+        unsafe { self.lock.write() }
+        RWLockWriteGuard::new(self, &DUMMY.0)
     }
 
     /// Attempt to lock this rwlock with exclusive write access.
     ///
     /// See `RWLock::try_write`.
     #[inline]
-    pub fn try_write(&'static self) -> Option<StaticRWLockWriteGuard> {
-        if unsafe { self.inner.try_write() } {
-            Some(StaticRWLockWriteGuard::new(self))
+    #[unstable = "may be merged with RWLock in the future"]
+    pub fn try_write(&'static self)
+                     -> TryLockResult<RWLockWriteGuard<'static, ()>> {
+        if unsafe { self.lock.try_write() } {
+            Ok(try!(RWLockWriteGuard::new(self, &DUMMY.0)))
         } else {
-            None
+            Err(TryLockError::WouldBlock)
         }
     }
 
@@ -290,70 +294,62 @@ pub fn try_write(&'static self) -> Option<StaticRWLockWriteGuard> {
     /// active users of the lock, and this also doesn't prevent any future users
     /// of this lock. This method is required to be called to not leak memory on
     /// all platforms.
+    #[unstable = "may be merged with RWLock in the future"]
     pub unsafe fn destroy(&'static self) {
-        self.inner.destroy()
+        self.lock.destroy()
     }
 }
 
 impl<'rwlock, T> RWLockReadGuard<'rwlock, T> {
-    fn new(lock: &RWLock<T>, guard: StaticRWLockReadGuard)
-           -> RWLockReadGuard<T> {
-        RWLockReadGuard { __lock: lock, __guard: guard }
+    fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell<T>)
+           -> LockResult<RWLockReadGuard<'rwlock, T>> {
+        poison::map_result(lock.poison.borrow(), |_| {
+            RWLockReadGuard {
+                __lock: lock,
+                __data: data,
+                __marker: marker::NoSend,
+            }
+        })
     }
 }
 impl<'rwlock, T> RWLockWriteGuard<'rwlock, T> {
-    fn new(lock: &RWLock<T>, guard: StaticRWLockWriteGuard)
-           -> RWLockWriteGuard<T> {
-        RWLockWriteGuard { __lock: lock, __guard: guard }
+    fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell<T>)
+           -> LockResult<RWLockWriteGuard<'rwlock, T>> {
+        poison::map_result(lock.poison.borrow(), |guard| {
+            RWLockWriteGuard {
+                __lock: lock,
+                __data: data,
+                __poison: guard,
+                __marker: marker::NoSend,
+            }
+        })
     }
 }
 
 impl<'rwlock, T> Deref<T> for RWLockReadGuard<'rwlock, T> {
-    fn deref(&self) -> &T { unsafe { &*self.__lock.data.get() } }
+    fn deref(&self) -> &T { unsafe { &*self.__data.get() } }
 }
 impl<'rwlock, T> Deref<T> for RWLockWriteGuard<'rwlock, T> {
-    fn deref(&self) -> &T { unsafe { &*self.__lock.data.get() } }
+    fn deref(&self) -> &T { unsafe { &*self.__data.get() } }
 }
 impl<'rwlock, T> DerefMut<T> for RWLockWriteGuard<'rwlock, T> {
-    fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.__lock.data.get() } }
-}
-
-impl StaticRWLockReadGuard {
-    fn new(lock: &'static StaticRWLock) -> StaticRWLockReadGuard {
-        let guard = StaticRWLockReadGuard {
-            lock: &lock.inner,
-            marker: marker::NoSend,
-        };
-        unsafe { (*lock.poison.get()).borrow().check("rwlock"); }
-        return guard;
-    }
-}
-impl StaticRWLockWriteGuard {
-    fn new(lock: &'static StaticRWLock) -> StaticRWLockWriteGuard {
-        unsafe {
-            let guard = StaticRWLockWriteGuard {
-                lock: &lock.inner,
-                marker: marker::NoSend,
-                poison: (*lock.poison.get()).borrow(),
-            };
-            guard.poison.check("rwlock");
-            return guard;
-        }
+    fn deref_mut(&mut self) -> &mut T {
+        unsafe { &mut *self.__data.get() }
     }
 }
 
 #[unsafe_destructor]
-impl Drop for StaticRWLockReadGuard {
+impl<'a, T> Drop for RWLockReadGuard<'a, T> {
     fn drop(&mut self) {
-        unsafe { self.lock.read_unlock(); }
+        unsafe { self.__lock.lock.read_unlock(); }
     }
 }
 
 #[unsafe_destructor]
-impl Drop for StaticRWLockWriteGuard {
+impl<'a, T> Drop for RWLockWriteGuard<'a, T> {
     fn drop(&mut self) {
-        self.poison.done();
-        unsafe { self.lock.write_unlock(); }
+        self.__lock.poison.done(&self.__poison);
+        unsafe { self.__lock.lock.write_unlock(); }
     }
 }
 
@@ -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 @@ fn frob() {
         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 @@ fn frob() {
     }
 
     #[test]
-    #[should_fail]
     fn test_rw_arc_poison_wr() {
         let arc = Arc::new(RWLock::new(1i));
         let arc2 = arc.clone();
-        let _ = Thread::spawn(move|| {
-            let lock = arc2.write();
-            assert_eq!(*lock, 2);
+        let _: Result<uint, _> = Thread::spawn(move|| {
+            let _lock = arc2.write().unwrap();
+            panic!();
         }).join();
-        let lock = arc.read();
-        assert_eq!(*lock, 1);
+        assert!(arc.read().is_err());
     }
 
     #[test]
-    #[should_fail]
     fn test_rw_arc_poison_ww() {
         let arc = Arc::new(RWLock::new(1i));
         let arc2 = arc.clone();
-        let _ = Thread::spawn(move|| {
-            let lock = arc2.write();
-            assert_eq!(*lock, 2);
+        let _: Result<uint, _> = Thread::spawn(move|| {
+            let _lock = arc2.write().unwrap();
+            panic!();
         }).join();
-        let lock = arc.write();
-        assert_eq!(*lock, 1);
+        assert!(arc.write().is_err());
     }
 
     #[test]
     fn test_rw_arc_no_poison_rr() {
         let arc = Arc::new(RWLock::new(1i));
         let arc2 = arc.clone();
-        let _ = Thread::spawn(move|| {
-            let lock = arc2.read();
-            assert_eq!(*lock, 2);
+        let _: Result<uint, _> = Thread::spawn(move|| {
+            let _lock = arc2.read().unwrap();
+            panic!();
         }).join();
-        let lock = arc.read();
+        let lock = arc.read().unwrap();
         assert_eq!(*lock, 1);
     }
     #[test]
     fn test_rw_arc_no_poison_rw() {
         let arc = Arc::new(RWLock::new(1i));
         let arc2 = arc.clone();
-        let _ = Thread::spawn(move|| {
-            let lock = arc2.read();
-            assert_eq!(*lock, 2);
+        let _: Result<uint, _> = Thread::spawn(move|| {
+            let _lock = arc2.read().unwrap();
+            panic!()
         }).join();
-        let lock = arc.write();
+        let lock = arc.write().unwrap();
         assert_eq!(*lock, 1);
     }
 
@@ -466,7 +458,7 @@ fn test_rw_arc() {
         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 @@ fn test_rw_arc() {
         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 @@ fn test_rw_arc() {
 
         // Wait for writer to finish
         rx.recv();
-        let lock = arc.read();
+        let lock = arc.read().unwrap();
         assert_eq!(*lock, 10);
     }
 
@@ -507,14 +499,14 @@ struct Unwinder {
             }
             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);
     }
 }
index 574b0f22bee00ab40e30ac3219553f5fab90ceba..e3b683a6ccb380786588fd57930197e9e2efb3c5 100644 (file)
@@ -68,9 +68,9 @@ pub fn new(count: int) -> 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 @@ pub fn acquire(&self) {
     /// 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();
     }
 
index 366e4b7d35b01eb67acd50643dc9a0ed8e44395a..ee534f6cdde3ecf135ad0e2590d597448cd88f1d 100644 (file)
@@ -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 @@ fn drop(&mut self) {
     }
 }
 
-/// 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 @@ fn drop(&mut self) {
 /// assert_eq!(rx.iter().take(8u).sum(), 8u);
 /// ```
 pub struct TaskPool {
-    // How the taskpool communicates with subtasks.
+    // How the threadpool communicates with subthreads.
     //
-    // This is the only such Sender, so when it is dropped all subtasks will
+    // This is the only such Sender, so when it is dropped all subthreads will
     // quit.
     jobs: Sender<Thunk>
 }
 
 impl TaskPool {
-    /// Spawns a new task pool with `tasks` tasks.
+    /// Spawns a new thread pool with `threads` threads.
     ///
     /// # Panics
     ///
-    /// This function will panic if `tasks` is 0.
-    pub fn new(tasks: uint) -> TaskPool {
-        assert!(tasks >= 1);
+    /// This function will panic if `threads` is 0.
+    pub fn new(threads: uint) -> TaskPool {
+        assert!(threads >= 1);
 
         let (tx, rx) = channel::<Thunk>();
         let rx = Arc::new(Mutex::new(rx));
 
-        // Taskpool tasks.
-        for _ in range(0, tasks) {
+        // Threadpool threads
+        for _ in range(0, threads) {
             spawn_in_pool(rx.clone());
         }
 
         TaskPool { jobs: tx }
     }
 
-    /// Executes the function `job` on a task in the pool.
+    /// Executes the function `job` on a thread in the pool.
     pub fn execute<F>(&self, job: F)
         where F : FnOnce(), F : Send
     {
@@ -106,14 +106,14 @@ pub fn execute<F>(&self, job: F)
 
 fn spawn_in_pool(jobs: Arc<Mutex<Receiver<Thunk>>>) {
     Thread::spawn(move |:| {
-        // Will spawn a new task on panic unless it is cancelled.
+        // Will spawn a new thread on panic unless it is cancelled.
         let sentinel = Sentinel::new(&jobs);
 
         loop {
             let message = {
                 // Only lock jobs for the time it takes
                 // to get a job, not run it.
-                let lock = jobs.lock();
+                let lock = jobs.lock().unwrap();
                 lock.recv_opt()
             };
 
@@ -165,12 +165,12 @@ fn test_recovery_from_subtask_panic() {
 
         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 @@ fn test_should_not_panic_on_drop_if_subtasks_panic_after_drop() {
         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|| {
index 1d646eb06b16774f2fd00705972f2e7cef663d86..866bf1d8a7d63ebc7812489a1c61cdf1e7886f2d 100644 (file)
@@ -115,10 +115,10 @@ macro_rules! demangle {
 
                         // 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('$') {
index a629f035b07afad3b0a5c294496549527aca27ef..9ef1c33312fc8b4ac6c5a6e354ce0caa12bcc0b2 100644 (file)
@@ -83,7 +83,7 @@ pub fn boot<T, F>(&'static self, f: F, helper: fn(helper_signal::signal, Receive
         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 @@ pub fn boot<T, F>(&'static self, f: F, helper: fn(helper_signal::signal, Receive
                 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 @@ pub fn boot<T, F>(&'static self, f: F, helper: fn(helper_signal::signal, Receive
     /// 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 @@ fn shutdown(&'static self) {
             // Shut down, but make sure this is done inside our lock to ensure
             // that we'll always receive the exit signal when the thread
             // returns.
-            let guard = self.lock.lock();
+            let mut guard = self.lock.lock().unwrap();
 
             // Close the channel by destroying it
             let chan: Box<Sender<M>> = mem::transmute(*self.chan.get());
@@ -137,7 +137,7 @@ fn shutdown(&'static self) {
 
             // Wait for the child to exit
             while !*self.shutdown.get() {
-                self.cond.wait(&guard);
+                guard = self.cond.wait(guard).unwrap();
             }
             drop(guard);
 
index 382f6875b281d01c3c788659978862f17608a381..7a09137a225dca5e21dc6d68994a9c71ee947e63 100644 (file)
@@ -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 @@ fn lock_nonblocking(&self) {}
     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 @@ fn lock_nonblocking(&self) {}
     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
index 983d0e5fa1486b1de52656a47f3035015aee4c9d..ddae9a132c31483a88b79286e6d3c1c747a872df 100644 (file)
@@ -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;
 
index f3babca32871ae86d8b36da38c2ac4c899a63522..4b7ac8ff4d3a962e3f3c33dce1e784f0cd1e93d6 100644 (file)
@@ -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
index f1b078b4e80ab6c46d3f81a23ec980e0b163830b..868b460aa5ed3897e807bc667aaf05babd764949 100644 (file)
@@ -145,7 +145,7 @@ fn lock_nonblocking(&self) {}
     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
index d1cb91bcdb377918d881db4076610a4ab03584b2..06259d61fcb8413bfa24b78e6cd36ed7352b7a87 100644 (file)
@@ -131,7 +131,6 @@ pub fn CancelIoEx(hFile: libc::HANDLE,
 
 pub mod compat {
     use intrinsics::{atomic_store_relaxed, transmute};
-    use iter::IteratorExt;
     use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID};
     use prelude::*;
 
index 15eddd569beec82d9d6171a1977283997d3b203c..3ad439078b9a146767660b3469ca6d93586add35 100644 (file)
@@ -265,8 +265,8 @@ fn prune(root: &Path, dirs: Vec<Path>) -> Vec<Path> {
                 {
                     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,
index 6924687d8c470235bed45caa3f5384fd07fe70db..aee98e22836be89280114a9260ebb6376e8955c3 100644 (file)
@@ -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
index e007b46b261b485819cfe17ed5da4413ae472e00..fa08290a888e9f3a2f86d1dcc303eec09aae1e2e 100644 (file)
@@ -99,8 +99,9 @@ fn FormatMessageW(flags: DWORD,
 
         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<String
                 // We want to explicitly catch the case when the
                 // closure returned invalid UTF-16, rather than
                 // set `res` to None and continue.
-                let s = String::from_utf16(sub)
+                let s = String::from_utf16(sub).ok()
                     .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16");
                 res = Some(s)
             }
@@ -169,8 +170,8 @@ pub fn getcwd() -> IoResult<Path> {
     }
 
     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,
index f793de5bb57ef9f735ea28fe6d989ec9be725bc4..99292b3b44bd1749b3b84ca51e3d1c4d06fdd97c 100644 (file)
@@ -101,8 +101,8 @@ pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
             };
             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);
         }
index 56731bd7ec3ee2a38d99026349cc991729b05688..a7b3ee996a34dc428bf77bb827feceb2ba5742ef 100644 (file)
@@ -313,7 +313,7 @@ fn new(name: Option<String>) -> 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<T>`, or it will implicitly join the child
     /// upon being dropped. To detach the child, allowing it to outlive the
     /// current thread, use `detach`.  See the module documentation for additional details.
@@ -334,6 +334,7 @@ pub fn yield_now() {
     }
 
     /// Determines whether the current thread is panicking.
+    #[inline]
     pub fn panicking() -> bool {
         unwind::panicking()
     }
@@ -349,9 +350,9 @@ pub fn panicking() -> bool {
     // 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 @@ pub fn park() {
     ///
     /// 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();
index 242dceb425636291692151bf6bf0c0adc2f82b6b..4cfa27093527a81720182f5692377a642458baeb 100644 (file)
@@ -240,13 +240,18 @@ pub fn with<F, R>(&'static self, f: F) -> R
         unsafe {
             let slot = slot.get().expect("cannot access a TLS value during or \
                                           after it is destroyed");
-            if (*slot.get()).is_none() {
-                *slot.get() = Some((self.init)());
-            }
-            f((*slot.get()).as_ref().unwrap())
+            f(match *slot.get() {
+                Some(ref inner) => inner,
+                None => self.init(slot),
+            })
         }
     }
 
+    unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
+        *slot.get() = Some((self.init)());
+        (*slot.get()).as_ref().unwrap()
+    }
+
     /// Test this TLS key to determine whether its value has been destroyed for
     /// the current thread or not.
     ///
index 756c86c211547efaebea7df4e9e55adc557aa867..5f96548c0530ac63badbeef3a827a5ddbc702b07 100644 (file)
@@ -62,10 +62,10 @@ pub struct Key<T> { #[doc(hidden)] pub inner: KeyInner<T> }
 #[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 @@ fn cell_allowed() {
             });
         });
     }
+
+    #[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());
+    }
 }
index debcbcd2154bddba0ebef01c2aadc164cde55b51..f253943943dcce0334a0cfbf39f335be377a5d78 100644 (file)
@@ -371,10 +371,18 @@ pub struct DefId {
 /// detects Copy, Send and Sync.
 #[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
 pub enum TyParamBound {
-    TraitTyParamBound(PolyTraitRef),
+    TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
     RegionTyParamBound(Lifetime)
 }
 
+/// A modifier on a bound, currently this is only used for `?Sized`, where the
+/// modifier is `Maybe`. Negative bounds should also be handled here.
+#[deriving(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
+pub enum TraitBoundModifier {
+    None,
+    Maybe,
+}
+
 pub type TyParamBounds = OwnedSlice<TyParamBound>;
 
 #[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)]
@@ -382,7 +390,6 @@ pub struct TyParam {
     pub ident: Ident,
     pub id: NodeId,
     pub bounds: TyParamBounds,
-    pub unbound: Option<TraitRef>,
     pub default: Option<P<Ty>>,
     pub span: Span
 }
@@ -1488,7 +1495,7 @@ pub struct PolyTraitRef {
     pub bound_lifetimes: Vec<LifetimeDef>,
 
     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
-    pub trait_ref: TraitRef
+    pub trait_ref: TraitRef,
 }
 
 #[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
@@ -1577,8 +1584,6 @@ pub enum Item_ {
     /// Represents a Trait Declaration
     ItemTrait(Unsafety,
               Generics,
-              Option<TraitRef>, // (optional) default bound not required for Self.
-                                // Currently, only Sized makes sense here.
               TyParamBounds,
               Vec<TraitItem>),
     ItemImpl(Unsafety,
index 9b42a8f75406900b0819e45c9a54595959b59f86..5a4f5731be50d9267c4ab672682f4f8cbc47b9ca 100644 (file)
@@ -780,9 +780,9 @@ fn visit_item(&mut self, i: &'ast Item) {
                     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));
                     }
                 }
index d2185a00876d2ce895efd8a055e2047446da1a0e..94a3784291d0bc595f56482a40a5c380a09f7de9 100644 (file)
@@ -139,11 +139,11 @@ fn fold_item_underscore<F>(cx: &mut Context<F>, 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)
index 77165168746b7251d6ca834f16c3017ac6dc50b7..239af1889090983b654ce639a698084142a21a60 100644 (file)
@@ -68,7 +68,6 @@ fn typaram(&self,
                span: Span,
                id: ast::Ident,
                bounds: OwnedSlice<ast::TyParamBound>,
-               unbound: Option<ast::TraitRef>,
                default: Option<P<ast::Ty>>) -> ast::TyParam;
 
     fn trait_ref(&self, path: ast::Path) -> ast::TraitRef;
@@ -414,13 +413,11 @@ fn typaram(&self,
                span: Span,
                id: ast::Ident,
                bounds: OwnedSlice<ast::TyParamBound>,
-               unbound: Option<ast::TraitRef>,
                default: Option<P<ast::Ty>>) -> ast::TyParam {
         ast::TyParam {
             ident: id,
             id: ast::DUMMY_NODE_ID,
             bounds: bounds,
-            unbound: unbound,
             default: default,
             span: span
         }
@@ -455,7 +452,7 @@ fn poly_trait_ref(&self, path: ast::Path) -> ast::PolyTraitRef {
     }
 
     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 {
index 57dfbc0c6e8bcf6f3f56ffd2a2a91e8ef997596e..3c8d74c14ee6393a8b918cd8ed2f7f586cc2f2ff 100644 (file)
@@ -58,10 +58,10 @@ fn expand_deriving_decodable_imp<F>(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 {
index 8bd3df6232ce5d61d67232fe3e7dd8c8b90cd67b..5829f34bccc5dac280e2223700933e197f986b61 100644 (file)
@@ -134,10 +134,10 @@ fn expand_deriving_encodable_imp<F>(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 {
index cf0201294ae54c02e9d941eafd370a22ea06c0ba..e4e31139d82f48925941cf6da93dc5f4bcb79c81 100644 (file)
@@ -417,7 +417,6 @@ fn create_derived_impl(&self,
             cx.typaram(self.span,
                        ty_param.ident,
                        OwnedSlice::from_vec(bounds),
-                       ty_param.unbound.clone(),
                        None)
         }));
 
index 56d11c2377fa4f58050b1d162663aeccaf31bfbc..95bdd8b9ffd2fb71116d47dfeb1efd5400c028da 100644 (file)
@@ -189,15 +189,19 @@ pub fn to_path(&self,
 }
 
 
-fn mk_ty_param(cx: &ExtCtxt, span: Span, name: &str,
-               bounds: &[Path], unbound: Option<ast::TraitRef>,
-               self_ident: Ident, self_generics: &Generics) -> ast::TyParam {
+fn mk_ty_param(cx: &ExtCtxt,
+               span: Span,
+               name: &str,
+               bounds: &[Path],
+               self_ident: Ident,
+               self_generics: &Generics)
+               -> ast::TyParam {
     let bounds =
         bounds.iter().map(|b| {
             let path = b.to_path(cx, span, self_ident, self_generics);
             cx.typarambound(path)
         }).collect();
-    cx.typaram(span, cx.ident_of(name), bounds, unbound, None)
+    cx.typaram(span, cx.ident_of(name), bounds, None)
 }
 
 fn mk_generics(lifetimes: Vec<ast::LifetimeDef>, ty_params: Vec<ast::TyParam>)
@@ -216,7 +220,7 @@ fn mk_generics(lifetimes: Vec<ast::LifetimeDef>, ty_params: Vec<ast::TyParam>)
 #[deriving(Clone)]
 pub struct LifetimeBounds<'a> {
     pub lifetimes: Vec<(&'a str, Vec<&'a str>)>,
-    pub bounds: Vec<(&'a str, Option<ast::TraitRef>, Vec<Path<'a>>)>,
+    pub bounds: Vec<(&'a str, Vec<Path<'a>>)>,
 }
 
 impl<'a> LifetimeBounds<'a> {
@@ -239,12 +243,11 @@ pub fn to_generics(&self,
         }).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)
                 }
index 4e59124a1294f042a966dd0f90c0064b67260cf5..72e3b45dc91b7b8217619deea64da07cc1f63c0a 100644 (file)
@@ -30,7 +30,7 @@ pub fn expand_deriving_hash<F>(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"))
index 4f6e4d1fb3c106484353c1e61e748e70485aaa1f..1ddf5b2a5c31eef8106680a72b9491e4143ba059 100644 (file)
@@ -36,7 +36,6 @@ pub fn expand_deriving_rand<F>(cx: &mut ExtCtxt,
                 generics: LifetimeBounds {
                     lifetimes: Vec::new(),
                     bounds: vec!(("R",
-                                  None,
                                   vec!( Path::new(vec!("std", "rand", "Rng")) )))
                 },
                 explicit_self: None,
index 11a9fdee0b9b0cb0528b474328e80b53b30c67f1..4f0169e31f2293ff65c26e55a845a8d80b612813 100644 (file)
@@ -736,18 +736,17 @@ pub fn noop_fold_ty_param_bound<T>(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<T: Folder>(tp: TyParam, fld: &mut T) -> TyParam {
-    let TyParam {id, ident, bounds, unbound, default, span} = tp;
+    let TyParam {id, ident, bounds, default, span} = tp;
     TyParam {
         id: fld.new_id(id),
         ident: ident,
         bounds: fld.fold_bounds(bounds),
-        unbound: unbound.map(|x| fld.fold_trait_ref(x)),
         default: default.map(|x| fld.fold_ty(x)),
         span: span
     }
@@ -1043,7 +1042,7 @@ pub fn noop_fold_item_underscore<T: Folder>(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<T: Folder>(i: Item_, folder: &mut T) -> Item_ {
             }).collect();
             ItemTrait(unsafety,
                       folder.fold_generics(generics),
-                      unbound,
                       bounds,
                       methods)
         }
index 2f43661eebeba7da6fad98c5a930b6381e486093..e88aabb044cc66a9296294b7deb4a1ac14869908 100644 (file)
@@ -15,7 +15,7 @@
 
 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 @@ pub fn parse_for_in_type(&mut self) -> Ty_ {
             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 @@ pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
         // 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 @@ pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_
             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 @@ pub fn parse_ty_sum(&mut self) -> P<Ty> {
             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 @@ fn handle_expression_like_statement(
 
     // Parses a sequence of bounds if a `:` is found,
     // otherwise returns empty list.
-    fn parse_colon_then_ty_param_bounds(&mut self)
+    fn parse_colon_then_ty_param_bounds(&mut self,
+                                        mode: BoundParsingMode)
                                         -> OwnedSlice<TyParamBound>
     {
         if !self.eat(&token::Colon) {
             OwnedSlice::empty()
         } else {
-            self.parse_ty_param_bounds()
+            self.parse_ty_param_bounds(mode)
         }
     }
 
@@ -4043,14 +4051,20 @@ fn parse_colon_then_ty_param_bounds(&mut self)
     // where   boundseq  = ( polybound + boundseq ) | polybound
     // and     polybound = ( 'for' '<' 'region '>' )? bound
     // and     bound     = 'region | trait_ref
-    // NB: The None/Some distinction is important for issue #7264.
-    fn parse_ty_param_bounds(&mut self)
+    fn parse_ty_param_bounds(&mut self,
+                             mode: BoundParsingMode)
                              -> OwnedSlice<TyParamBound>
     {
         let mut result = vec!();
         loop {
+            let question_span = self.span;
+            let ate_question = self.eat(&token::Question);
             match self.token {
                 token::Lifetime(lifetime) => {
+                    if ate_question {
+                        self.span_err(question_span,
+                                      "`?` may only modify trait bounds, not lifetime bounds");
+                    }
                     result.push(RegionTyParamBound(ast::Lifetime {
                         id: ast::DUMMY_NODE_ID,
                         span: self.span,
@@ -4060,7 +4074,18 @@ fn parse_ty_param_bounds(&mut self)
                 }
                 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 @@ fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
         }
     }
 
-    /// 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 @@ fn parse_ty_param(&mut self) -> TyParam {
             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 @@ fn parse_ty_param(&mut self) -> TyParam {
             ident: ident,
             id: ast::DUMMY_NODE_ID,
             bounds: bounds,
-            unbound: unbound,
             default: default,
             span: span,
         }
@@ -4260,7 +4292,7 @@ fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
                     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 @@ pub fn parse_method(&mut self,
     fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
         let ident = self.parse_ident();
         let mut tps = self.parse_generics();
-        let sized = self.parse_for_sized();
+        let unbound = self.parse_for_sized();
 
         // Parse supertrait bounds.
-        let bounds = self.parse_colon_then_ty_param_bounds();
+        let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
+
+        if let Some(unbound) = unbound {
+            let mut bounds_as_vec = bounds.into_vec();
+            bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
+                                                                trait_ref: unbound },
+                                                 TraitBoundModifier::Maybe));
+            bounds = OwnedSlice::from_vec(bounds_as_vec);
+        };
 
         self.parse_where_clause(&mut tps);
 
         let meths = self.parse_trait_items();
-        (ident, ItemTrait(unsafety, tps, sized, bounds, meths), None)
+        (ident, ItemTrait(unsafety, tps, bounds, meths), None)
     }
 
     fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
@@ -4974,12 +5014,25 @@ fn parse_visibility(&mut self) -> Visibility {
     }
 
     fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
+        // FIXME, this should really use TraitBoundModifier, but it will get
+        // re-jigged shortly in any case, so leaving the hacky version for now.
         if self.eat_keyword(keywords::For) {
             let span = self.span;
+            let mut ate_question = false;
+            if self.eat(&token::Question) {
+                ate_question = true;
+            }
             let ident = self.parse_ident();
-            if !self.eat(&token::Question) {
+            if self.eat(&token::Question) {
+                if ate_question {
+                    self.span_err(span,
+                        "unexpected `?`");
+                }
+                ate_question = true;
+            }
+            if !ate_question {
                 self.span_err(span,
-                    "expected 'Sized?' after `for` in trait item");
+                    "expected `?Sized` after `for` in trait item");
                 return None;
             }
             let tref = Parser::trait_ref_from_ident(ident, span);
@@ -5924,7 +5977,7 @@ fn parse_use(&mut self) -> ViewItem_ {
     }
 
 
-    /// 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 @@ fn parse_view_path(&mut self) -> P<ViewPath> {
         }
         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 @@ fn parse_view_path(&mut self) -> P<ViewPath> {
         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)))
     }
 
index f575d3d6c676b884a4b3042d4769bdf39ea42551..f22a4b5c6ed10b30e09a85824afe5ad703e4f161 100644 (file)
@@ -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))*/
 }
 
index accffbc35babead701d83cf1e050d2930a6dfd6c..02a03285d3b86df9e5a7d8909d77edf40688bef6 100644 (file)
@@ -13,7 +13,7 @@
 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 @@ pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
                 }
                 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 @@ pub fn print_bounds(&mut self,
                 }
 
                 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 @@ pub fn print_generics(&mut self,
     }
 
     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 {
index 22cfea862517efc15fbcec1df0f07ffe8fe81bf3..1cd21ccac7a0ef41b7d757b3ee2cb51b65333c0f 100644 (file)
@@ -85,8 +85,8 @@ fn visit_trait_ref(&mut self, t: &'v TraitRef) { walk_trait_ref(self, t) }
     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);
index a4ebcfe8a568b023bd5ad5b5e5470fcf32ed93b7..420b1100ec1cd2013aaa8e20e0c44e21af30cbba 100644 (file)
@@ -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",
index aed73472416064642911af790b25d57c9390b6c7..3a37981744a5af2433fed551f742465c78c9af7f 160000 (submodule)
@@ -1 +1 @@
-Subproject commit aed73472416064642911af790b25d57c9390b6c7
+Subproject commit 3a37981744a5af2433fed551f742465c78c9af7f
index 16129593485b85f49be57c5ce963a109dc4af314..d9a4aede7d7d910b5f0c703ee07b8bb6ea962351 100644 (file)
@@ -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) {
index 49f53bf9d3883ec555497d40fd3dc23c6f5be2da..8ec44b2dd3c1405e896d54f95232083fd9389359 100644 (file)
 
 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 (file)
index 0000000..923f95e
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+mod foo {
+    pub use self::bar::X;
+    use self::bar::X;
+    //~^ ERROR a value named `X` has already been imported in this module
+    //~| ERROR a type named `X` has already been imported in this module
+
+    mod bar {
+        pub struct X;
+    }
+}
+
+fn main() {
+    let _ = foo::X;
+}
diff --git a/src/test/compile-fail/duplicate-trait-bounds.rs b/src/test/compile-fail/duplicate-trait-bounds.rs
new file mode 100644 (file)
index 0000000..d9aa9d9
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+trait Foo {}
+
+fn foo<T: Foo + Foo>() {} //~ ERROR `Foo` already appears in the list of bounds
+
+fn main() {}
diff --git a/src/test/compile-fail/import-shadow-1.rs b/src/test/compile-fail/import-shadow-1.rs
new file mode 100644 (file)
index 0000000..007b28b
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::*;
+use bar::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+    pub type Baz = int;
+}
+
+mod bar {
+    pub type Baz = int;
+}
+
+mod qux {
+    pub use bar::Baz;
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/import-shadow-2.rs b/src/test/compile-fail/import-shadow-2.rs
new file mode 100644 (file)
index 0000000..e597b55
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::*;
+use foo::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+    pub type Baz = int;
+}
+
+mod bar {
+    pub type Baz = int;
+}
+
+mod qux {
+    pub use bar::Baz;
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/import-shadow-3.rs b/src/test/compile-fail/import-shadow-3.rs
new file mode 100644 (file)
index 0000000..68222fa
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::Baz;
+use bar::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+    pub type Baz = int;
+}
+
+mod bar {
+    pub type Baz = int;
+}
+
+mod qux {
+    pub use bar::Baz;
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/import-shadow-4.rs b/src/test/compile-fail/import-shadow-4.rs
new file mode 100644 (file)
index 0000000..c698004
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::*;
+use bar::Baz; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+    pub type Baz = int;
+}
+
+mod bar {
+    pub type Baz = int;
+}
+
+mod qux {
+    pub use bar::Baz;
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/import-shadow-5.rs b/src/test/compile-fail/import-shadow-5.rs
new file mode 100644 (file)
index 0000000..6ad7e5e
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::Baz;
+use bar::Baz; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+    pub type Baz = int;
+}
+
+mod bar {
+    pub type Baz = int;
+}
+
+mod qux {
+    pub use bar::Baz;
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/import-shadow-6.rs b/src/test/compile-fail/import-shadow-6.rs
new file mode 100644 (file)
index 0000000..1864251
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use qux::*;
+use foo::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+    pub type Baz = int;
+}
+
+mod bar {
+    pub type Baz = int;
+}
+
+mod qux {
+    pub use bar::Baz;
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/import-shadow-7.rs b/src/test/compile-fail/import-shadow-7.rs
new file mode 100644 (file)
index 0000000..a2df266
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that import shadowing using globs causes errors
+
+#![no_implicit_prelude]
+#![feature(globs)]
+
+use foo::*;
+use qux::*; //~ERROR a type named `Baz` has already been imported in this module
+
+mod foo {
+    pub type Baz = int;
+}
+
+mod bar {
+    pub type Baz = int;
+}
+
+mod qux {
+    pub use bar::Baz;
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/issue-13853-2.rs b/src/test/compile-fail/issue-13853-2.rs
new file mode 100644 (file)
index 0000000..ea0d880
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+trait FromStructReader<'a> { }
+trait ResponseHook {
+     fn get<'a, T: FromStructReader<'a>>(&'a self);
+}
+fn foo(res : Box<ResponseHook>) { res.get } //~ ERROR attempted to take value of method
+fn main() {}
diff --git a/src/test/compile-fail/issue-13853-3.rs b/src/test/compile-fail/issue-13853-3.rs
new file mode 100644 (file)
index 0000000..f10c47b
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type = "lib"]
+
+enum NodeContents<'a> {
+    Children(Vec<Node<'a>>),
+}
+
+impl<'a> Drop for NodeContents<'a> {
+    //~^ ERROR cannot implement a destructor on a structure with type parameters
+    fn drop( &mut self ) {
+    }
+}
+
+struct Node<'a> {
+    contents: NodeContents<'a>,
+}
+
+impl<'a> Node<'a> {
+    fn noName(contents: NodeContents<'a>) -> Node<'a> {
+        Node{  contents: contents,}
+    }
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/issue-13853-4.rs b/src/test/compile-fail/issue-13853-4.rs
new file mode 100644 (file)
index 0000000..7d653f5
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct AutoBuilder<'a> {
+    context: &'a int
+}
+
+impl<'a> Drop for AutoBuilder<'a> {
+    //~^ ERROR cannot implement a destructor on a structure with type parameters
+    fn drop(&mut self) {
+    }
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/issue-13853-5.rs b/src/test/compile-fail/issue-13853-5.rs
new file mode 100644 (file)
index 0000000..b3a4f34
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+trait Deserializer<'a> { }
+
+trait Deserializable {
+    fn deserialize_token<'a, D: Deserializer<'a>>(D, &'a str) -> Self;
+}
+
+impl<'a, T: Deserializable> Deserializable for &'a str {
+    //~^ ERROR unable to infer enough type information
+    fn deserialize_token<D: Deserializer<'a>>(_x: D, _y: &'a str) -> &'a str {
+    }
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/issue-13853.rs b/src/test/compile-fail/issue-13853.rs
new file mode 100644 (file)
index 0000000..868836a
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+trait Node {
+    fn zomg();
+}
+
+trait Graph<N: Node> {
+    fn nodes<'a, I: Iterator<&'a N>>(&'a self) -> I;
+}
+
+impl<N: Node> Graph<N> for Vec<N> {
+    fn nodes<'a, I: Iterator<&'a N>>(&self) -> I {
+        self.iter() //~ ERROR mismatched types
+    }
+}
+
+struct Stuff;
+
+impl Node for Stuff {
+    fn zomg() {
+        println!("zomg");
+    }
+}
+
+fn iterate<N: Node, G: Graph<N>>(graph: &G) {
+    for node in graph.iter() { //~ ERROR does not implement any method in scope named
+        node.zomg();
+    }
+}
+
+pub fn main() {
+    let graph = Vec::new();
+
+    graph.push(Stuff);
+
+    iterate(graph); //~ ERROR mismatched types
+}
diff --git a/src/test/compile-fail/issue-14227.rs b/src/test/compile-fail/issue-14227.rs
new file mode 100644 (file)
index 0000000..c4846a6
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+extern {
+    pub static symbol: ();
+}
+static CRASH: () = symbol; //~ cannot refer to other statics by value
+
+fn main() {}
diff --git a/src/test/compile-fail/issue-15034.rs b/src/test/compile-fail/issue-15034.rs
new file mode 100644 (file)
index 0000000..13d27e7
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub struct Lexer<'a> {
+    input: &'a str,
+}
+
+impl<'a> Lexer<'a> {
+    pub fn new(input: &'a str) -> Lexer<'a> {
+        Lexer { input: input }
+    }
+}
+
+struct Parser<'a> {
+    lexer: &'a mut Lexer<'a>,
+}
+
+impl<'a> Parser<'a> {
+    pub fn new(lexer: &'a mut Lexer) -> Parser<'a> {
+        Parser { lexer: lexer }
+        //~^ ERROR cannot infer an appropriate lifetime for lifetime parameter
+    }
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/issue-16538.rs b/src/test/compile-fail/issue-16538.rs
new file mode 100644 (file)
index 0000000..0e02283
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+mod Y {
+    type X = uint;
+    extern {
+        static x: *const uint;
+    }
+    fn foo(value: *const X) -> *const X {
+        value
+    }
+}
+
+static foo: *const Y::X = Y::foo(Y::x as *const Y::X);
+//~^ ERROR cannot refer to other statics by value
+//~| ERROR: the trait `core::kinds::Sync` is not implemented for the type
+
+fn main() {}
diff --git a/src/test/compile-fail/issue-17728.rs b/src/test/compile-fail/issue-17728.rs
new file mode 100644 (file)
index 0000000..50b0a1a
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::fmt::{Show, Formatter, Error};
+use std::collections::HashMap;
+
+trait HasInventory {
+    fn getInventory<'s>(&'s self) -> &'s mut Inventory;
+    fn addToInventory(&self, item: &Item);
+    fn removeFromInventory(&self, itemName: &str) -> bool;
+}
+
+trait TraversesWorld {
+    fn attemptTraverse(&self, room: &Room, directionStr: &str) -> Result<&Room, &str> {
+        let direction = str_to_direction(directionStr);
+        let maybe_room = room.direction_to_room.find(&direction);
+        //~^ ERROR cannot infer an appropriate lifetime for autoref due to conflicting requirements
+        match maybe_room {
+            Some(entry) => Ok(entry),
+            _ => Err("Direction does not exist in room.")
+        }
+    }
+}
+
+
+#[deriving(Show, Eq, PartialEq, Hash)]
+enum RoomDirection {
+    West,
+    East,
+    North,
+    South,
+    Up,
+    Down,
+    In,
+    Out,
+
+    None
+}
+
+struct Room {
+    description: String,
+    items: Vec<Item>,
+    direction_to_room: HashMap<RoomDirection, Room>,
+}
+
+impl Room {
+    fn new(description: &'static str) -> Room {
+        Room {
+            description: description.to_string(),
+            items: Vec::new(),
+            direction_to_room: HashMap::new()
+        }
+    }
+
+    fn add_direction(&mut self, direction: RoomDirection, room: Room) {
+        self.direction_to_room.insert(direction, room);
+    }
+}
+
+struct Item {
+    name: String,
+}
+
+struct Inventory {
+    items: Vec<Item>,
+}
+
+impl Inventory {
+    fn new() -> Inventory {
+        Inventory {
+            items: Vec::new()
+        }
+    }
+}
+
+struct Player {
+    name: String,
+    inventory: Inventory,
+}
+
+impl Player {
+    fn new(name: &'static str) -> Player {
+        Player {
+            name: name.to_string(),
+            inventory: Inventory::new()
+        }
+    }
+}
+
+impl TraversesWorld for Player {
+}
+
+impl Show for Player {
+    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
+        formatter.write_str("Player{ name:");
+        formatter.write_str(self.name.as_slice());
+        formatter.write_str(" }");
+        Ok(())
+    }
+}
+
+fn str_to_direction(to_parse: &str) -> RoomDirection {
+    match to_parse {
+        "w" | "west" => RoomDirection::West,
+        "e" | "east" => RoomDirection::East,
+        "n" | "north" => RoomDirection::North,
+        "s" | "south" => RoomDirection::South,
+        "in" => RoomDirection::In,
+        "out" => RoomDirection::Out,
+        "up" => RoomDirection::Up,
+        "down" => RoomDirection::Down,
+        _ => None //~ ERROR mismatched types
+    }
+}
+
+fn main() {
+    let mut player = Player::new("Test player");
+    let mut room = Room::new("A test room");
+    println!("Made a player: {}", player);
+    println!("Direction parse: {}", str_to_direction("east"));
+    match player.attemptTraverse(&room, "west") {
+        Ok(_) => println!("Was able to move west"),
+        Err(msg) => println!("Not able to move west: {}", msg)
+    };
+}
diff --git a/src/test/compile-fail/issue-17740.rs b/src/test/compile-fail/issue-17740.rs
new file mode 100644 (file)
index 0000000..73f86fe
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo<'a> {
+    data: &'a[u8],
+}
+
+impl <'a> Foo<'a>{
+    fn bar(self: &mut Foo) {
+    //~^ mismatched types: expected `Foo<'a>`, found `Foo<'_>` (lifetime mismatch)
+    //~| mismatched types: expected `Foo<'a>`, found `Foo<'_>` (lifetime mismatch)
+    }
+}
+
+fn main() {}
diff --git a/src/test/compile-fail/issue-19707.rs b/src/test/compile-fail/issue-19707.rs
new file mode 100644 (file)
index 0000000..9affb44
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(unboxed_closures)]
+#![allow(dead_code)]
+
+type foo = fn(&u8, &u8) -> &u8; //~ ERROR missing lifetime specifier
+//~^ HELP the signature does not say whether it is borrowed from argument 1 or argument 2
+
+fn bar<F: Fn(&u8, &u8) -> &u8>(f: &F) {} //~ ERROR missing lifetime specifier
+//~^ HELP the signature does not say whether it is borrowed from argument 1 or argument 2
+
+fn main() {}
index 0090dd544f6553c571983fda1271cd8aa583e54e..bbd41b28f03616a83da48c484031df58d3ff64de 100644 (file)
@@ -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<Foo> = box 5;
+    let _m: Box<Foo> = r as Box<Foo>;
+    //~^ ERROR `core::kinds::Sized` is not implemented for the type `Foo`
+    //~| ERROR `Foo` is not implemented for the type `Foo`
 }
index 2646edd7684e6fe5c5a5ecdc72e3f4f36174318e..77836143f27dd8824c8d91c7831d44f8d3b7cb64 100644 (file)
@@ -14,8 +14,7 @@
 // Regresion test for issue 7364
 static boxed: Box<RefCell<int>> = box RefCell::new(0);
 //~^ ERROR statics are not allowed to have custom pointers
-//~^^ ERROR: the trait `core::kinds::Sync` is not implemented for the type
-//~^^^ ERROR: the trait `core::kinds::Sync` is not implemented for the type
-//~^^^^ ERROR: the trait `core::kinds::Sync` is not implemented for the type
+//~| ERROR: the trait `core::kinds::Sync` is not implemented for the type
+//~| ERROR: the trait `core::kinds::Sync` is not implemented for the type
 
 fn main() { }
index 4b058f6fdb343cef21cd68dc531f15edd9352259..95ebb8bd882215524fe298fbe46989142cba7c91 100644 (file)
@@ -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 (file)
index 0000000..398b4f5
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn f() {
+    'l: loop {
+        fn g() {
+            loop {
+                break 'l; //~ ERROR use of undeclared label
+            }
+        }
+    }
+}
+
+fn main() {}
index d96599404deb840f13faaee2b10ea0f75fa727bb..f673c3b797809803e0d1d7c5bb3bc57e0ded9f87 100644 (file)
@@ -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<S: Send>() {}
 
 pub fn main() {
-    test_send::<rand::TaskRng>();
+    test_send::<rand::ThreadRng>();
     //~^ ERROR `core::kinds::Send` is not implemented
     //~^^ ERROR `core::kinds::Send` is not implemented
 }
index 2aa4264225c965b4c9f49f443cc07f4e2002af63..88d8f10e7094d9f60561c613ed05b8a0ab379239 100644 (file)
@@ -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 @@
 // 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) {
index 7b096d7d583a5e6f5126b7dd3c7d28c39daebb6e..f83734b1502eb61426eb194afc83680bca85aa63 100644 (file)
@@ -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() { <random ident> }` and checks the
 // compiler emits a span of the appropriate length (for the
@@ -18,7 +18,7 @@
 // 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(),
index 19af9fd7ea7b41ea88fafc26ba1c96d5c9497c6c..d3d2e3581aaf7e08ac4f9f7008ea0b2a7c17966d 100644 (file)
@@ -23,7 +23,7 @@ fn foo(&self) -> int {
     }
 }
 
-struct Foo<Sized? T> {
+struct Foo<T: ?Sized> {
     f: T
 }
 
index 26cb27cc653925b576e27eb874eb2dc9f28242ed..47547bb7e5a27958859a5a4ad068f41cc448f56c 100644 (file)
@@ -10,7 +10,7 @@
 
 // As dst-struct.rs, but the unsized field is the only field in the struct.
 
-struct Fat<Sized? T> {
+struct Fat<T: ?Sized> {
     ptr: T
 }
 
index 3644ca81d5659f784a13c28718cf9c1b10e07774..fb536904ac80f4d197d483fb632f72890d1e1a1e 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-struct Fat<Sized? T> {
+struct Fat<T: ?Sized> {
     f1: int,
     f2: &'static str,
     ptr: T
index 907c7810736ba98f2291fca3f316d86fd53a501b..abe55d78ac69a4bb00f9b7f99b7d4ead00694929 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-struct Fat<Sized? T> {
+struct Fat<T: ?Sized> {
     f1: int,
     f2: &'static str,
     ptr: T
diff --git a/src/test/run-pass/inconsistent-lifetime-mismatch.rs b/src/test/run-pass/inconsistent-lifetime-mismatch.rs
new file mode 100644 (file)
index 0000000..b30583c
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn foo(_: &[&str]) {}
+
+fn bad(a: &str, b: &str) {
+    foo(&[a, b]);
+}
+
+fn good(a: &str, b: &str) {
+    foo(&[a.as_slice(), b.as_slice()]);
+}
+
+fn main() {}
diff --git a/src/test/run-pass/issue-13655.rs b/src/test/run-pass/issue-13655.rs
new file mode 100644 (file)
index 0000000..6fdaac9
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(unboxed_closures)]
+use std::ops::Fn;
+
+struct Foo<T>(T);
+
+impl<T: Copy> Fn<(), T> for Foo<T> {
+    extern "rust-call" fn call(&self, _: ()) -> T {
+      match *self {
+        Foo(t) => t
+      }
+    }
+}
+
+fn main() {
+  let t: u8 = 1;
+  println!("{}", Foo(t)());
+}
diff --git a/src/test/run-pass/issue-13665.rs b/src/test/run-pass/issue-13665.rs
new file mode 100644 (file)
index 0000000..5ccbe9a
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn foo<'r>() {
+  let maybe_value_ref: Option<&'r u8> = None;
+
+  let _ = maybe_value_ref.map(|& ref v| v);
+  let _ = maybe_value_ref.map(|& ref v| -> &'r u8 {v});
+  let _ = maybe_value_ref.map(|& ref v: &'r u8| -> &'r u8 {v});
+  let _ = maybe_value_ref.map(|& ref v: &'r u8| {v});
+}
+
+fn main() {
+  foo();
+}
diff --git a/src/test/run-pass/issue-13808.rs b/src/test/run-pass/issue-13808.rs
new file mode 100644 (file)
index 0000000..e20090a
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo<'a> {
+    listener: ||: 'a
+}
+
+impl<'a> Foo<'a> {
+    fn new(listener: ||: 'a) -> Foo<'a> {
+        Foo { listener: listener }
+    }
+}
+
+fn main() {
+    let a = Foo::new(|| {});
+}
index 053a4916e229a6c3e679b7ad607b48a7fd9d9cd9..3a63e63355cd09b0eda51acee61a0bd6dd8d7f28 100644 (file)
@@ -22,7 +22,7 @@ struct IndirectBlah { x: Box<IndirectTraitWithSend> }
 impl TraitWithSend for IndirectBlah {}
 impl IndirectTraitWithSend for IndirectBlah {}
 
-fn test_trait<Sized? T: Send>() { println!("got here!") }
+fn test_trait<T: Send + ?Sized>() { println!("got here!") }
 
 fn main() {
     test_trait::<TraitWithSend>();
index fa38dcc1986730b08e7f16949a5f99635950f9e2..092bcf661a76a2b5e2ecd7a4cef68790f0fd4196 100644 (file)
@@ -11,6 +11,6 @@
 // Test that astconv doesn't forget about mutability of &mut str
 
 fn main() {
-    fn foo<Sized? T>(_: &mut T) {}
+    fn foo<T: ?Sized>(_: &mut T) {}
     let _f: fn(&mut str) = foo;
 }
diff --git a/src/test/run-pass/issue-18906.rs b/src/test/run-pass/issue-18906.rs
new file mode 100644 (file)
index 0000000..e82359b
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub trait Borrow<Sized? Borrowed> {
+        fn borrow(&self) -> &Borrowed;
+}
+
+impl<T: Sized> Borrow<T> for T {
+        fn borrow(&self) -> &T { self }
+}
+
+trait Foo {
+        fn foo(&self, other: &Self);
+}
+
+fn bar<K, Q>(k: &K, q: &Q) where K: Borrow<Q>, Q: Foo {
+    q.foo(k.borrow())
+}
+
+struct MyTree<K>;
+
+impl<K> MyTree<K> {
+    // This caused a failure in #18906
+    fn bar<Q>(k: &K, q: &Q) where K: Borrow<Q>, Q: Foo {
+        q.foo(k.borrow())
+    }
+}
+
+fn main() {}
index ee500b3d4fa36620cddf32910c7607e3dca772e6..39b0711721b54a5abccfadd47447c0d7b28f8503 100644 (file)
@@ -17,8 +17,7 @@ mod foo { pub fn p() -> int { 1 } }
     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 @@ pub mod baz {
     }
 }
 
-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();
 }
index 9bb912e081ce68363d78686e223845dc413a0106..a83bc73457e020b4bdac0682be4294f22cdff004 100644 (file)
 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!()
     }
 }
index b45faca2de6024d7d0de72bf0658cb126b390eb2..4e4fb75b428cc84f055a3a59a953b86f9771b488 100644 (file)
@@ -16,7 +16,7 @@
 use std::kinds::Sized;
 
 // Note: this must be generic for the problem to show up
-trait Foo<A> for Sized? {
+trait Foo<A> for ?Sized {
     fn foo(&self);
 }
 
index 2e4b9da691e3941dd37d28b11fc8d0fc5677a871..2d087406fd6f77a2d31eed60be0227d4646f8c12 100644 (file)
@@ -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 (file)
index 0000000..4151ad6
--- /dev/null
@@ -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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+mod base {
+    pub trait HasNew<T> {
+        fn new() -> T;
+    }
+
+    pub struct Foo {
+        dummy: (),
+    }
+
+    impl HasNew<Foo> for Foo {
+        fn new() -> Foo {
+            Foo { dummy: () }
+        }
+    }
+
+    pub struct Bar {
+        dummy: (),
+    }
+
+    impl HasNew<Bar> for Bar {
+        fn new() -> Bar {
+            Bar { dummy: () }
+        }
+    }
+}
+
+pub fn main() {
+    let _f: base::Foo = base::HasNew::new();
+    let _b: base::Bar = base::HasNew::new();
+}
index 141d6c88dd96108607083019bdceb5d4cf6928b7..07b9fac66554e0730ba063c5fe9f924ce4e07539 100644 (file)
 //
 // ignore-lexer-test FIXME #15879
 
-// Test syntax checks for `Sized?` syntax.
+// Test syntax checks for `?Sized` syntax.
 
-trait T1 for Sized? {}
-pub trait T2 for Sized? {}
-trait T3<X: T1> for Sized?: T2 {}
-trait T4<Sized? X> {}
-trait T5<Sized? X, Y> {}
-trait T6<Y, Sized? X> {}
-trait T7<Sized? X, Sized? Y> {}
-trait T8<Sized? X: T2> {}
-struct S1<Sized? X>;
-enum E<Sized? X> {}
-impl <Sized? X> T1 for S1<X> {}
-fn f<Sized? X>() {}
-type TT<Sized? T> = T;
+trait T1 for ?Sized {}
+pub trait T2 for ?Sized {}
+trait T3<X: T1> for ?Sized: T2 {}
+trait T4<X: ?Sized> {}
+trait T5<X: ?Sized, Y> {}
+trait T6<Y, X: ?Sized> {}
+trait T7<X: ?Sized, Y: ?Sized> {}
+trait T8<X: ?Sized+T2> {}
+trait T9<X: T2 + ?Sized> {}
+struct S1<X: ?Sized>;
+enum E<X: ?Sized> {}
+impl <X: ?Sized> T1 for S1<X> {}
+fn f<X: ?Sized>() {}
+type TT<T: ?Sized> = T;
 
 pub fn main() {
 }
index d28d47c0cfb85f6249850e955c0f8e67d4a92659..8d2c99d4414c9921bf2110f15c86ac1a7ba3ceaf 100644 (file)
@@ -13,7 +13,7 @@
 // Test sized-ness checking in substitution.
 
 // Unbounded.
-fn f1<Sized? X>(x: &X) {
+fn f1<X: ?Sized>(x: &X) {
     f1::<X>(x);
 }
 fn f2<X>(x: &X) {
@@ -22,8 +22,8 @@ fn f2<X>(x: &X) {
 }
 
 // Bounded.
-trait T for Sized? {}
-fn f3<Sized? X: T>(x: &X) {
+trait T for ?Sized {}
+fn f3<X: T+?Sized>(x: &X) {
     f3::<X>(x);
 }
 fn f4<X: T>(x: &X) {
@@ -32,7 +32,7 @@ fn f4<X: T>(x: &X) {
 }
 
 // Self type.
-trait T2 for Sized? {
+trait T2 for ?Sized {
     fn f() -> Box<Self>;
 }
 struct S;
@@ -41,14 +41,14 @@ fn f() -> Box<S> {
         box S
     }
 }
-fn f5<Sized? X: T2>(x: &X) {
+fn f5<X: ?Sized+T2>(x: &X) {
     let _: Box<X> = T2::f();
 }
 fn f6<X: T2>(x: &X) {
     let _: Box<X> = T2::f();
 }
 
-trait T3 for Sized? {
+trait T3 for ?Sized {
     fn f() -> Box<Self>;
 }
 impl T3 for S {
@@ -56,7 +56,7 @@ fn f() -> Box<S> {
         box S
     }
 }
-fn f7<Sized? X: T3>(x: &X) {
+fn f7<X: ?Sized+T3>(x: &X) {
     // This is valid, but the unsized bound on X is irrelevant because any type
     // which implements T3 must have statically known size.
     let _: Box<X> = T3::f();
@@ -66,7 +66,7 @@ trait T4<X> {
     fn m1(x: &T4<X>);
     fn m2(x: &T5<X>);
 }
-trait T5<Sized? X> {
+trait T5<X: ?Sized> {
     // not an error (for now)
     fn m1(x: &T4<X>);
     fn m2(x: &T5<X>);
@@ -76,21 +76,21 @@ trait T6<X: T> {
     fn m1(x: &T4<X>);
     fn m2(x: &T5<X>);
 }
-trait T7<Sized? X: T> {
+trait T7<X: ?Sized+T> {
     // not an error (for now)
     fn m1(x: &T4<X>);
     fn m2(x: &T5<X>);
 }
 
 // The last field in a struct or variant may be unsized
-struct S2<Sized? X> {
+struct S2<X: ?Sized> {
     f: X,
 }
-struct S3<Sized? X> {
+struct S3<X: ?Sized> {
     f1: int,
     f2: X,
 }
-enum E<Sized? X> {
+enum E<X: ?Sized> {
     V1(X),
     V2{x: X},
     V3(int, X),
index fe89c7532eebcc0ad429e6a9af5f2fd17a7e045c..6ff1cffb4a42f448bf9fda4a3d7cc8e98fdbf4de 100644 (file)
@@ -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::<DropCounter>()
+            let main = thread_rng().gen_iter::<DropCounter>()
                                  .take(len)
                                  .collect::<Vec<DropCounter>>();
 
index f48272366e2fdbeb047290d7ae6bcb9c7ed19024..dacfeb0081925ab0bcd6d4fc617cc60c70d0a53f 100644 (file)
@@ -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!()
     }
 }