]> git.lizzy.rs Git - rust.git/commitdiff
rollup merge of #21353: sanxiyn/upvar
authorAlex Crichton <alex@alexcrichton.com>
Tue, 10 Feb 2015 16:39:51 +0000 (08:39 -0800)
committerAlex Crichton <alex@alexcrichton.com>
Tue, 10 Feb 2015 16:39:51 +0000 (08:39 -0800)
Fix #20558.

1017 files changed:
Makefile.in
configure
man/rustc.1
mk/docs.mk
mk/main.mk
mk/tests.mk
src/compiletest/compiletest.rs
src/compiletest/errors.rs
src/compiletest/header.rs
src/compiletest/procsrv.rs
src/compiletest/runtest.rs
src/doc/reference.md
src/doc/trpl/SUMMARY.md
src/doc/trpl/compound-data-types.md
src/doc/trpl/concurrency.md [new file with mode: 0644]
src/doc/trpl/crates-and-modules.md
src/doc/trpl/ownership.md
src/doc/trpl/plugins.md
src/doc/trpl/rust-book.css [deleted file]
src/doc/trpl/threads.md [deleted file]
src/doc/trpl/unsafe.md
src/etc/errorck.py
src/etc/featureck.py
src/etc/licenseck.py
src/etc/tidy.py
src/grammar/check.sh
src/grammar/parser-lalr.y
src/grammar/testparser.py
src/grammar/verify.rs
src/liballoc/arc.rs
src/liballoc/lib.rs
src/liballoc/rc.rs
src/libcollections/bench.rs
src/libcollections/binary_heap.rs
src/libcollections/bit.rs
src/libcollections/btree/map.rs
src/libcollections/btree/node.rs
src/libcollections/btree/set.rs
src/libcollections/dlist.rs
src/libcollections/enum_set.rs
src/libcollections/fmt.rs [new file with mode: 0644]
src/libcollections/lib.rs
src/libcollections/macros.rs
src/libcollections/ring_buf.rs
src/libcollections/slice.rs
src/libcollections/str.rs
src/libcollections/string.rs
src/libcollections/vec.rs
src/libcollections/vec_map.rs
src/libcore/finally.rs
src/libcore/fmt/float.rs
src/libcore/fmt/mod.rs
src/libcore/hash/mod.rs
src/libcore/hash/sip.rs
src/libcore/iter.rs
src/libcore/lib.rs
src/libcore/marker.rs
src/libcore/mem.rs
src/libcore/ops.rs
src/libcore/ptr.rs
src/libcore/slice.rs
src/libcore/str/mod.rs
src/libcoretest/char.rs
src/libcoretest/finally.rs
src/libcoretest/hash/sip.rs
src/libcoretest/str.rs
src/libflate/lib.rs
src/libgetopts/lib.rs
src/libgraphviz/lib.rs
src/libgraphviz/maybe_owned_vec.rs [deleted file]
src/liblibc/lib.rs
src/liblog/lib.rs
src/librand/chacha.rs
src/librand/distributions/mod.rs
src/librand/isaac.rs
src/librand/lib.rs
src/librand/reseeding.rs
src/librbml/io.rs
src/librbml/lib.rs
src/librustc/diagnostics.rs
src/librustc/lint/builtin.rs
src/librustc/lint/context.rs
src/librustc/metadata/creader.rs
src/librustc/metadata/csearch.rs
src/librustc/metadata/encoder.rs
src/librustc/metadata/loader.rs
src/librustc/metadata/tydecode.rs
src/librustc/middle/astencode.rs
src/librustc/middle/check_const.rs
src/librustc/middle/check_match.rs
src/librustc/middle/const_eval.rs
src/librustc/middle/dataflow.rs
src/librustc/middle/dead.rs
src/librustc/middle/entry.rs
src/librustc/middle/expr_use_visitor.rs
src/librustc/middle/graph.rs
src/librustc/middle/infer/combine.rs
src/librustc/middle/infer/error_reporting.rs
src/librustc/middle/infer/freshen.rs
src/librustc/middle/infer/higher_ranked/mod.rs
src/librustc/middle/infer/region_inference/graphviz.rs
src/librustc/middle/infer/region_inference/mod.rs
src/librustc/middle/lang_items.rs
src/librustc/middle/liveness.rs
src/librustc/middle/mem_categorization.rs
src/librustc/middle/region.rs
src/librustc/middle/resolve_lifetime.rs
src/librustc/middle/stability.rs
src/librustc/middle/subst.rs
src/librustc/middle/traits/coherence.rs
src/librustc/middle/traits/doc.rs
src/librustc/middle/traits/error_reporting.rs
src/librustc/middle/traits/fulfill.rs
src/librustc/middle/traits/project.rs
src/librustc/middle/traits/select.rs
src/librustc/middle/traits/util.rs
src/librustc/middle/ty.rs
src/librustc/middle/ty_walk.rs
src/librustc/middle/weak_lang_items.rs
src/librustc/plugin/build.rs
src/librustc/plugin/load.rs
src/librustc/plugin/mod.rs
src/librustc/plugin/registry.rs
src/librustc/session/config.rs
src/librustc/session/mod.rs
src/librustc/session/search_paths.rs
src/librustc/util/common.rs
src/librustc/util/nodemap.rs
src/librustc/util/ppaux.rs
src/librustc/util/snapshot_vec.rs
src/librustc_back/sha2.rs
src/librustc_back/svh.rs
src/librustc_back/target/mod.rs
src/librustc_bitflags/lib.rs
src/librustc_borrowck/borrowck/check_loans.rs
src/librustc_borrowck/borrowck/doc.rs
src/librustc_borrowck/borrowck/fragments.rs
src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs
src/librustc_borrowck/borrowck/gather_loans/move_error.rs
src/librustc_borrowck/borrowck/gather_loans/restrictions.rs
src/librustc_borrowck/borrowck/mod.rs
src/librustc_borrowck/borrowck/move_data.rs
src/librustc_borrowck/graphviz.rs
src/librustc_driver/driver.rs
src/librustc_driver/lib.rs
src/librustc_driver/pretty.rs
src/librustc_driver/test.rs
src/librustc_llvm/lib.rs
src/librustc_privacy/lib.rs
src/librustc_resolve/build_reduced_graph.rs
src/librustc_resolve/diagnostics.rs
src/librustc_resolve/lib.rs
src/librustc_trans/back/link.rs
src/librustc_trans/back/lto.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/_match.rs
src/librustc_trans/trans/adt.rs
src/librustc_trans/trans/asm.rs
src/librustc_trans/trans/base.rs
src/librustc_trans/trans/build.rs
src/librustc_trans/trans/cabi_mips.rs
src/librustc_trans/trans/cabi_powerpc.rs
src/librustc_trans/trans/cabi_x86_64.rs
src/librustc_trans/trans/callee.rs
src/librustc_trans/trans/cleanup.rs
src/librustc_trans/trans/common.rs
src/librustc_trans/trans/consts.rs
src/librustc_trans/trans/context.rs
src/librustc_trans/trans/controlflow.rs
src/librustc_trans/trans/debuginfo.rs
src/librustc_trans/trans/expr.rs
src/librustc_trans/trans/foreign.rs
src/librustc_trans/trans/glue.rs
src/librustc_trans/trans/intrinsic.rs
src/librustc_trans/trans/meth.rs
src/librustc_trans/trans/monomorphize.rs
src/librustc_trans/trans/tvec.rs
src/librustc_trans/trans/type_of.rs
src/librustc_trans/trans/value.rs
src/librustc_typeck/astconv.rs
src/librustc_typeck/check/_match.rs
src/librustc_typeck/check/callee.rs
src/librustc_typeck/check/compare_method.rs
src/librustc_typeck/check/method/confirm.rs
src/librustc_typeck/check/method/probe.rs
src/librustc_typeck/check/method/suggest.rs
src/librustc_typeck/check/mod.rs
src/librustc_typeck/check/vtable.rs
src/librustc_typeck/check/wf.rs
src/librustc_typeck/check/writeback.rs
src/librustc_typeck/coherence/orphan.rs
src/librustc_typeck/collect.rs
src/librustc_typeck/diagnostics.rs
src/librustc_typeck/lib.rs
src/librustc_typeck/rscope.rs
src/librustc_typeck/variance.rs
src/librustdoc/clean/inline.rs
src/librustdoc/clean/mod.rs
src/librustdoc/core.rs
src/librustdoc/externalfiles.rs
src/librustdoc/html/escape.rs
src/librustdoc/html/format.rs
src/librustdoc/html/highlight.rs
src/librustdoc/html/markdown.rs
src/librustdoc/html/render.rs
src/librustdoc/html/toc.rs
src/librustdoc/lib.rs
src/librustdoc/markdown.rs
src/librustdoc/passes.rs
src/librustdoc/plugins.rs
src/librustdoc/test.rs
src/librustdoc/visit_ast.rs
src/libserialize/collection_impls.rs
src/libserialize/json.rs
src/libstd/ascii.rs
src/libstd/collections/hash/bench.rs
src/libstd/collections/hash/map.rs
src/libstd/collections/hash/set.rs
src/libstd/collections/hash/table.rs
src/libstd/collections/mod.rs
src/libstd/dynamic_lib.rs
src/libstd/env.rs
src/libstd/ffi/c_str.rs
src/libstd/fmt.rs [deleted file]
src/libstd/fs.rs [new file with mode: 0644]
src/libstd/io/mod.rs
src/libstd/io/prelude.rs
src/libstd/lib.rs
src/libstd/macros.rs
src/libstd/num/mod.rs
src/libstd/num/strconv.rs
src/libstd/old_io/buffered.rs
src/libstd/old_io/comm_adapters.rs
src/libstd/old_io/extensions.rs
src/libstd/old_io/fs.rs
src/libstd/old_io/mem.rs
src/libstd/old_io/mod.rs
src/libstd/old_io/net/ip.rs
src/libstd/old_io/process.rs
src/libstd/old_io/result.rs
src/libstd/old_io/util.rs
src/libstd/old_path/posix.rs
src/libstd/old_path/windows.rs
src/libstd/os.rs
src/libstd/path.rs
src/libstd/rand/mod.rs
src/libstd/rand/os.rs
src/libstd/rt/args.rs
src/libstd/rt/unwind.rs
src/libstd/rt/util.rs
src/libstd/sync/barrier.rs
src/libstd/sync/condvar.rs
src/libstd/sync/future.rs
src/libstd/sync/mpsc/mod.rs
src/libstd/sync/mpsc/oneshot.rs
src/libstd/sync/mpsc/spsc_queue.rs
src/libstd/sync/mutex.rs
src/libstd/sync/poison.rs
src/libstd/sync/rwlock.rs
src/libstd/sync/task_pool.rs
src/libstd/sys/common/helper_thread.rs
src/libstd/sys/common/mod.rs
src/libstd/sys/common/net.rs
src/libstd/sys/common/thread_info.rs
src/libstd/sys/common/wtf8.rs
src/libstd/sys/unix/c.rs
src/libstd/sys/unix/ext.rs
src/libstd/sys/unix/fd.rs [new file with mode: 0644]
src/libstd/sys/unix/fs2.rs [new file with mode: 0644]
src/libstd/sys/unix/mod.rs
src/libstd/sys/unix/os.rs
src/libstd/sys/unix/os_str.rs
src/libstd/sys/unix/pipe.rs
src/libstd/sys/unix/process.rs
src/libstd/sys/windows/ext.rs
src/libstd/sys/windows/fs2.rs [new file with mode: 0644]
src/libstd/sys/windows/handle.rs
src/libstd/sys/windows/mod.rs
src/libstd/sys/windows/os.rs
src/libstd/sys/windows/process.rs
src/libstd/sys/windows/thread_local.rs
src/libstd/sys/windows/tty.rs
src/libstd/thread.rs
src/libstd/thunk.rs
src/libstd/time/duration.rs
src/libsyntax/ast.rs
src/libsyntax/ast_map/blocks.rs
src/libsyntax/ast_util.rs
src/libsyntax/attr.rs
src/libsyntax/codemap.rs
src/libsyntax/config.rs
src/libsyntax/diagnostics/macros.rs
src/libsyntax/diagnostics/plugin.rs
src/libsyntax/diagnostics/registry.rs
src/libsyntax/ext/asm.rs
src/libsyntax/ext/base.rs
src/libsyntax/ext/build.rs
src/libsyntax/ext/cfg.rs
src/libsyntax/ext/cfg_attr.rs
src/libsyntax/ext/concat.rs
src/libsyntax/ext/concat_idents.rs
src/libsyntax/ext/deriving/bounds.rs
src/libsyntax/ext/deriving/clone.rs
src/libsyntax/ext/deriving/cmp/eq.rs
src/libsyntax/ext/deriving/cmp/ord.rs
src/libsyntax/ext/deriving/cmp/totaleq.rs
src/libsyntax/ext/deriving/cmp/totalord.rs
src/libsyntax/ext/deriving/decodable.rs
src/libsyntax/ext/deriving/default.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/mod.rs
src/libsyntax/ext/deriving/primitive.rs
src/libsyntax/ext/deriving/rand.rs
src/libsyntax/ext/deriving/show.rs
src/libsyntax/ext/env.rs
src/libsyntax/ext/expand.rs
src/libsyntax/ext/format.rs
src/libsyntax/ext/quote.rs
src/libsyntax/ext/source_util.rs
src/libsyntax/ext/tt/macro_parser.rs
src/libsyntax/ext/tt/macro_rules.rs
src/libsyntax/feature_gate.rs
src/libsyntax/fold.rs
src/libsyntax/owned_slice.rs
src/libsyntax/parse/lexer/mod.rs
src/libsyntax/parse/mod.rs
src/libsyntax/parse/obsolete.rs
src/libsyntax/parse/parser.rs
src/libsyntax/parse/token.rs
src/libsyntax/print/pprust.rs
src/libsyntax/std_inject.rs
src/libsyntax/test.rs
src/libsyntax/util/small_vector.rs
src/libsyntax/visit.rs
src/libterm/terminfo/mod.rs
src/libterm/terminfo/parm.rs
src/libtest/lib.rs
src/libtest/stats.rs
src/libunicode/lib.rs
src/libunicode/u_str.rs
src/rt/rust_builtin.c
src/rustbook/css.rs
src/rustbook/javascript.rs
src/snapshots.txt
src/test/auxiliary/issue-18711.rs
src/test/auxiliary/issue-21146-inc.rs [new file with mode: 0644]
src/test/auxiliary/lang-item-public.rs
src/test/auxiliary/lint_group_plugin_test.rs
src/test/auxiliary/lint_plugin_test.rs
src/test/auxiliary/logging_right_crate.rs
src/test/auxiliary/no_std_crate.rs
src/test/auxiliary/plugin_args.rs
src/test/auxiliary/roman_numerals.rs
src/test/auxiliary/static-methods-crate.rs
src/test/auxiliary/syntax-extension-with-dll-deps-1.rs [deleted file]
src/test/auxiliary/syntax-extension-with-dll-deps-2.rs [deleted file]
src/test/auxiliary/syntax_extension_with_dll_deps_1.rs [new file with mode: 0644]
src/test/auxiliary/syntax_extension_with_dll_deps_2.rs [new file with mode: 0644]
src/test/auxiliary/unboxed-closures-cross-crate.rs
src/test/auxiliary/weak-lang-items.rs
src/test/bench/core-map.rs
src/test/bench/core-set.rs
src/test/bench/core-std.rs
src/test/bench/msgsend-pipes-shared.rs
src/test/bench/msgsend-pipes.rs
src/test/bench/rt-messaging-ping-pong.rs
src/test/bench/rt-parfib.rs
src/test/bench/shootout-binarytrees.rs
src/test/bench/shootout-chameneos-redux.rs
src/test/bench/shootout-fannkuch-redux.rs
src/test/bench/shootout-fasta-redux.rs
src/test/bench/shootout-fasta.rs
src/test/bench/shootout-k-nucleotide-pipes.rs
src/test/bench/shootout-k-nucleotide.rs
src/test/bench/shootout-mandelbrot.rs
src/test/bench/shootout-nbody.rs
src/test/bench/shootout-pfib.rs
src/test/bench/shootout-reverse-complement.rs
src/test/bench/shootout-spectralnorm.rs
src/test/bench/sudoku.rs
src/test/compile-fail-fulldeps/gated-plugin.rs
src/test/compile-fail-fulldeps/lint-group-plugin-deny-cmdline.rs
src/test/compile-fail-fulldeps/lint-plugin-deny-attr.rs
src/test/compile-fail-fulldeps/lint-plugin-deny-cmdline.rs
src/test/compile-fail-fulldeps/lint-plugin-forbid-attrs.rs
src/test/compile-fail-fulldeps/lint-plugin-forbid-cmdline.rs
src/test/compile-fail-fulldeps/macro-crate-cannot-read-embedded-ident.rs
src/test/compile-fail-fulldeps/macro-crate-rlib.rs
src/test/compile-fail-fulldeps/plugin-MacroRulesTT.rs
src/test/compile-fail/array-old-syntax-1.rs [deleted file]
src/test/compile-fail/assign-to-method.rs
src/test/compile-fail/assoc-inherent.rs
src/test/compile-fail/associated-types-ICE-when-projecting-out-of-err.rs
src/test/compile-fail/associated-types-project-from-hrtb-explicit.rs [deleted file]
src/test/compile-fail/attr-bad-meta.rs [deleted file]
src/test/compile-fail/bad-match.rs [deleted file]
src/test/compile-fail/bad-mid-path-type-params.rs
src/test/compile-fail/bad-name.rs [deleted file]
src/test/compile-fail/better-expected.rs [deleted file]
src/test/compile-fail/bind-struct-early-modifiers.rs [deleted file]
src/test/compile-fail/blind-item-local-shadow.rs
src/test/compile-fail/borrowck-array-double-move.rs [deleted file]
src/test/compile-fail/borrowck-assign-comp-idx.rs
src/test/compile-fail/borrowck-borrowed-uniq-rvalue-2.rs
src/test/compile-fail/borrowck-call-is-borrow-issue-12224.rs
src/test/compile-fail/borrowck-closures-mut-and-imm.rs
src/test/compile-fail/borrowck-closures-mut-of-imm.rs
src/test/compile-fail/borrowck-closures-two-mut.rs
src/test/compile-fail/borrowck-closures-unique-imm.rs
src/test/compile-fail/borrowck-closures-unique.rs
src/test/compile-fail/borrowck-closures-use-after-free.rs
src/test/compile-fail/borrowck-init-in-called-fn-expr.rs
src/test/compile-fail/borrowck-init-in-fn-expr.rs
src/test/compile-fail/borrowck-move-out-of-vec-tail.rs
src/test/compile-fail/borrowck-mut-slice-of-imm-vec.rs
src/test/compile-fail/borrowck-overloaded-index-autoderef.rs
src/test/compile-fail/borrowck-overloaded-index.rs
src/test/compile-fail/borrowck-report-with-custom-diagnostic.rs
src/test/compile-fail/borrowck-use-in-index-lvalue.rs
src/test/compile-fail/borrowck-vec-pattern-element-loan.rs
src/test/compile-fail/borrowck-vec-pattern-loan-from-mut.rs
src/test/compile-fail/borrowck-vec-pattern-move-tail.rs
src/test/compile-fail/borrowck-vec-pattern-nesting.rs
src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs
src/test/compile-fail/byte-literals.rs [deleted file]
src/test/compile-fail/byte-string-literals.rs [deleted file]
src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs
src/test/compile-fail/circular_modules_hello.rs [deleted file]
src/test/compile-fail/circular_modules_main.rs [deleted file]
src/test/compile-fail/class-implements-bad-trait.rs [deleted file]
src/test/compile-fail/closure-reform-bad.rs
src/test/compile-fail/column-offset-1-based.rs [deleted file]
src/test/compile-fail/dead-code-closure-bang.rs
src/test/compile-fail/derive-no-std-not-supported.rs [new file with mode: 0644]
src/test/compile-fail/duplicate-visibility.rs [deleted file]
src/test/compile-fail/empty-impl-semicolon.rs [deleted file]
src/test/compile-fail/estr-subtyping.rs
src/test/compile-fail/extern-expected-fn-or-brace.rs [deleted file]
src/test/compile-fail/extern-foreign-crate.rs [deleted file]
src/test/compile-fail/extern-no-fn.rs [deleted file]
src/test/compile-fail/fn-trait-formatting.rs
src/test/compile-fail/gated-bad-feature.rs
src/test/compile-fail/gated-no-std.rs [new file with mode: 0644]
src/test/compile-fail/immut-function-arguments.rs
src/test/compile-fail/import-from-path.rs [deleted file]
src/test/compile-fail/import-from-rename.rs [deleted file]
src/test/compile-fail/import-glob-path.rs [deleted file]
src/test/compile-fail/import-glob-rename.rs [deleted file]
src/test/compile-fail/integral-indexing.rs
src/test/compile-fail/issue-10392-2.rs [deleted file]
src/test/compile-fail/issue-10392.rs [deleted file]
src/test/compile-fail/issue-10398.rs
src/test/compile-fail/issue-10636-1.rs [deleted file]
src/test/compile-fail/issue-10636-2.rs [deleted file]
src/test/compile-fail/issue-11192.rs
src/test/compile-fail/issue-11374.rs
src/test/compile-fail/issue-11873.rs
src/test/compile-fail/issue-12369.rs
src/test/compile-fail/issue-14303-enum.rs [deleted file]
src/test/compile-fail/issue-14303-fn-def.rs [deleted file]
src/test/compile-fail/issue-14303-fncall.rs [deleted file]
src/test/compile-fail/issue-14303-impl.rs [deleted file]
src/test/compile-fail/issue-14303-path.rs [deleted file]
src/test/compile-fail/issue-14303-struct.rs [deleted file]
src/test/compile-fail/issue-14303-trait.rs [deleted file]
src/test/compile-fail/issue-15783.rs
src/test/compile-fail/issue-15914.rs [deleted file]
src/test/compile-fail/issue-1655.rs [deleted file]
src/test/compile-fail/issue-16939.rs
src/test/compile-fail/issue-17551.rs
src/test/compile-fail/issue-17651.rs
src/test/compile-fail/issue-17728.rs
src/test/compile-fail/issue-17904.rs [deleted file]
src/test/compile-fail/issue-1802-1.rs [deleted file]
src/test/compile-fail/issue-19096.rs [deleted file]
src/test/compile-fail/issue-19398.rs [deleted file]
src/test/compile-fail/issue-19660.rs
src/test/compile-fail/issue-20711-2.rs [deleted file]
src/test/compile-fail/issue-20711.rs [deleted file]
src/test/compile-fail/issue-21146.rs [new file with mode: 0644]
src/test/compile-fail/issue-21153.rs [deleted file]
src/test/compile-fail/issue-2149.rs
src/test/compile-fail/issue-21974.rs [new file with mode: 0644]
src/test/compile-fail/issue-2354-1.rs [deleted file]
src/test/compile-fail/issue-2354.rs [deleted file]
src/test/compile-fail/issue-3036.rs [deleted file]
src/test/compile-fail/issue-3044.rs
src/test/compile-fail/issue-3563.rs
src/test/compile-fail/issue-4335.rs
src/test/compile-fail/issue-5239-1.rs
src/test/compile-fail/issue-5806.rs [deleted file]
src/test/compile-fail/issue-6610.rs [deleted file]
src/test/compile-fail/issue-6801.rs
src/test/compile-fail/issue-7364.rs
src/test/compile-fail/issue-7573.rs
src/test/compile-fail/issue-9243.rs
src/test/compile-fail/keyword-abstract.rs [deleted file]
src/test/compile-fail/keyword-do-as-identifier.rs [deleted file]
src/test/compile-fail/keyword-final.rs [deleted file]
src/test/compile-fail/keyword-mut-as-identifier.rs [deleted file]
src/test/compile-fail/keyword-override.rs [deleted file]
src/test/compile-fail/keyword-priv-as-identifier.rs [deleted file]
src/test/compile-fail/keyword-ref-as-identifier.rs [deleted file]
src/test/compile-fail/keyword-typeof.rs [deleted file]
src/test/compile-fail/lang-item-missing.rs
src/test/compile-fail/lex-bad-char-literals.rs [deleted file]
src/test/compile-fail/lex-bad-token.rs [deleted file]
src/test/compile-fail/lint-dead-code-1.rs
src/test/compile-fail/lint-missing-doc.rs
src/test/compile-fail/lint-unused-mut-variables.rs
src/test/compile-fail/lub-if.rs
src/test/compile-fail/lub-match.rs
src/test/compile-fail/macro-attribute.rs [deleted file]
src/test/compile-fail/macro-bad-delimiter-ident.rs [deleted file]
src/test/compile-fail/macro-keyword.rs [deleted file]
src/test/compile-fail/macro-mismatched-delim-brace-paren.rs [deleted file]
src/test/compile-fail/macro-mismatched-delim-paren-brace.rs [deleted file]
src/test/compile-fail/macros-no-semicolon.rs [deleted file]
src/test/compile-fail/malformed-plugin-1.rs [new file with mode: 0644]
src/test/compile-fail/malformed-plugin-2.rs [new file with mode: 0644]
src/test/compile-fail/malformed-plugin-3.rs [new file with mode: 0644]
src/test/compile-fail/match-arrows-block-then-binop.rs [deleted file]
src/test/compile-fail/match-vec-invalid.rs [deleted file]
src/test/compile-fail/match-vec-unreachable.rs
src/test/compile-fail/missing_debug_impls.rs
src/test/compile-fail/mod_file_disambig.rs [deleted file]
src/test/compile-fail/mod_file_not_exist.rs [deleted file]
src/test/compile-fail/mod_file_not_owning.rs [deleted file]
src/test/compile-fail/mod_file_with_path_attr.rs [deleted file]
src/test/compile-fail/move-fragments-9.rs
src/test/compile-fail/move-into-dead-array-1.rs [new file with mode: 0644]
src/test/compile-fail/move-into-dead-array-2.rs [new file with mode: 0644]
src/test/compile-fail/move-out-of-array-1.rs [new file with mode: 0644]
src/test/compile-fail/moves-based-on-type-exprs.rs
src/test/compile-fail/multi-plugin-attr.rs [deleted file]
src/test/compile-fail/multiline-comment-line-tracking.rs [deleted file]
src/test/compile-fail/multitrait.rs [deleted file]
src/test/compile-fail/mut-patterns.rs [deleted file]
src/test/compile-fail/new-unicode-escapes-1.rs [deleted file]
src/test/compile-fail/new-unicode-escapes-2.rs [deleted file]
src/test/compile-fail/new-unicode-escapes-3.rs [deleted file]
src/test/compile-fail/new-unicode-escapes-4.rs [deleted file]
src/test/compile-fail/non-exhaustive-match.rs
src/test/compile-fail/not-a-pred.rs [deleted file]
src/test/compile-fail/omitted-arg-in-item-fn.rs [deleted file]
src/test/compile-fail/paamayim-nekudotayim.rs [deleted file]
src/test/compile-fail/packed-struct-generic-transmute.rs
src/test/compile-fail/parenthesized-box-expr-message.rs [deleted file]
src/test/compile-fail/pat-range-bad-dots.rs [deleted file]
src/test/compile-fail/pat-ref-enum.rs [deleted file]
src/test/compile-fail/plugin-extern-crate-attr-deprecated.rs [new file with mode: 0644]
src/test/compile-fail/privacy1.rs
src/test/compile-fail/privacy2.rs
src/test/compile-fail/privacy3.rs
src/test/compile-fail/privacy4.rs
src/test/compile-fail/range-3.rs [deleted file]
src/test/compile-fail/range-4.rs [deleted file]
src/test/compile-fail/raw-byte-string-eof.rs [deleted file]
src/test/compile-fail/raw-byte-string-literals.rs [deleted file]
src/test/compile-fail/raw-str-delim.rs [deleted file]
src/test/compile-fail/raw-str-unbalanced.rs [deleted file]
src/test/compile-fail/raw-str-unterminated.rs [deleted file]
src/test/compile-fail/refutable-pattern-in-fn-arg.rs
src/test/compile-fail/region-bound-on-closure-outlives-call.rs
src/test/compile-fail/regionck-unboxed-closure-lifetimes.rs
src/test/compile-fail/regions-addr-of-upvar-self.rs
src/test/compile-fail/regions-bounded-method-type-parameters-trait-bound.rs
src/test/compile-fail/regions-escape-unboxed-closure.rs
src/test/compile-fail/regions-glb-free-free.rs
src/test/compile-fail/regions-infer-paramd-method.rs [deleted file]
src/test/compile-fail/regions-out-of-scope-slice.rs [deleted file]
src/test/compile-fail/regions-pattern-typing-issue-19552.rs
src/test/compile-fail/regions-return-ref-to-upvar-issue-17403.rs
src/test/compile-fail/regions-struct-not-wf.rs
src/test/compile-fail/regions-trait-2.rs [deleted file]
src/test/compile-fail/regions-trait-3.rs [deleted file]
src/test/compile-fail/removed-syntax-closure-lifetime.rs [deleted file]
src/test/compile-fail/removed-syntax-enum-newtype.rs [deleted file]
src/test/compile-fail/removed-syntax-extern-const.rs [deleted file]
src/test/compile-fail/removed-syntax-field-let.rs [deleted file]
src/test/compile-fail/removed-syntax-field-semicolon.rs [deleted file]
src/test/compile-fail/removed-syntax-fixed-vec.rs [deleted file]
src/test/compile-fail/removed-syntax-fn-pure.rs [deleted file]
src/test/compile-fail/removed-syntax-fn-sigil.rs [deleted file]
src/test/compile-fail/removed-syntax-larrow-init.rs [deleted file]
src/test/compile-fail/removed-syntax-larrow-move.rs [deleted file]
src/test/compile-fail/removed-syntax-mode.rs [deleted file]
src/test/compile-fail/removed-syntax-mut-vec-expr.rs [deleted file]
src/test/compile-fail/removed-syntax-mut-vec-ty.rs [deleted file]
src/test/compile-fail/removed-syntax-ptr-lifetime.rs [deleted file]
src/test/compile-fail/removed-syntax-record.rs [deleted file]
src/test/compile-fail/removed-syntax-static-fn.rs [deleted file]
src/test/compile-fail/removed-syntax-uniq-mut-expr.rs [deleted file]
src/test/compile-fail/removed-syntax-uniq-mut-ty.rs [deleted file]
src/test/compile-fail/removed-syntax-with-1.rs [deleted file]
src/test/compile-fail/removed-syntax-with-2.rs [deleted file]
src/test/compile-fail/required-lang-item.rs
src/test/compile-fail/reserved-be.rs [deleted file]
src/test/compile-fail/slice-1.rs
src/test/compile-fail/slice-2.rs
src/test/compile-fail/stable-features.rs [new file with mode: 0644]
src/test/compile-fail/struct-literal-in-for.rs [deleted file]
src/test/compile-fail/struct-literal-in-if.rs [deleted file]
src/test/compile-fail/struct-literal-in-match-discriminant.rs [deleted file]
src/test/compile-fail/struct-literal-in-while.rs [deleted file]
src/test/compile-fail/struct-no-fields-enumlike.rs [deleted file]
src/test/compile-fail/struct-no-fields.rs [deleted file]
src/test/compile-fail/trait-coercion-generic-regions.rs
src/test/compile-fail/trait-keyword.rs [deleted file]
src/test/compile-fail/unbalanced-doublequote.rs [deleted file]
src/test/compile-fail/unboxed-closure-immutable-capture.rs
src/test/compile-fail/unboxed-closure-region.rs
src/test/compile-fail/unboxed-closure-sugar-used-on-struct-3.rs [deleted file]
src/test/compile-fail/unboxed-closures-borrow-conflict.rs
src/test/compile-fail/unboxed-closures-infer-argument-types-two-region-pointers.rs
src/test/compile-fail/unboxed-closures-type-mismatch.rs
src/test/compile-fail/unsized.rs [deleted file]
src/test/compile-fail/unused-mut-warning-captured-var.rs
src/test/compile-fail/use-as-where-use-ends-with-mod-sep.rs [deleted file]
src/test/compile-fail/use-ends-with-mod-sep.rs [deleted file]
src/test/compile-fail/use-mod-4.rs [deleted file]
src/test/compile-fail/variadic-ffi-1.rs [deleted file]
src/test/compile-fail/variadic-ffi-3.rs [deleted file]
src/test/compile-fail/variadic-ffi-4.rs [deleted file]
src/test/compile-fail/weak-lang-item.rs
src/test/compile-fail/where-for-self-2.rs [new file with mode: 0644]
src/test/compile-fail/where-for-self.rs [new file with mode: 0644]
src/test/debuginfo/closure-in-generic-function.rs
src/test/debuginfo/constant-in-match-pattern.rs [new file with mode: 0644]
src/test/debuginfo/lexical-scope-in-parameterless-closure.rs
src/test/debuginfo/lexical-scope-in-stack-closure.rs
src/test/debuginfo/lexical-scope-in-unique-closure.rs
src/test/debuginfo/multi-byte-chars.rs
src/test/debuginfo/type-names.rs
src/test/debuginfo/var-captured-in-nested-closure.rs
src/test/debuginfo/var-captured-in-sendable-closure.rs
src/test/debuginfo/var-captured-in-stack-closure.rs
src/test/parse-fail/array-old-syntax-1.rs [new file with mode: 0644]
src/test/parse-fail/associated-types-project-from-hrtb-explicit.rs [new file with mode: 0644]
src/test/parse-fail/attr-bad-meta.rs [new file with mode: 0644]
src/test/parse-fail/bad-match.rs [new file with mode: 0644]
src/test/parse-fail/bad-name.rs [new file with mode: 0644]
src/test/parse-fail/better-expected.rs [new file with mode: 0644]
src/test/parse-fail/bind-struct-early-modifiers.rs [new file with mode: 0644]
src/test/parse-fail/byte-literals.rs [new file with mode: 0644]
src/test/parse-fail/byte-string-literals.rs [new file with mode: 0644]
src/test/parse-fail/circular_modules_hello.rs [new file with mode: 0644]
src/test/parse-fail/circular_modules_main.rs [new file with mode: 0644]
src/test/parse-fail/class-implements-bad-trait.rs [new file with mode: 0644]
src/test/parse-fail/column-offset-1-based.rs [new file with mode: 0644]
src/test/parse-fail/duplicate-visibility.rs [new file with mode: 0644]
src/test/parse-fail/empty-impl-semicolon.rs [new file with mode: 0644]
src/test/parse-fail/extern-expected-fn-or-brace.rs [new file with mode: 0644]
src/test/parse-fail/extern-foreign-crate.rs [new file with mode: 0644]
src/test/parse-fail/extern-no-fn.rs [new file with mode: 0644]
src/test/parse-fail/import-from-path.rs [new file with mode: 0644]
src/test/parse-fail/import-from-rename.rs [new file with mode: 0644]
src/test/parse-fail/import-glob-path.rs [new file with mode: 0644]
src/test/parse-fail/import-glob-rename.rs [new file with mode: 0644]
src/test/parse-fail/issue-10392-2.rs [new file with mode: 0644]
src/test/parse-fail/issue-10392.rs [new file with mode: 0644]
src/test/parse-fail/issue-10636-1.rs [new file with mode: 0644]
src/test/parse-fail/issue-10636-2.rs [new file with mode: 0644]
src/test/parse-fail/issue-14303-enum.rs [new file with mode: 0644]
src/test/parse-fail/issue-14303-fn-def.rs [new file with mode: 0644]
src/test/parse-fail/issue-14303-fncall.rs [new file with mode: 0644]
src/test/parse-fail/issue-14303-impl.rs [new file with mode: 0644]
src/test/parse-fail/issue-14303-path.rs [new file with mode: 0644]
src/test/parse-fail/issue-14303-struct.rs [new file with mode: 0644]
src/test/parse-fail/issue-14303-trait.rs [new file with mode: 0644]
src/test/parse-fail/issue-15914.rs [new file with mode: 0644]
src/test/parse-fail/issue-1655.rs [new file with mode: 0644]
src/test/parse-fail/issue-17904.rs [new file with mode: 0644]
src/test/parse-fail/issue-1802-1.rs [new file with mode: 0644]
src/test/parse-fail/issue-19096.rs [new file with mode: 0644]
src/test/parse-fail/issue-19398.rs [new file with mode: 0644]
src/test/parse-fail/issue-20711-2.rs [new file with mode: 0644]
src/test/parse-fail/issue-20711.rs [new file with mode: 0644]
src/test/parse-fail/issue-21153.rs [new file with mode: 0644]
src/test/parse-fail/issue-2354-1.rs [new file with mode: 0644]
src/test/parse-fail/issue-2354.rs [new file with mode: 0644]
src/test/parse-fail/issue-3036.rs [new file with mode: 0644]
src/test/parse-fail/issue-5806.rs [new file with mode: 0644]
src/test/parse-fail/issue-6610.rs [new file with mode: 0644]
src/test/parse-fail/keyword-abstract.rs [new file with mode: 0644]
src/test/parse-fail/keyword-do-as-identifier.rs [new file with mode: 0644]
src/test/parse-fail/keyword-final.rs [new file with mode: 0644]
src/test/parse-fail/keyword-mut-as-identifier.rs [new file with mode: 0644]
src/test/parse-fail/keyword-override.rs [new file with mode: 0644]
src/test/parse-fail/keyword-priv-as-identifier.rs [new file with mode: 0644]
src/test/parse-fail/keyword-ref-as-identifier.rs [new file with mode: 0644]
src/test/parse-fail/keyword-typeof.rs [new file with mode: 0644]
src/test/parse-fail/lex-bad-char-literals.rs [new file with mode: 0644]
src/test/parse-fail/lex-bad-token.rs [new file with mode: 0644]
src/test/parse-fail/macro-attribute.rs [new file with mode: 0644]
src/test/parse-fail/macro-bad-delimiter-ident.rs [new file with mode: 0644]
src/test/parse-fail/macro-keyword.rs [new file with mode: 0644]
src/test/parse-fail/macro-mismatched-delim-brace-paren.rs [new file with mode: 0644]
src/test/parse-fail/macro-mismatched-delim-paren-brace.rs [new file with mode: 0644]
src/test/parse-fail/macros-no-semicolon.rs [new file with mode: 0644]
src/test/parse-fail/match-arrows-block-then-binop.rs [new file with mode: 0644]
src/test/parse-fail/match-vec-invalid.rs [new file with mode: 0644]
src/test/parse-fail/mod_file_disambig.rs [new file with mode: 0644]
src/test/parse-fail/mod_file_not_exist.rs [new file with mode: 0644]
src/test/parse-fail/mod_file_not_owning.rs [new file with mode: 0644]
src/test/parse-fail/mod_file_with_path_attr.rs [new file with mode: 0644]
src/test/parse-fail/multiline-comment-line-tracking.rs [new file with mode: 0644]
src/test/parse-fail/multitrait.rs [new file with mode: 0644]
src/test/parse-fail/mut-patterns.rs [new file with mode: 0644]
src/test/parse-fail/new-unicode-escapes-1.rs [new file with mode: 0644]
src/test/parse-fail/new-unicode-escapes-2.rs [new file with mode: 0644]
src/test/parse-fail/new-unicode-escapes-3.rs [new file with mode: 0644]
src/test/parse-fail/new-unicode-escapes-4.rs [new file with mode: 0644]
src/test/parse-fail/not-a-pred.rs [new file with mode: 0644]
src/test/parse-fail/omitted-arg-in-item-fn.rs [new file with mode: 0644]
src/test/parse-fail/paamayim-nekudotayim.rs [new file with mode: 0644]
src/test/parse-fail/parenthesized-box-expr-message.rs [new file with mode: 0644]
src/test/parse-fail/pat-range-bad-dots.rs [new file with mode: 0644]
src/test/parse-fail/pat-ref-enum.rs [new file with mode: 0644]
src/test/parse-fail/range-3.rs [new file with mode: 0644]
src/test/parse-fail/range-4.rs [new file with mode: 0644]
src/test/parse-fail/raw-byte-string-eof.rs [new file with mode: 0644]
src/test/parse-fail/raw-byte-string-literals.rs [new file with mode: 0644]
src/test/parse-fail/raw-str-delim.rs [new file with mode: 0644]
src/test/parse-fail/raw-str-unbalanced.rs [new file with mode: 0644]
src/test/parse-fail/raw-str-unterminated.rs [new file with mode: 0644]
src/test/parse-fail/regions-infer-paramd-method.rs [new file with mode: 0644]
src/test/parse-fail/regions-out-of-scope-slice.rs [new file with mode: 0644]
src/test/parse-fail/regions-trait-2.rs [new file with mode: 0644]
src/test/parse-fail/regions-trait-3.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-closure-lifetime.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-enum-newtype.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-extern-const.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-field-let.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-field-semicolon.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-fixed-vec.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-fn-pure.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-fn-sigil.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-larrow-init.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-larrow-move.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-mode.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-mut-vec-expr.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-mut-vec-ty.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-ptr-lifetime.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-record.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-static-fn.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-uniq-mut-expr.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-uniq-mut-ty.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-with-1.rs [new file with mode: 0644]
src/test/parse-fail/removed-syntax-with-2.rs [new file with mode: 0644]
src/test/parse-fail/reserved-be.rs [new file with mode: 0644]
src/test/parse-fail/struct-literal-in-for.rs [new file with mode: 0644]
src/test/parse-fail/struct-literal-in-if.rs [new file with mode: 0644]
src/test/parse-fail/struct-literal-in-match-discriminant.rs [new file with mode: 0644]
src/test/parse-fail/struct-literal-in-while.rs [new file with mode: 0644]
src/test/parse-fail/struct-no-fields-enumlike.rs [new file with mode: 0644]
src/test/parse-fail/struct-no-fields.rs [new file with mode: 0644]
src/test/parse-fail/trait-keyword.rs [new file with mode: 0644]
src/test/parse-fail/unbalanced-doublequote.rs [new file with mode: 0644]
src/test/parse-fail/unboxed-closure-sugar-used-on-struct-3.rs [new file with mode: 0644]
src/test/parse-fail/unsized.rs [new file with mode: 0644]
src/test/parse-fail/use-as-where-use-ends-with-mod-sep.rs [new file with mode: 0644]
src/test/parse-fail/use-ends-with-mod-sep.rs [new file with mode: 0644]
src/test/parse-fail/use-mod-4.rs [new file with mode: 0644]
src/test/parse-fail/variadic-ffi-1.rs [new file with mode: 0644]
src/test/parse-fail/variadic-ffi-3.rs [new file with mode: 0644]
src/test/parse-fail/variadic-ffi-4.rs [new file with mode: 0644]
src/test/pretty/issue-4264.pp
src/test/run-fail/bug-2470-bounds-check-overflow-3.rs
src/test/run-make/alloc-extern-crates/Makefile [new file with mode: 0644]
src/test/run-make/alloc-extern-crates/fakealloc.rs [new file with mode: 0644]
src/test/run-make/c-dynamic-dylib/cfoo.c
src/test/run-make/c-dynamic-rlib/cfoo.c
src/test/run-make/c-link-to-rust-dylib/bar.c
src/test/run-make/c-link-to-rust-staticlib/bar.c
src/test/run-make/c-static-dylib/cfoo.c
src/test/run-make/c-static-rlib/cfoo.c
src/test/run-make/cannot-read-embedded-idents/create_and_compile.rs
src/test/run-make/error-found-staticlib-instead-crate/Makefile [new file with mode: 0644]
src/test/run-make/error-found-staticlib-instead-crate/bar.rs [new file with mode: 0644]
src/test/run-make/error-found-staticlib-instead-crate/foo.rs [new file with mode: 0644]
src/test/run-make/extern-fn-generic/test.c
src/test/run-make/extern-fn-mangle/test.c
src/test/run-make/extern-fn-with-packed-struct/test.c
src/test/run-make/extern-fn-with-union/test.c
src/test/run-make/interdependent-c-libraries/bar.c
src/test/run-make/interdependent-c-libraries/foo.c
src/test/run-make/issue-12446/foo.c
src/test/run-make/issue-15460/foo.c
src/test/run-make/issue-19371/foo.rs
src/test/run-make/link-path-order/correct.c
src/test/run-make/link-path-order/wrong.c
src/test/run-make/linkage-attr-on-static/foo.c
src/test/run-make/lto-smoke-c/bar.c
src/test/run-make/manual-link/bar.c
src/test/run-make/manual-link/foo.c
src/test/run-make/mismatching-target-triples/bar.rs
src/test/run-make/mismatching-target-triples/foo.rs
src/test/run-make/no-duplicate-libs/bar.c
src/test/run-make/no-duplicate-libs/bar.rs
src/test/run-make/no-duplicate-libs/foo.c
src/test/run-make/no-duplicate-libs/foo.rs
src/test/run-make/pretty-expanded-hygiene/input.pp.rs
src/test/run-make/pretty-expanded-hygiene/input.rs
src/test/run-make/rustdoc-assoc-types/Makefile [new file with mode: 0644]
src/test/run-make/rustdoc-assoc-types/lib.rs [new file with mode: 0644]
src/test/run-make/rustdoc-extern-method/Makefile [new file with mode: 0644]
src/test/run-make/rustdoc-extern-method/bar.rs [new file with mode: 0644]
src/test/run-make/rustdoc-extern-method/foo.rs [new file with mode: 0644]
src/test/run-make/rustdoc-ffi/Makefile [new file with mode: 0644]
src/test/run-make/rustdoc-ffi/lib.rs [new file with mode: 0644]
src/test/run-make/rustdoc-ffi/user.rs [new file with mode: 0644]
src/test/run-make/rustdoc-hidden-line/foo.rs
src/test/run-make/rustdoc-negative-impl/foo.rs
src/test/run-make/rustdoc-where/foo.rs
src/test/run-make/save-analysis/foo.rs
src/test/run-make/simd-ffi/simd.rs
src/test/run-make/target-specs/foo.rs
src/test/run-make/unicode-input/multiple_files.rs
src/test/run-make/unicode-input/span_length.rs
src/test/run-make/use-extern-for-plugins/Makefile [new file with mode: 0644]
src/test/run-make/use-extern-for-plugins/bar.rs [new file with mode: 0644]
src/test/run-make/use-extern-for-plugins/baz.rs [new file with mode: 0644]
src/test/run-make/use-extern-for-plugins/foo.rs [new file with mode: 0644]
src/test/run-pass-fulldeps/compiler-calls.rs [new file with mode: 0644]
src/test/run-pass-fulldeps/issue_16723_multiple_items_syntax_ext.rs
src/test/run-pass-fulldeps/lint-group-plugin.rs
src/test/run-pass-fulldeps/lint-plugin-cmdline-allow.rs
src/test/run-pass-fulldeps/lint-plugin.rs
src/test/run-pass-fulldeps/macro-crate-does-hygiene-work.rs
src/test/run-pass-fulldeps/macro-crate-outlive-expansion-phase.rs
src/test/run-pass-fulldeps/macro-crate.rs
src/test/run-pass-fulldeps/plugin-args-1.rs
src/test/run-pass-fulldeps/plugin-args-2.rs
src/test/run-pass-fulldeps/plugin-args-3.rs
src/test/run-pass-fulldeps/plugin-args-4.rs [deleted file]
src/test/run-pass-fulldeps/plugin-link-does-resolve.rs [deleted file]
src/test/run-pass-fulldeps/plugin-plus-extern-crate.rs [new file with mode: 0644]
src/test/run-pass-fulldeps/roman-numerals-macro.rs
src/test/run-pass-fulldeps/syntax-extension-with-dll-deps.rs
src/test/run-pass/assignability-trait.rs
src/test/run-pass/associated-types-conditional-dispatch.rs
src/test/run-pass/associated-types-duplicate-binding-in-env-hrtb.rs [new file with mode: 0644]
src/test/run-pass/associated-types-duplicate-binding-in-env.rs [new file with mode: 0644]
src/test/run-pass/auto-encode.rs
src/test/run-pass/backtrace.rs
src/test/run-pass/bare-fn-implements-fn-mut.rs
src/test/run-pass/block-fn-coerce.rs
src/test/run-pass/bool.rs
src/test/run-pass/borrowck-binding-mutbl.rs
src/test/run-pass/borrowck-closures-two-imm.rs
src/test/run-pass/borrowck-move-by-capture-ok.rs
src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs
src/test/run-pass/borrowed-ptr-pattern-2.rs
src/test/run-pass/capture-clauses-unboxed-closures.rs
src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs
src/test/run-pass/cleanup-shortcircuit.rs
src/test/run-pass/closure-inference2.rs
src/test/run-pass/coerce-overloaded-autoderef.rs
src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs
src/test/run-pass/coerce-reborrow-mut-vec-arg.rs
src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs
src/test/run-pass/copy-out-of-array-1.rs [new file with mode: 0644]
src/test/run-pass/derive-no-std.rs [new file with mode: 0644]
src/test/run-pass/deriving-encodable-decodable-box.rs
src/test/run-pass/deriving-encodable-decodable-cell-refcell.rs
src/test/run-pass/deriving-encodable-decodable.rs
src/test/run-pass/destructure-array-1.rs [new file with mode: 0644]
src/test/run-pass/empty-tag.rs
src/test/run-pass/fn-pattern-expected-type.rs
src/test/run-pass/fn-type-infer.rs
src/test/run-pass/for-loop-no-std.rs [new file with mode: 0644]
src/test/run-pass/foreach-external-iterators-break.rs
src/test/run-pass/foreach-external-iterators-nested.rs
src/test/run-pass/foreach-external-iterators.rs
src/test/run-pass/format-no-std.rs [new file with mode: 0644]
src/test/run-pass/getopts_ref.rs
src/test/run-pass/hashmap-memory.rs
src/test/run-pass/hrtb-precedence-of-plus.rs
src/test/run-pass/hrtb-unboxed-closure-trait.rs
src/test/run-pass/if-let.rs
src/test/run-pass/ifmt.rs
src/test/run-pass/inconsistent-lifetime-mismatch.rs
src/test/run-pass/issue-10626.rs
src/test/run-pass/issue-10683.rs
src/test/run-pass/issue-10718.rs
src/test/run-pass/issue-11869.rs
src/test/run-pass/issue-13027.rs
src/test/run-pass/issue-13304.rs
src/test/run-pass/issue-13323.rs
src/test/run-pass/issue-13434.rs
src/test/run-pass/issue-14021.rs
src/test/run-pass/issue-14456.rs
src/test/run-pass/issue-1460.rs
src/test/run-pass/issue-14919.rs
src/test/run-pass/issue-14936.rs
src/test/run-pass/issue-14940.rs
src/test/run-pass/issue-15149.rs
src/test/run-pass/issue-15571.rs
src/test/run-pass/issue-16256.rs
src/test/run-pass/issue-16560.rs
src/test/run-pass/issue-16668.rs
src/test/run-pass/issue-16774.rs
src/test/run-pass/issue-16783.rs
src/test/run-pass/issue-17734.rs
src/test/run-pass/issue-17816.rs
src/test/run-pass/issue-17897.rs
src/test/run-pass/issue-18188.rs
src/test/run-pass/issue-18352.rs
src/test/run-pass/issue-18652.rs
src/test/run-pass/issue-18661.rs
src/test/run-pass/issue-18685.rs
src/test/run-pass/issue-18711.rs
src/test/run-pass/issue-19135.rs
src/test/run-pass/issue-2074.rs
src/test/run-pass/issue-21306.rs
src/test/run-pass/issue-21891.rs [new file with mode: 0644]
src/test/run-pass/issue-3052.rs
src/test/run-pass/issue-3429.rs
src/test/run-pass/issue-3559.rs
src/test/run-pass/issue-3563-3.rs
src/test/run-pass/issue-4541.rs
src/test/run-pass/issue-5239-2.rs
src/test/run-pass/issue-5550.rs
src/test/run-pass/issue-6157.rs
src/test/run-pass/issue-7660.rs
src/test/run-pass/issue-868.rs
src/test/run-pass/issue-8898.rs
src/test/run-pass/issue-9129.rs
src/test/run-pass/issue-9259.rs
src/test/run-pass/issue-9382.rs
src/test/run-pass/istr.rs
src/test/run-pass/lambda-infer-unresolved.rs
src/test/run-pass/lang-item-public.rs
src/test/run-pass/last-use-in-cap-clause.rs
src/test/run-pass/logging-separate-lines.rs
src/test/run-pass/loop-label-shadowing.rs
src/test/run-pass/match-str.rs
src/test/run-pass/method-mut-self-modifies-mut-slice-lvalue.rs
src/test/run-pass/move-out-of-field.rs
src/test/run-pass/mut-function-arguments.rs
src/test/run-pass/mut-in-ident-patterns.rs
src/test/run-pass/new-unicode-escapes.rs
src/test/run-pass/no-std-xcrate2.rs
src/test/run-pass/order-drop-with-match.rs
src/test/run-pass/out-of-stack-new-thread-no-split.rs
src/test/run-pass/out-of-stack-no-split.rs
src/test/run-pass/out-of-stack.rs
src/test/run-pass/overloaded-autoderef.rs
src/test/run-pass/overloaded-deref-count.rs
src/test/run-pass/overloaded-deref.rs
src/test/run-pass/overloaded-index-autoderef.rs
src/test/run-pass/overloaded-index.rs
src/test/run-pass/pattern-in-closure.rs
src/test/run-pass/process-remove-from-env.rs
src/test/run-pass/process-spawn-with-unicode-params.rs
src/test/run-pass/range.rs
src/test/run-pass/ranges-precedence.rs
src/test/run-pass/rcvr-borrowed-to-slice.rs
src/test/run-pass/realloc-16687.rs
src/test/run-pass/regions-borrow-evec-uniq.rs
src/test/run-pass/regions-copy-closure.rs
src/test/run-pass/regions-dependent-autoslice.rs
src/test/run-pass/regions-infer-borrow-scope-view.rs
src/test/run-pass/regions-lifetime-nonfree-late-bound.rs
src/test/run-pass/regions-mock-tcx.rs
src/test/run-pass/regions-static-closure.rs
src/test/run-pass/repeated-vector-syntax.rs
src/test/run-pass/return-from-closure.rs
src/test/run-pass/running-with-no-runtime.rs
src/test/run-pass/rust-log-filter.rs
src/test/run-pass/segfault-no-out-of-stack.rs
src/test/run-pass/sendfn-spawn-with-fn-arg.rs
src/test/run-pass/signal-exit-status.rs
src/test/run-pass/sigpipe-should-be-ignored.rs
src/test/run-pass/slice-2.rs
src/test/run-pass/slice.rs
src/test/run-pass/small-enums-with-fields.rs
src/test/run-pass/smallest-hello-world.rs
src/test/run-pass/swap-2.rs
src/test/run-pass/tempfile.rs
src/test/run-pass/trait-bounds-in-arc.rs
src/test/run-pass/traits-issue-22019.rs [new file with mode: 0644]
src/test/run-pass/type-id-higher-rank.rs
src/test/run-pass/typeck_type_placeholder_1.rs
src/test/run-pass/unboxed-closures-all-traits.rs
src/test/run-pass/unboxed-closures-boxed.rs
src/test/run-pass/unboxed-closures-by-ref.rs
src/test/run-pass/unboxed-closures-direct-sugary-call.rs
src/test/run-pass/unboxed-closures-drop.rs
src/test/run-pass/unboxed-closures-generic.rs
src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-bound.rs
src/test/run-pass/unboxed-closures-infer-argument-types-from-expected-object-type.rs
src/test/run-pass/unboxed-closures-infer-argument-types-with-bound-regions-from-expected-bound.rs
src/test/run-pass/unboxed-closures-monomorphization.rs
src/test/run-pass/unboxed-closures-move-mutable.rs
src/test/run-pass/unboxed-closures-prelude.rs
src/test/run-pass/unboxed-closures-simple.rs
src/test/run-pass/unboxed-closures-single-word-env.rs
src/test/run-pass/unboxed-closures-static-call-fn-once.rs
src/test/run-pass/unboxed-closures-unique-type-id.rs
src/test/run-pass/unit-like-struct-drop-run.rs
src/test/run-pass/unused-move-capture.rs
src/test/run-pass/use.rs
src/test/run-pass/vec-concat.rs
src/test/run-pass/vec-macro-no-std.rs
src/test/run-pass/vector-sort-panic-safe.rs
src/test/run-pass/wait-forked-but-failed-child.rs
src/test/run-pass/weird-exprs.rs
src/test/run-pass/where-clauses-unboxed-closures.rs
src/test/run-pass/where-for-self.rs [new file with mode: 0644]

index 63c5742a540d404c0502a38326fceb06e47da22a..a760155bbd91aeeee3a961599f7a7cf86c4b331a 100644 (file)
@@ -59,6 +59,9 @@
 #   * check-stage$(stage)-$(crate) - Test a crate in a specific stage
 #   * check-stage$(stage)-{rpass,rfail,cfail,rmake,...} - Run tests in src/test/
 #   * check-stage1-T-$(target)-H-$(host) - Run cross-compiled-tests
+#   * tidy-basic - show file / line stats
+#   * tidy-errors - show the highest rustc error code
+#   * tidy-features - show the status of language and lib features
 #
 # Then mix in some of these environment variables to harness the
 # ultimate power of The Rust Build System.
index 2127f2c656d03bf8797bee7547d12850efac865a..a80dafcf04779693cc41b85b3cc4fc1d3044d9aa 100755 (executable)
--- a/configure
+++ b/configure
@@ -653,9 +653,7 @@ probe CFG_GRUN             grun
 probe CFG_FLEX             flex
 probe CFG_BISON            bison
 probe CFG_PANDOC           pandoc
-probe CFG_PDFLATEX         pdflatex
 probe CFG_XELATEX          xelatex
-probe CFG_LUALATEX         lualatex
 probe CFG_GDB              gdb
 probe CFG_LLDB             lldb
 
index 3d8b27a408a27edd808ece57785b33e47940b6e7..49056afa045abb46f7e970696fd03f6ec1ef0b24 100644 (file)
@@ -18,10 +18,15 @@ Display the help message
 \fB\-\-cfg\fR SPEC
 Configure the compilation environment
 .TP
-\fB\-L\fR PATH
-Add a directory to the library search path
-.TP
-\fB\-l\fR NAME[:KIND]
+\fB\-L\fR [KIND=]PATH
+Add a directory to the library search path. The optional KIND can be one of:
+    dependency = only lookup transitive dependencies here
+    crate = only lookup local `extern crate` directives here
+    native = only lookup native libraries here
+    framework = only look for OSX frameworks here
+    all = look for anything here (the default)
+.TP
+\fB\-l\fR [KIND=]NAME
 Link the generated crate(s) to the specified native library NAME. The optional
 KIND can be one of, static, dylib, or framework. If omitted, dylib is assumed.
 .TP
index 8af47700f25dc4e550fa445b5820d3e12d232004..71b253379aa01961e67032518d94c0cc4af70a06 100644 (file)
@@ -85,27 +85,16 @@ else
 HTML_DEPS :=
 endif
 
-# Check for the various external utilities for the EPUB/PDF docs:
-
-ifeq ($(CFG_LUALATEX),)
-  $(info cfg: no lualatex found, deferring to xelatex)
-  ifeq ($(CFG_XELATEX),)
-    $(info cfg: no xelatex found, deferring to pdflatex)
-    ifeq ($(CFG_PDFLATEX),)
-      $(info cfg: no pdflatex found, disabling LaTeX docs)
-      NO_PDF_DOCS = 1
-       else
-      CFG_LATEX := $(CFG_PDFLATEX)
-    endif
-  else
+# Check for xelatex
+
+ifeq ($(CFG_XELATEX),)
     CFG_LATEX := $(CFG_XELATEX)
     XELATEX = 1
-  endif
-else
-  CFG_LATEX := $(CFG_LUALATEX)
+  else
+    $(info cfg: no xelatex found, disabling LaTeX docs)
+    NO_PDF_DOCS = 1
 endif
 
-
 ifeq ($(CFG_PANDOC),)
 $(info cfg: no pandoc found, omitting PDF and EPUB docs)
 ONLY_HTML_DOCS = 1
index 0e52f168f59ed2072cb87c2eddfee295cb821685..a6b201a2b7bdfc7bd1a7c259bc7068ae6053fe90 100644 (file)
@@ -72,6 +72,7 @@ endif
 # numbers and dots here
 CFG_VERSION_WIN = $(CFG_RELEASE_NUM)
 
+CFG_INFO := $(info cfg: version $(CFG_VERSION))
 
 ######################################################################
 # More configuration
@@ -179,6 +180,7 @@ endif
 
 ifndef CFG_DISABLE_VALGRIND_RPASS
   $(info cfg: enabling valgrind run-pass tests (CFG_ENABLE_VALGRIND_RPASS))
+  $(info cfg: valgrind-rpass command set to $(CFG_VALGRIND))
   CFG_VALGRIND_RPASS :=$(CFG_VALGRIND)
 else
   CFG_VALGRIND_RPASS :=
index e28f56fffe41b3d547f7c82ed3f1b86ef2b18725..d8d77db1e0276fbe17909049022dfa91c5ac80b1 100644 (file)
@@ -162,7 +162,8 @@ $(foreach file,$(wildcard $(S)src/doc/trpl/*.md), \
 ######################################################################
 
 # The main testing target. Tests lots of stuff.
-check: cleantmptestlogs cleantestlibs check-notidy tidy
+check: cleantmptestlogs cleantestlibs all check-stage2 tidy
+       $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log
 
 # As above but don't bother running tidy.
 check-notidy: cleantmptestlogs cleantestlibs all check-stage2
@@ -235,57 +236,24 @@ cleantestlibs:
 ######################################################################
 
 ifdef CFG_NOTIDY
+.PHONY: tidy
 tidy:
 else
 
-ALL_CS := $(wildcard $(S)src/rt/*.cpp \
-                     $(S)src/rt/*/*.cpp \
-                     $(S)src/rt/*/*/*.cpp \
-                     $(S)src/rustllvm/*.cpp)
-ALL_CS := $(filter-out $(S)src/rt/miniz.cpp \
-                      $(wildcard $(S)src/rt/hoedown/src/*.c) \
-                      $(wildcard $(S)src/rt/hoedown/bin/*.c) \
-       ,$(ALL_CS))
-ALL_HS := $(wildcard $(S)src/rt/*.h \
-                     $(S)src/rt/*/*.h \
-                     $(S)src/rt/*/*/*.h \
-                     $(S)src/rustllvm/*.h)
-ALL_HS := $(filter-out $(S)src/rt/valgrind/valgrind.h \
-                       $(S)src/rt/valgrind/memcheck.h \
-                       $(S)src/rt/msvc/typeof.h \
-                       $(S)src/rt/msvc/stdint.h \
-                       $(S)src/rt/msvc/inttypes.h \
-                      $(wildcard $(S)src/rt/hoedown/src/*.h) \
-                      $(wildcard $(S)src/rt/hoedown/bin/*.h) \
-       ,$(ALL_HS))
-
 # Run the tidy script in multiple parts to avoid huge 'echo' commands
-tidy:
+.PHONY: tidy
+tidy: tidy-basic tidy-binaries tidy-errors tidy-features
+
+endif
+
+.PHONY: tidy-basic
+tidy-basic:
                @$(call E, check: formatting)
-               $(Q)find $(S)src -name '*.r[sc]' \
-                   -and -not -regex '^$(S)src/jemalloc.*' \
-                   -and -not -regex '^$(S)src/libuv.*' \
-                   -and -not -regex '^$(S)src/llvm.*' \
-                   -and -not -regex '^$(S)src/gyp.*' \
-                   -and -not -regex '^$(S)src/libbacktrace.*' \
-                   -print0 \
-               | xargs -0 -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
-               $(Q)find $(S)src/etc -name '*.py' \
-               | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
-               $(Q)find $(S)src/doc -name '*.js' \
-               | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
-               $(Q)find $(S)src/etc -name '*.sh' \
-               | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
-               $(Q)find $(S)src/etc -name '*.pl' \
-               | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
-               $(Q)find $(S)src/etc -name '*.c' \
-               | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
-               $(Q)find $(S)src/etc -name '*.h' \
-               | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
-               $(Q)echo $(ALL_CS) \
-               | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
-               $(Q)echo $(ALL_HS) \
-               | xargs -n 10 $(CFG_PYTHON) $(S)src/etc/tidy.py
+               $(Q) $(CFG_PYTHON) $(S)src/etc/tidy.py $(S)src/
+
+.PHONY: tidy-binaries
+tidy-binaries:
+               @$(call E, check: binaries)
                $(Q)find $(S)src -type f -perm +a+x \
                    -not -name '*.rs' -and -not -name '*.py' \
                    -and -not -name '*.sh' \
@@ -300,11 +268,16 @@ tidy:
                | grep '^$(S)src/libbacktrace' -v \
                | grep '^$(S)src/rust-installer' -v \
                | xargs $(CFG_PYTHON) $(S)src/etc/check-binaries.py
-               $(Q) $(CFG_PYTHON) $(S)src/etc/errorck.py $(S)src/
-               $(Q) $(CFG_PYTHON) $(S)src/etc/featureck.py $(S)src/
 
+.PHONY: tidy-errors
+tidy-errors:
+               @$(call E, check: extended errors)
+               $(Q) $(CFG_PYTHON) $(S)src/etc/errorck.py $(S)src/
 
-endif
+.PHONY: tidy-features
+tidy-features:
+               @$(call E, check: feature sanity)
+               $(Q) $(CFG_PYTHON) $(S)src/etc/featureck.py $(S)src/
 
 
 ######################################################################
@@ -479,6 +452,7 @@ RPASS_FULL_RS := $(wildcard $(S)src/test/run-pass-fulldeps/*.rs)
 CFAIL_FULL_RS := $(wildcard $(S)src/test/compile-fail-fulldeps/*.rs)
 RFAIL_RS := $(wildcard $(S)src/test/run-fail/*.rs)
 CFAIL_RS := $(wildcard $(S)src/test/compile-fail/*.rs)
+PFAIL_RS := $(wildcard $(S)src/test/parse-fail/*.rs)
 BENCH_RS := $(wildcard $(S)src/test/bench/*.rs)
 PRETTY_RS := $(wildcard $(S)src/test/pretty/*.rs)
 DEBUGINFO_GDB_RS := $(wildcard $(S)src/test/debuginfo/*.rs)
@@ -495,7 +469,7 @@ RPASS_VALGRIND_TESTS := $(RPASS_VALGRIND_RS)
 RPASS_FULL_TESTS := $(RPASS_FULL_RS)
 CFAIL_FULL_TESTS := $(CFAIL_FULL_RS)
 RFAIL_TESTS := $(RFAIL_RS)
-CFAIL_TESTS := $(CFAIL_RS)
+CFAIL_TESTS := $(CFAIL_RS) $(PFAIL_RS)
 BENCH_TESTS := $(BENCH_RS)
 PERF_TESTS := $(PERF_RS)
 PRETTY_TESTS := $(PRETTY_RS)
@@ -639,7 +613,6 @@ CTEST_COMMON_ARGS$(1)-T-$(2)-H-$(3) := \
 
 ifdef CFG_VALGRIND_RPASS
 ifdef GOOD_VALGRIND_$(2)
-$(info cfg: valgrind-path set to $(CFG_VALGRIND_RPASS))
 CTEST_COMMON_ARGS$(1)-T-$(2)-H-$(3) += --valgrind-path "$(CFG_VALGRIND_RPASS)"
 endif
 endif
index 07e92c704d86f9fb854660d24378c27026fac86f..e6d2a691cf5630467f1edf4aef3b12b756be7eb2 100644 (file)
@@ -97,28 +97,31 @@ pub fn parse_config(args: Vec<String> ) -> Config {
     assert!(!args.is_empty());
     let argv0 = args[0].clone();
     let args_ = args.tail();
-    if args[1].as_slice() == "-h" || args[1].as_slice() == "--help" {
+    if args[1] == "-h" || args[1] == "--help" {
         let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
-        println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
+        println!("{}", getopts::usage(&message, &groups));
         println!("");
         panic!()
     }
 
     let matches =
-        &match getopts::getopts(args_.as_slice(), groups.as_slice()) {
+        &match getopts::getopts(args_, &groups) {
           Ok(m) => m,
           Err(f) => panic!("{:?}", f)
         };
 
     if matches.opt_present("h") || matches.opt_present("help") {
         let message = format!("Usage: {} [OPTIONS]  [TESTNAME...]", argv0);
-        println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
+        println!("{}", getopts::usage(&message, &groups));
         println!("");
         panic!()
     }
 
     fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
-        Path::new(m.opt_str(nm).unwrap())
+        match m.opt_str(nm) {
+            Some(s) => Path::new(s),
+            None => panic!("no option (=path) found for {}", nm),
+        }
     }
 
     let filter = if !matches.free.is_empty() {
@@ -156,9 +159,9 @@ fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
         adb_test_dir: opt_str2(matches.opt_str("adb-test-dir")),
         adb_device_status:
             "arm-linux-androideabi" ==
-                opt_str2(matches.opt_str("target")).as_slice() &&
+                opt_str2(matches.opt_str("target")) &&
             "(none)" !=
-                opt_str2(matches.opt_str("adb-test-dir")).as_slice() &&
+                opt_str2(matches.opt_str("adb-test-dir")) &&
             !opt_str2(matches.opt_str("adb-test-dir")).is_empty(),
         lldb_python_dir: matches.opt_str("lldb-python-dir"),
         verbose: matches.opt_present("verbose"),
@@ -201,7 +204,7 @@ pub fn log_config(config: &Config) {
 pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
     match *maybestr {
         None => "(none)",
-        Some(ref s) => s.as_slice(),
+        Some(ref s) => s,
     }
 }
 
@@ -213,7 +216,7 @@ pub fn opt_str2(maybestr: Option<String>) -> String {
 }
 
 pub fn run_tests(config: &Config) {
-    if config.target.as_slice() == "arm-linux-androideabi" {
+    if config.target == "arm-linux-androideabi" {
         match config.mode {
             DebugInfoGdb => {
                 println!("arm-linux-androideabi debug-info \
@@ -306,13 +309,13 @@ pub fn is_test(config: &Config, testfile: &Path) -> bool {
     let mut valid = false;
 
     for ext in &valid_extensions {
-        if name.ends_with(ext.as_slice()) {
+        if name.ends_with(ext) {
             valid = true;
         }
     }
 
     for pre in &invalid_prefixes {
-        if name.starts_with(pre.as_slice()) {
+        if name.starts_with(pre) {
             valid = false;
         }
     }
@@ -359,7 +362,7 @@ pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::Test
     let config = (*config).clone();
     // FIXME (#9639): This needs to handle non-utf8 paths
     let testfile = testfile.as_str().unwrap().to_string();
-    test::DynMetricFn(box move |mm: &mut test::MetricMap| {
+    test::DynMetricFn(box move |mm: &mut test::MetricMap| {
         runtest::run_metrics(config, testfile, mm)
     })
 }
index 40d4397916d3f2d38f53142ec778ff895ce6e704..d8faa53a2de647bc8c82262505ec266572e00daa 100644 (file)
@@ -44,7 +44,7 @@ pub fn load_errors(testfile: &Path) -> Vec<ExpectedError> {
     rdr.lines().enumerate().filter_map(|(line_no, ln)| {
         parse_expected(last_nonfollow_error,
                        line_no + 1,
-                       ln.unwrap().as_slice())
+                       &ln.unwrap())
             .map(|(which, error)| {
                 match which {
                     FollowPrevious(_) => {}
index 005ec013b8e6dd5acc3c638b2478a3944305ee39..c2539679643221332b31a32c6caba396dc6f3aee 100644 (file)
@@ -145,7 +145,7 @@ pub fn load_props(testfile: &Path) -> TestProps {
 
 pub fn is_test_ignored(config: &Config, testfile: &Path) -> bool {
     fn ignore_target(config: &Config) -> String {
-        format!("ignore-{}", util::get_os(config.target.as_slice()))
+        format!("ignore-{}", util::get_os(&config.target))
     }
     fn ignore_stage(config: &Config) -> String {
         format!("ignore-{}",
@@ -169,8 +169,8 @@ fn ignore_gdb(config: &Config, line: &str) -> bool {
                                           .expect("Malformed GDB version directive");
                     // Ignore if actual version is smaller the minimum required
                     // version
-                    gdb_version_to_int(actual_version.as_slice()) <
-                        gdb_version_to_int(min_version.as_slice())
+                    gdb_version_to_int(actual_version) <
+                        gdb_version_to_int(min_version)
                 } else {
                     false
                 }
@@ -197,8 +197,8 @@ fn ignore_lldb(config: &Config, line: &str) -> bool {
                                           .expect("Malformed lldb version directive");
                     // Ignore if actual version is smaller the minimum required
                     // version
-                    lldb_version_to_int(actual_version.as_slice()) <
-                        lldb_version_to_int(min_version.as_slice())
+                    lldb_version_to_int(actual_version) <
+                        lldb_version_to_int(min_version)
                 } else {
                     false
                 }
@@ -209,8 +209,8 @@ fn ignore_lldb(config: &Config, line: &str) -> bool {
 
     let val = iter_header(testfile, |ln| {
         !parse_name_directive(ln, "ignore-test") &&
-        !parse_name_directive(ln, ignore_target(config).as_slice()) &&
-        !parse_name_directive(ln, ignore_stage(config).as_slice()) &&
+        !parse_name_directive(ln, &ignore_target(config)) &&
+        !parse_name_directive(ln, &ignore_stage(config)) &&
         !(config.mode == common::Pretty && parse_name_directive(ln, "ignore-pretty")) &&
         !(config.target != config.host && parse_name_directive(ln, "ignore-cross-compile")) &&
         !ignore_gdb(config, ln) &&
@@ -294,7 +294,7 @@ fn parse_pretty_compare_only(line: &str) -> bool {
 fn parse_exec_env(line: &str) -> Option<(String, String)> {
     parse_name_value_directive(line, "exec-env").map(|nv| {
         // nv is either FOO or FOO=BAR
-        let mut strs: Vec<String> = nv.as_slice()
+        let mut strs: Vec<String> = nv
                                       .splitn(1, '=')
                                       .map(|s| s.to_string())
                                       .collect();
@@ -330,7 +330,7 @@ fn parse_name_directive(line: &str, directive: &str) -> bool {
 pub fn parse_name_value_directive(line: &str, directive: &str)
                                   -> Option<String> {
     let keycolon = format!("{}:", directive);
-    match line.find_str(keycolon.as_slice()) {
+    match line.find_str(&keycolon) {
         Some(colon) => {
             let value = line[(colon + keycolon.len()) .. line.len()].to_string();
             debug!("{}: {}", directive, value);
@@ -344,7 +344,7 @@ pub fn gdb_version_to_int(version_string: &str) -> int {
     let error_string = format!(
         "Encountered GDB version string with unexpected format: {}",
         version_string);
-    let error_string = error_string.as_slice();
+    let error_string = error_string;
 
     let components: Vec<&str> = version_string.trim().split('.').collect();
 
@@ -352,8 +352,8 @@ pub fn gdb_version_to_int(version_string: &str) -> int {
         panic!("{}", error_string);
     }
 
-    let major: int = components[0].parse().ok().expect(error_string);
-    let minor: int = components[1].parse().ok().expect(error_string);
+    let major: int = components[0].parse().ok().expect(&error_string);
+    let minor: int = components[1].parse().ok().expect(&error_string);
 
     return major * 1000 + minor;
 }
@@ -362,7 +362,7 @@ pub fn lldb_version_to_int(version_string: &str) -> int {
     let error_string = format!(
         "Encountered LLDB version string with unexpected format: {}",
         version_string);
-    let error_string = error_string.as_slice();
-    let major: int = version_string.parse().ok().expect(error_string);
+    let error_string = error_string;
+    let major: int = version_string.parse().ok().expect(&error_string);
     return major;
 }
index 4b0eea33d69b7a2176cd0c0c86d1480f43409c48..148a43e6c783196555b044efb3e4ec8e1791d4d6 100644 (file)
@@ -23,7 +23,7 @@ fn add_target_env(cmd: &mut Command, lib_path: &str, aux_path: Option<&str>) {
 
     // Add the new dylib search path var
     let var = DynamicLibrary::envvar();
-    let newpath = DynamicLibrary::create_path(path.as_slice());
+    let newpath = DynamicLibrary::create_path(&path);
     let newpath = String::from_utf8(newpath).unwrap();
     cmd.env(var.to_string(), newpath);
 }
index a8e644dba99d18a8552d1d359f272f5a96d54840..5a372fd7cdcb261f83898f29e0ace7a8a63738ab 100644 (file)
@@ -40,7 +40,7 @@
 use test::MetricMap;
 
 pub fn run(config: Config, testfile: String) {
-    match config.target.as_slice() {
+    match &*config.target {
 
         "arm-linux-androideabi" => {
             if !config.adb_device_status {
@@ -106,10 +106,10 @@ fn run_cfail_test(config: &Config, props: &TestProps, testfile: &Path) {
         }
         check_expected_errors(expected_errors, testfile, &proc_res);
     } else {
-        check_error_patterns(props, testfile, output_to_check.as_slice(), &proc_res);
+        check_error_patterns(props, testfile, &output_to_check, &proc_res);
     }
     check_no_compiler_crash(&proc_res);
-    check_forbid_output(props, output_to_check.as_slice(), &proc_res);
+    check_forbid_output(props, &output_to_check, &proc_res);
 }
 
 fn run_rfail_test(config: &Config, props: &TestProps, testfile: &Path) {
@@ -133,7 +133,7 @@ fn run_rfail_test(config: &Config, props: &TestProps, testfile: &Path) {
 
     let output_to_check = get_output(props, &proc_res);
     check_correct_failure_status(&proc_res);
-    check_error_patterns(props, testfile, output_to_check.as_slice(), &proc_res);
+    check_error_patterns(props, testfile, &output_to_check, &proc_res);
 }
 
 fn check_correct_failure_status(proc_res: &ProcRes) {
@@ -141,8 +141,8 @@ fn check_correct_failure_status(proc_res: &ProcRes) {
     static RUST_ERR: int = 101;
     if !proc_res.status.matches_exit_status(RUST_ERR) {
         fatal_proc_rec(
-            format!("failure produced the wrong error: {:?}",
-                    proc_res.status).as_slice(),
+            &format!("failure produced the wrong error: {:?}",
+                     proc_res.status),
             proc_res);
     }
 }
@@ -211,11 +211,10 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
                                     props,
                                     testfile,
                                     srcs[round].to_string(),
-                                    props.pretty_mode.as_slice());
+                                    &props.pretty_mode);
 
         if !proc_res.status.success() {
-            fatal_proc_rec(format!("pretty-printing failed in round {}",
-                                   round).as_slice(),
+            fatal_proc_rec(&format!("pretty-printing failed in round {}", round),
                           &proc_res);
         }
 
@@ -237,11 +236,11 @@ fn run_pretty_test(config: &Config, props: &TestProps, testfile: &Path) {
     if props.pp_exact.is_some() {
         // Now we have to care about line endings
         let cr = "\r".to_string();
-        actual = actual.replace(cr.as_slice(), "").to_string();
-        expected = expected.replace(cr.as_slice(), "").to_string();
+        actual = actual.replace(&cr, "").to_string();
+        expected = expected.replace(&cr, "").to_string();
     }
 
-    compare_source(expected.as_slice(), actual.as_slice());
+    compare_source(&expected, &actual);
 
     // If we're only making sure that the output matches then just stop here
     if props.pretty_compare_only { return; }
@@ -282,7 +281,7 @@ fn print_source(config: &Config,
                                      testfile,
                                      pretty_type.to_string()),
                         props.exec_env.clone(),
-                        config.compile_lib_path.as_slice(),
+                        &config.compile_lib_path,
                         Some(aux_dir.as_str().unwrap()),
                         Some(src))
     }
@@ -335,9 +334,9 @@ fn typecheck_source(config: &Config, props: &TestProps,
     fn make_typecheck_args(config: &Config, props: &TestProps, testfile: &Path) -> ProcArgs {
         let aux_dir = aux_output_dir_name(config, testfile);
         let target = if props.force_host {
-            config.host.as_slice()
+            &*config.host
         } else {
-            config.target.as_slice()
+            &*config.target
         };
         // FIXME (#9639): This needs to handle non-utf8 paths
         let mut args = vec!("-".to_string(),
@@ -382,7 +381,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
     let exe_file = make_exe_name(config, testfile);
 
     let debugger_run_result;
-    match config.target.as_slice() {
+    match &*config.target {
         "arm-linux-androideabi" => {
 
             cmds = cmds.replace("run", "continue").to_string();
@@ -397,12 +396,12 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
             debug!("script_str = {}", script_str);
             dump_output_file(config,
                              testfile,
-                             script_str.as_slice(),
+                             &script_str,
                              "debugger.script");
 
 
             procsrv::run("",
-                         config.adb_path.as_slice(),
+                         &config.adb_path,
                          None,
                          &[
                             "push".to_string(),
@@ -411,10 +410,10 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                          ],
                          vec!(("".to_string(), "".to_string())),
                          Some("".to_string()))
-                .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
+                .expect(&format!("failed to exec `{:?}`", config.adb_path));
 
             procsrv::run("",
-                         config.adb_path.as_slice(),
+                         &config.adb_path,
                          None,
                          &[
                             "forward".to_string(),
@@ -423,7 +422,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                          ],
                          vec!(("".to_string(), "".to_string())),
                          Some("".to_string()))
-                .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
+                .expect(&format!("failed to exec `{:?}`", config.adb_path));
 
             let adb_arg = format!("export LD_LIBRARY_PATH={}; \
                                    gdbserver :5039 {}/{}",
@@ -434,8 +433,8 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                                       .unwrap()).unwrap());
 
             let mut process = procsrv::run_background("",
-                                                      config.adb_path
-                                                            .as_slice(),
+                                                      &config.adb_path
+                                                            ,
                                                       None,
                                                       &[
                                                         "shell".to_string(),
@@ -444,7 +443,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                                                       vec!(("".to_string(),
                                                             "".to_string())),
                                                       Some("".to_string()))
-                .expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
+                .expect(&format!("failed to exec `{:?}`", config.adb_path));
             loop {
                 //waiting 1 second for gdbserver start
                 timer::sleep(Duration::milliseconds(1000));
@@ -477,16 +476,16 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                 err,
                 status
             } = procsrv::run("",
-                             gdb_path.as_slice(),
+                             &gdb_path,
                              None,
-                             debugger_opts.as_slice(),
+                             &debugger_opts,
                              vec!(("".to_string(), "".to_string())),
                              None)
-                .expect(format!("failed to exec `{:?}`", gdb_path).as_slice());
+                .expect(&format!("failed to exec `{:?}`", gdb_path));
             let cmdline = {
                 let cmdline = make_cmdline("",
                                            "arm-linux-androideabi-gdb",
-                                           debugger_opts.as_slice());
+                                           &debugger_opts);
                 logv(config, format!("executing {}", cmdline));
                 cmdline
             };
@@ -517,16 +516,16 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
             match config.gdb_version {
                 Some(ref version) => {
                     println!("NOTE: compiletest thinks it is using GDB version {}",
-                             version.as_slice());
+                             version);
 
-                    if header::gdb_version_to_int(version.as_slice()) >
+                    if header::gdb_version_to_int(version) >
                         header::gdb_version_to_int("7.4") {
                         // Add the directory containing the pretty printers to
                         // GDB's script auto loading safe path
                         script_str.push_str(
-                            format!("add-auto-load-safe-path {}\n",
-                                    rust_pp_module_abs_path.replace("\\", "\\\\").as_slice())
-                                .as_slice());
+                            &format!("add-auto-load-safe-path {}\n",
+                                     rust_pp_module_abs_path.replace("\\", "\\\\"))
+                                );
                     }
                 }
                 _ => {
@@ -553,13 +552,13 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
                                              *line)[]);
             }
 
-            script_str.push_str(cmds.as_slice());
+            script_str.push_str(&cmds);
             script_str.push_str("quit\n");
 
             debug!("script_str = {}", script_str);
             dump_output_file(config,
                              testfile,
-                             script_str.as_slice(),
+                             &script_str,
                              "debugger.script");
 
             // run debugger script with gdb
@@ -592,7 +591,7 @@ fn debugger() -> String {
                                                   testfile,
                                                   proc_args,
                                                   environment,
-                                                  config.run_lib_path.as_slice(),
+                                                  &config.run_lib_path,
                                                   None,
                                                   None);
         }
@@ -602,7 +601,7 @@ fn debugger() -> String {
         fatal("gdb failed to execute");
     }
 
-    check_debugger_output(&debugger_run_result, check_lines.as_slice());
+    check_debugger_output(&debugger_run_result, &check_lines);
 }
 
 fn find_rust_src_root(config: &Config) -> Option<Path> {
@@ -644,7 +643,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
     match config.lldb_version {
         Some(ref version) => {
             println!("NOTE: compiletest thinks it is using LLDB version {}",
-                     version.as_slice());
+                     version);
         }
         _ => {
             println!("NOTE: compiletest does not know which version of \
@@ -684,13 +683,12 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
 
     // Set breakpoints on every line that contains the string "#break"
     for line in &breakpoint_lines {
-        script_str.push_str(format!("breakpoint set --line {}\n",
-                                    line).as_slice());
+        script_str.push_str(&format!("breakpoint set --line {}\n", line));
     }
 
     // Append the other commands
     for line in &commands {
-        script_str.push_str(line.as_slice());
+        script_str.push_str(line);
         script_str.push_str("\n");
     }
 
@@ -701,7 +699,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
     debug!("script_str = {}", script_str);
     dump_output_file(config,
                      testfile,
-                     script_str.as_slice(),
+                     &script_str,
                      "debugger.script");
     let debugger_script = make_out_name(config, testfile, "debugger.script");
 
@@ -715,7 +713,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
         fatal_proc_rec("Error while running LLDB", &debugger_run_result);
     }
 
-    check_debugger_output(&debugger_run_result, check_lines.as_slice());
+    check_debugger_output(&debugger_run_result, &check_lines);
 
     fn run_lldb(config: &Config,
                 test_executable: &Path,
@@ -729,7 +727,7 @@ fn run_lldb(config: &Config,
         cmd.arg(lldb_script_path)
            .arg(test_executable)
            .arg(debugger_script)
-           .env_set_all(&[("PYTHONPATH", config.lldb_python_dir.clone().unwrap().as_slice())]);
+           .env_set_all(&[("PYTHONPATH", config.lldb_python_dir.clone().unwrap())]);
 
         let (status, out, err) = match cmd.spawn() {
             Ok(process) => {
@@ -741,12 +739,12 @@ fn run_lldb(config: &Config,
                  String::from_utf8(error).unwrap())
             },
             Err(e) => {
-                fatal(format!("Failed to setup Python process for \
-                               LLDB script: {}", e).as_slice())
+                fatal(&format!("Failed to setup Python process for \
+                                LLDB script: {}", e))
             }
         };
 
-        dump_output(config, test_executable, out.as_slice(), err.as_slice());
+        dump_output(config, test_executable, &out, &err);
         return ProcRes {
             status: status,
             stdout: out,
@@ -782,20 +780,19 @@ fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
                 }
 
                 header::parse_name_value_directive(
-                        line.as_slice(),
-                        command_directive.as_slice()).map(|cmd| {
+                        &line,
+                        &command_directive).map(|cmd| {
                     commands.push(cmd)
                 });
 
                 header::parse_name_value_directive(
-                        line.as_slice(),
-                        check_directive.as_slice()).map(|cmd| {
+                        &line,
+                        &check_directive).map(|cmd| {
                     check_lines.push(cmd)
                 });
             }
             Err(e) => {
-                fatal(format!("Error while parsing debugger commands: {}",
-                              e).as_slice())
+                fatal(&format!("Error while parsing debugger commands: {}", e))
             }
         }
         counter += 1;
@@ -834,7 +831,7 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String])
         // bits in the wrong case of an enum) with the notation "[...]".
         let check_fragments: Vec<Vec<String>> =
             check_lines.iter().map(|s| {
-                s.as_slice()
+                s
                  .trim()
                  .split_str("[...]")
                  .map(|x| x.to_string())
@@ -849,13 +846,13 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String])
             let mut failed = false;
             for frag in &check_fragments[i] {
                 let found = if first {
-                    if rest.starts_with(frag.as_slice()) {
+                    if rest.starts_with(frag) {
                         Some(0)
                     } else {
                         None
                     }
                 } else {
-                    rest.find_str(frag.as_slice())
+                    rest.find_str(frag)
                 };
                 match found {
                     None => {
@@ -877,8 +874,8 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String])
             }
         }
         if i != num_check_lines {
-            fatal_proc_rec(format!("line not found in debugger output: {}",
-                                  check_lines.get(i).unwrap()).as_slice(),
+            fatal_proc_rec(&format!("line not found in debugger output: {}",
+                                    check_lines.get(i).unwrap()),
                           debugger_run_result);
         }
     }
@@ -889,14 +886,13 @@ fn check_error_patterns(props: &TestProps,
                         output_to_check: &str,
                         proc_res: &ProcRes) {
     if props.error_patterns.is_empty() {
-        fatal(format!("no error pattern specified in {:?}",
-                      testfile.display()).as_slice());
+        fatal(&format!("no error pattern specified in {:?}", testfile.display()));
     }
     let mut next_err_idx = 0;
     let mut next_err_pat = &props.error_patterns[next_err_idx];
     let mut done = false;
     for line in output_to_check.lines() {
-        if line.contains(next_err_pat.as_slice()) {
+        if line.contains(next_err_pat) {
             debug!("found error pattern {}", next_err_pat);
             next_err_idx += 1;
             if next_err_idx == props.error_patterns.len() {
@@ -911,13 +907,11 @@ fn check_error_patterns(props: &TestProps,
 
     let missing_patterns = &props.error_patterns[next_err_idx..];
     if missing_patterns.len() == 1 {
-        fatal_proc_rec(format!("error pattern '{}' not found!",
-                              missing_patterns[0]).as_slice(),
+        fatal_proc_rec(&format!("error pattern '{}' not found!", missing_patterns[0]),
                       proc_res);
     } else {
         for pattern in missing_patterns {
-            error(format!("error pattern '{}' not found!",
-                          *pattern).as_slice());
+            error(&format!("error pattern '{}' not found!", *pattern));
         }
         fatal_proc_rec("multiple error patterns not found", proc_res);
     }
@@ -936,7 +930,7 @@ fn check_forbid_output(props: &TestProps,
                        output_to_check: &str,
                        proc_res: &ProcRes) {
     for pat in &props.forbid_output {
-        if output_to_check.contains(pat.as_slice()) {
+        if output_to_check.contains(pat) {
             fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
         }
     }
@@ -959,7 +953,7 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
 
     #[cfg(windows)]
     fn prefix_matches( line : &str, prefix : &str ) -> bool {
-        line.to_ascii_lowercase().starts_with(prefix.to_ascii_lowercase().as_slice())
+        line.to_ascii_lowercase().starts_with(&prefix.to_ascii_lowercase())
     }
 
     #[cfg(unix)]
@@ -988,13 +982,13 @@ fn continuation( line: &str) -> bool {
         for (i, ee) in expected_errors.iter().enumerate() {
             if !found_flags[i] {
                 debug!("prefix={} ee.kind={} ee.msg={} line={}",
-                       prefixes[i].as_slice(),
+                       prefixes[i],
                        ee.kind,
                        ee.msg,
                        line);
-                if (prefix_matches(line, prefixes[i].as_slice()) || continuation(line)) &&
-                    line.contains(ee.kind.as_slice()) &&
-                    line.contains(ee.msg.as_slice()) {
+                if (prefix_matches(line, &prefixes[i]) || continuation(line)) &&
+                    line.contains(&ee.kind) &&
+                    line.contains(&ee.msg) {
                     found_flags[i] = true;
                     was_expected = true;
                     break;
@@ -1008,8 +1002,8 @@ fn continuation( line: &str) -> bool {
         }
 
         if !was_expected && is_compiler_error_or_warning(line) {
-            fatal_proc_rec(format!("unexpected compiler error or warning: '{}'",
-                                  line).as_slice(),
+            fatal_proc_rec(&format!("unexpected compiler error or warning: '{}'",
+                                    line),
                           proc_res);
         }
     }
@@ -1017,8 +1011,8 @@ fn continuation( line: &str) -> bool {
     for (i, &flag) in found_flags.iter().enumerate() {
         if !flag {
             let ee = &expected_errors[i];
-            fatal_proc_rec(format!("expected {} on line {} not found: {}",
-                                  ee.kind, ee.line, ee.msg).as_slice(),
+            fatal_proc_rec(&format!("expected {} on line {} not found: {}",
+                                    ee.kind, ee.line, ee.msg),
                           proc_res);
         }
     }
@@ -1139,7 +1133,7 @@ fn exec_compiled_test(config: &Config, props: &TestProps,
 
     let env = props.exec_env.clone();
 
-    match config.target.as_slice() {
+    match &*config.target {
 
         "arm-linux-androideabi" => {
             _arm_exec_compiled_test(config, props, testfile, env)
@@ -1151,7 +1145,7 @@ fn exec_compiled_test(config: &Config, props: &TestProps,
                             testfile,
                             make_run_args(config, props, testfile),
                             env,
-                            config.run_lib_path.as_slice(),
+                            &config.run_lib_path,
                             Some(aux_dir.as_str().unwrap()),
                             None)
         }
@@ -1174,7 +1168,7 @@ fn compose_and_run_compiler(
     let extra_link_args = vec!("-L".to_string(), aux_dir.as_str().unwrap().to_string());
 
     for rel_ab in &props.aux_builds {
-        let abs_ab = config.aux_base.join(rel_ab.as_slice());
+        let abs_ab = config.aux_base.join(rel_ab);
         let aux_props = header::load_props(&abs_ab);
         let mut crate_type = if aux_props.no_prefer_dynamic {
             Vec::new()
@@ -1195,17 +1189,17 @@ fn compose_and_run_compiler(
                                      &abs_ab,
                                      aux_args,
                                      Vec::new(),
-                                     config.compile_lib_path.as_slice(),
+                                     &config.compile_lib_path,
                                      Some(aux_dir.as_str().unwrap()),
                                      None);
         if !auxres.status.success() {
             fatal_proc_rec(
-                format!("auxiliary build of {:?} failed to compile: ",
-                        abs_ab.display()).as_slice(),
+                &format!("auxiliary build of {:?} failed to compile: ",
+                        abs_ab.display()),
                 &auxres);
         }
 
-        match config.target.as_slice() {
+        match &*config.target {
             "arm-linux-androideabi" => {
                 _arm_push_aux_shared_library(config, testfile);
             }
@@ -1217,7 +1211,7 @@ fn compose_and_run_compiler(
                     testfile,
                     args,
                     Vec::new(),
-                    config.compile_lib_path.as_slice(),
+                    &config.compile_lib_path,
                     Some(aux_dir.as_str().unwrap()),
                     input)
 }
@@ -1252,16 +1246,16 @@ fn make_compile_args<F>(config: &Config,
 {
     let xform_file = xform(config, testfile);
     let target = if props.force_host {
-        config.host.as_slice()
+        &*config.host
     } else {
-        config.target.as_slice()
+        &*config.target
     };
     // FIXME (#9639): This needs to handle non-utf8 paths
     let mut args = vec!(testfile.as_str().unwrap().to_string(),
                         "-L".to_string(),
                         config.build_base.as_str().unwrap().to_string(),
                         format!("--target={}", target));
-    args.push_all(extras.as_slice());
+    args.push_all(&extras);
     if !props.no_prefer_dynamic {
         args.push("-C".to_string());
         args.push("prefer-dynamic".to_string());
@@ -1329,7 +1323,7 @@ fn make_run_args(config: &Config, props: &TestProps, testfile: &Path) ->
 fn split_maybe_args(argstr: &Option<String>) -> Vec<String> {
     match *argstr {
         Some(ref s) => {
-            s.as_slice()
+            s
              .split(' ')
              .filter_map(|s| {
                  if s.chars().all(|c| c.is_whitespace()) {
@@ -1350,8 +1344,8 @@ fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String
     let cmdline =
         {
             let cmdline = make_cmdline(lib_path,
-                                       prog.as_slice(),
-                                       args.as_slice());
+                                       &prog,
+                                       &args);
             logv(config, format!("executing {}", cmdline));
             cmdline
         };
@@ -1360,12 +1354,12 @@ fn program_output(config: &Config, testfile: &Path, lib_path: &str, prog: String
         err,
         status
     } = procsrv::run(lib_path,
-                     prog.as_slice(),
+                     &prog,
                      aux_path,
-                     args.as_slice(),
+                     &args,
                      env,
-                     input).expect(format!("failed to exec `{}`", prog).as_slice());
-    dump_output(config, testfile, out.as_slice(), err.as_slice());
+                     input).expect(&format!("failed to exec `{}`", prog));
+    dump_output(config, testfile, &out, &err);
     return ProcRes {
         status: status,
         stdout: out,
@@ -1422,7 +1416,7 @@ fn output_testname(testfile: &Path) -> Path {
 fn output_base_name(config: &Config, testfile: &Path) -> Path {
     config.build_base
         .join(&output_testname(testfile))
-        .with_extension(config.stage_id.as_slice())
+        .with_extension(&config.stage_id)
 }
 
 fn maybe_dump_to_stdout(config: &Config, out: &str, err: &str) {
@@ -1465,12 +1459,11 @@ fn _arm_exec_compiled_test(config: &Config,
                            -> ProcRes {
     let args = make_run_args(config, props, testfile);
     let cmdline = make_cmdline("",
-                               args.prog.as_slice(),
-                               args.args.as_slice());
+                               &args.prog,
+                               &args.args);
 
     // get bare program string
     let mut tvec: Vec<String> = args.prog
-                                    .as_slice()
                                     .split('/')
                                     .map(|ts| ts.to_string())
                                     .collect();
@@ -1478,7 +1471,7 @@ fn _arm_exec_compiled_test(config: &Config,
 
     // copy to target
     let copy_result = procsrv::run("",
-                                   config.adb_path.as_slice(),
+                                   &config.adb_path,
                                    None,
                                    &[
                                     "push".to_string(),
@@ -1487,7 +1480,7 @@ fn _arm_exec_compiled_test(config: &Config,
                                    ],
                                    vec!(("".to_string(), "".to_string())),
                                    Some("".to_string()))
-        .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+        .expect(&format!("failed to exec `{}`", config.adb_path));
 
     if config.verbose {
         println!("push ({}) {} {} {}",
@@ -1514,11 +1507,11 @@ fn _arm_exec_compiled_test(config: &Config,
         runargs.push(tv.to_string());
     }
     procsrv::run("",
-                 config.adb_path.as_slice(),
+                 &config.adb_path,
                  None,
-                 runargs.as_slice(),
+                 &runargs,
                  vec!(("".to_string(), "".to_string())), Some("".to_string()))
-        .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+        .expect(&format!("failed to exec `{}`", config.adb_path));
 
     // get exitcode of result
     runargs = Vec::new();
@@ -1528,12 +1521,12 @@ fn _arm_exec_compiled_test(config: &Config,
 
     let procsrv::Result{ out: exitcode_out, err: _, status: _ } =
         procsrv::run("",
-                     config.adb_path.as_slice(),
+                     &config.adb_path,
                      None,
-                     runargs.as_slice(),
+                     &runargs,
                      vec!(("".to_string(), "".to_string())),
                      Some("".to_string()))
-        .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+        .expect(&format!("failed to exec `{}`", config.adb_path));
 
     let mut exitcode: int = 0;
     for c in exitcode_out.chars() {
@@ -1552,12 +1545,12 @@ fn _arm_exec_compiled_test(config: &Config,
 
     let procsrv::Result{ out: stdout_out, err: _, status: _ } =
         procsrv::run("",
-                     config.adb_path.as_slice(),
+                     &config.adb_path,
                      None,
-                     runargs.as_slice(),
+                     &runargs,
                      vec!(("".to_string(), "".to_string())),
                      Some("".to_string()))
-        .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+        .expect(&format!("failed to exec `{}`", config.adb_path));
 
     // get stderr of result
     runargs = Vec::new();
@@ -1567,17 +1560,17 @@ fn _arm_exec_compiled_test(config: &Config,
 
     let procsrv::Result{ out: stderr_out, err: _, status: _ } =
         procsrv::run("",
-                     config.adb_path.as_slice(),
+                     &config.adb_path,
                      None,
-                     runargs.as_slice(),
+                     &runargs,
                      vec!(("".to_string(), "".to_string())),
                      Some("".to_string()))
-        .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+        .expect(&format!("failed to exec `{}`", config.adb_path));
 
     dump_output(config,
                 testfile,
-                stdout_out.as_slice(),
-                stderr_out.as_slice());
+                &stdout_out,
+                &stderr_out);
 
     ProcRes {
         status: process::ProcessExit::ExitStatus(exitcode),
@@ -1595,7 +1588,7 @@ fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
         if file.extension_str() == Some("so") {
             // FIXME (#9639): This needs to handle non-utf8 paths
             let copy_result = procsrv::run("",
-                                           config.adb_path.as_slice(),
+                                           &config.adb_path,
                                            None,
                                            &[
                                             "push".to_string(),
@@ -1607,7 +1600,7 @@ fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
                                            vec!(("".to_string(),
                                                  "".to_string())),
                                            Some("".to_string()))
-                .expect(format!("failed to exec `{}`", config.adb_path).as_slice());
+                .expect(&format!("failed to exec `{}`", config.adb_path));
 
             if config.verbose {
                 println!("push ({}) {:?} {} {}",
@@ -1702,7 +1695,7 @@ fn disassemble_extract(config: &Config, _props: &TestProps,
 
 fn count_extracted_lines(p: &Path) -> uint {
     let x = File::open(&p.with_extension("ll")).read_to_end().unwrap();
-    let x = str::from_utf8(x.as_slice()).unwrap();
+    let x = str::from_utf8(&x).unwrap();
     x.lines().count()
 }
 
index 326946837bf661ee0c158a212832a00cbd303525..999efc95c0e60b536103d64e4f96e02e11709e53 100644 (file)
@@ -256,11 +256,11 @@ cases mentioned in [Number literals](#number-literals) below.
 
 | [Number literals](#number-literals)`*` | Example | Exponentiation | Suffixes |
 |----------------------------------------|---------|----------------|----------|
-| Decimal integer | `98_222is` | `N/A` | Integer suffixes |
-| Hex integer | `0xffis` | `N/A` | Integer suffixes |
-| Octal integer | `0o77is` | `N/A` | Integer suffixes |
-| Binary integer | `0b1111_0000is` | `N/A` | Integer suffixes |
-| Floating-point | `123.0E+77f64` | `Optional` | Floating-point suffixes |
+| Decimal integer | `98_222` | `N/A` | Integer suffixes |
+| Hex integer | `0xff` | `N/A` | Integer suffixes |
+| Octal integer | `0o77` | `N/A` | Integer suffixes |
+| Binary integer | `0b1111_0000` | `N/A` | Integer suffixes |
+| Floating-point | `123.0E+77` | `Optional` | Floating-point suffixes |
 
 `*` All number literals allow `_` as a visual separator: `1_234.0E+18f64`
 
@@ -1813,7 +1813,6 @@ default visibility with the `priv` keyword. When an item is declared as `pub`,
 it can be thought of as being accessible to the outside world. For example:
 
 ```
-# #![allow(missing_copy_implementations)]
 # fn main() {}
 // Declare a private struct
 struct Foo;
@@ -2015,6 +2014,11 @@ type int8_t = i8;
 - `no_start` - disable linking to the `native` crate, which specifies the
   "start" language item.
 - `no_std` - disable linking to the `std` crate.
+- `plugin` — load a list of named crates as compiler plugins, e.g.
+             `#![plugin(foo, bar)]`. Optional arguments for each plugin,
+             i.e. `#![plugin(foo(... args ...))]`, are provided to the plugin's
+             registrar function.  The `plugin` feature gate is required to use
+             this attribute.
 
 ### Module-only attributes
 
@@ -2083,7 +2087,7 @@ On `struct`s:
   remove any padding between fields (note that this is very fragile and may
   break platforms which require aligned access).
 
-### Macro- and plugin-related attributes
+### Macro-related attributes
 
 - `macro_use` on a `mod` — macros defined in this module will be visible in the
   module's parent, after this module has been included.
@@ -2098,13 +2102,8 @@ On `struct`s:
 
 - `macro_export` - export a macro for cross-crate usage.
 
-- `plugin` on an `extern crate` — load this crate as a [compiler
-  plugin][plugin].  The `plugin` feature gate is required.  Any arguments to
-  the attribute, e.g. `#[plugin=...]` or `#[plugin(...)]`, are provided to the
-  plugin.
-
-- `no_link` on an `extern crate` — even if we load this crate for macros or
-  compiler plugins, don't link it into the output.
+- `no_link` on an `extern crate` — even if we load this crate for macros, don't
+  link it into the output.
 
 See the [macros section of the
 book](book/macros.html#scoping-and-macro-import/export) for more information on
@@ -2468,6 +2467,12 @@ The currently implemented features of the reference compiler are:
 
 * `associated_types` - Allows type aliases in traits. Experimental.
 
+* `no_std` - Allows the `#![no_std]` crate attribute, which disables the implicit
+             `extern crate std`. This typically requires use of the unstable APIs
+             behind the libstd "facade", such as libcore and libcollections. It
+             may also cause problems when using syntax extensions, including
+             `#[derive]`.
+
 If a feature is promoted to a language feature, then all existing programs will
 start to receive compilation warnings about #[feature] directives which enabled
 the new feature (because the directive is no longer necessary). However, if a
index 6131e1b8a70703066498f0c28a25122ae0aabcfc..9d65f30e7237993e2d2793dc410644e664019ed3 100644 (file)
@@ -27,7 +27,7 @@
     * [Iterators](iterators.md)
     * [Generics](generics.md)
     * [Traits](traits.md)
-    * [Threads](threads.md)
+    * [Concurrency](concurrency.md)
     * [Error Handling](error-handling.md)
     * [Documentation](documentation.md)
 * [III: Advanced Topics](advanced.md)
index 901b44661b04c743771893cd77aac09d7e1d3ee9..8b99278acb1f67e3d917b5421b03662a10c7350a 100644 (file)
@@ -200,8 +200,62 @@ destructuring `let`, as we discussed previously in 'tuples.' In this case, the
 ## Enums
 
 Finally, Rust has a "sum type", an *enum*. Enums are an incredibly useful
-feature of Rust, and are used throughout the standard library. This is an enum
-that is provided by the Rust standard library:
+feature of Rust, and are used throughout the standard library. An `enum` is
+a type which ties a set of alternates to a specific name. For example, below
+we define `Character` to be either a `Digit` or something else. These
+can be used via their fully scoped names: `Character::Other` (more about `::`
+below).
+
+```rust
+enum Character {
+    Digit(i32),
+    Other,
+}
+```
+
+An `enum` variant can be defined as most normal types. Below are some example
+types have been listed which also would be allowed in an `enum`.
+
+```rust
+struct Empty;
+struct Color(i32, i32, i32);
+struct Length(i32);
+struct Status { Health: i32, Mana: i32, Attack: i32, Defense: i32 }
+struct HeightDatabase(Vec<i32>);
+```
+
+So you see that depending on the sub-datastructure, the `enum` variant, same as
+a struct, may or may not hold data. That is, in `Character`, `Digit` is a name
+tied to an `i32` where `Other` is just a name. However, the fact that they are
+distinct makes this very useful.
+
+As with structures, enums don't by default have access to operators such as
+compare ( `==` and `!=`), binary operations (`*` and `+`), and order
+(`<` and `>=`). As such, using the previous `Character` type, the
+following code is invalid:
+
+```{rust,ignore}
+// These assignments both succeed
+let ten  = Character::Digit(10);
+let four = Character::Digit(4);
+
+// Error: `*` is not implemented for type `Character`
+let forty = ten * four;
+
+// Error: `<=` is not implemented for type `Character`
+let four_is_smaller = four <= ten;
+
+// Error: `==` is not implemented for type `Character`
+let four_equals_ten = four == ten;
+```
+
+This may seem rather limiting, particularly equality being invalid; in
+many cases however, it's unnecessary. Rust provides the [`match`][match]
+keyword, which will be examined in more detail in the next section, which
+often allows better and easier branch control than a series of `if`/`else`
+statements would. However, for our [game][game] we need the comparisons
+to work so we will utilize the `Ordering` `enum` provided by the standard
+library which supports such comparisons. It has this form:
 
 ```{rust}
 enum Ordering {
@@ -211,14 +265,9 @@ enum Ordering {
 }
 ```
 
-An `Ordering` can only be _one_ of `Less`, `Equal`, or `Greater` at any given
-time.
-
-Because `Ordering` is provided by the standard library, we can use the `use`
-keyword to use it in our code. We'll learn more about `use` later, but it's
-used to bring names into scope.
-
-Here's an example of how to use `Ordering`:
+Because we did not define `Ordering`, we must import it (from the std
+library) with the `use` keyword. Here's an example of how `Ordering` is
+used:
 
 ```{rust}
 use std::cmp::Ordering;
@@ -245,11 +294,10 @@ fn main() {
 }
 ```
 
-There's a symbol here we haven't seen before: the double colon (`::`).
-This is used to indicate a namespace. In this case, `Ordering` lives in
-the `cmp` submodule of the `std` module. We'll talk more about modules
-later in the guide. For now, all you need to know is that you can `use`
-things from the standard library if you need them.
+The `::` symbol is used to indicate a namespace. In this case, `Ordering` lives
+in the `cmp` submodule of the `std` module. We'll talk more about modules later
+in the guide. For now, all you need to know is that you can `use` things from
+the standard library if you need them.
 
 Okay, let's talk about the actual code in the example. `cmp` is a function that
 compares two things, and returns an `Ordering`. We return either
@@ -259,95 +307,44 @@ the two values are less, greater, or equal. Note that each variant of the
 `Greater`.
 
 The `ordering` variable has the type `Ordering`, and so contains one of the
-three values. We can then do a bunch of `if`/`else` comparisons to check which
-one it is. However, repeated `if`/`else` comparisons get quite tedious. Rust
-has a feature that not only makes them nicer to read, but also makes sure that
-you never miss a case. Before we get to that, though, let's talk about another
-kind of enum: one with values.
+three values. We then do a bunch of `if`/`else` comparisons to check which
+one it is.
 
-This enum has two variants, one of which has a value:
+This `Ordering::Greater` notation is too long. Lets use `use` to import can
+the `enum` variants instead. This will avoid full scoping:
 
 ```{rust}
-enum OptionalInt {
-    Value(i32),
-    Missing,
-}
-```
-
-This enum represents an `i32` that we may or may not have. In the `Missing`
-case, we have no value, but in the `Value` case, we do. This enum is specific
-to `i32`s, though. We can make it usable by any type, but we haven't quite
-gotten there yet!
-
-You can also have any number of values in an enum:
+use std::cmp::Ordering::{self, Equal, Less, Greater};
 
-```{rust}
-enum OptionalColor {
-    Color(i32, i32, i32),
-    Missing,
-}
-```
-
-And you can also have something like this:
-
-```{rust}
-enum StringResult {
-    StringOK(String),
-    ErrorReason(String),
+fn cmp(a: i32, b: i32) -> Ordering {
+    if a < b { Less }
+    else if a > b { Greater }
+    else { Equal }
 }
-```
-Where a `StringResult` is either a `StringResult::StringOK`, with the result of
-a computation, or a `StringResult::ErrorReason` with a `String` explaining
-what caused the computation to fail. These kinds of `enum`s are actually very
-useful and are even part of the standard library.
 
-Here is an example of using our `StringResult`:
+fn main() {
+    let x = 5;
+    let y = 10;
 
-```rust
-enum StringResult {
-    StringOK(String),
-    ErrorReason(String),
-}
+    let ordering = cmp(x, y); // ordering: Ordering
 
-fn respond(greeting: &str) -> StringResult {
-    if greeting == "Hello" {
-        StringResult::StringOK("Good morning!".to_string())
-    } else {
-        StringResult::ErrorReason("I didn't understand you!".to_string())
-    }
+    if ordering == Less { println!("less"); }
+    else if ordering == Greater { println!("greater"); }
+    else if ordering == Equal { println!("equal"); }
 }
 ```
 
-That's a lot of typing! We can use the `use` keyword to make it shorter:
+Importing variants is convenient and compact, but can also cause name conflicts,
+so do this with caution. It's considered good style to rarely import variants
+for this reason.
 
-```rust
-use StringResult::StringOK;
-use StringResult::ErrorReason;
+As you can see, `enum`s are quite a powerful tool for data representation, and are
+even more useful when they're [generic][generics] across types. Before we
+get to generics, though, let's talk about how to use them with pattern matching, a
+tool that will let us deconstruct this sum type (the type theory term for enums)
+in a very elegant way and avoid all these messy `if`/`else`s.
 
-enum StringResult {
-    StringOK(String),
-    ErrorReason(String),
-}
-
-# fn main() {}
-
-fn respond(greeting: &str) -> StringResult {
-    if greeting == "Hello" {
-        StringOK("Good morning!".to_string())
-    } else {
-        ErrorReason("I didn't understand you!".to_string())
-    }
-}
-```
 
-`use` declarations must come before anything else, which looks a little strange in this example,
-since we `use` the variants before we define them. Anyway, in the body of `respond`, we can just
-say `StringOK` now, rather than the full `StringResult::StringOK`. Importing variants can be
-convenient, but can also cause name conflicts, so do this with caution. It's considered good style
-to rarely import variants for this reason.
-
-As you can see, `enum`s with values are quite a powerful tool for data representation,
-and can be even more useful when they're generic across types. Before we get to generics,
-though, let's talk about how to use them with pattern matching, a tool that will
-let us deconstruct this sum type (the type theory term for enums) in a very elegant
-way and avoid all these messy `if`/`else`s.
+[match]: ./match.html
+[game]: ./guessing-game.html#comparing-guesses
+[generics]: ./generics.html
diff --git a/src/doc/trpl/concurrency.md b/src/doc/trpl/concurrency.md
new file mode 100644 (file)
index 0000000..5dba1b2
--- /dev/null
@@ -0,0 +1,391 @@
+% Concurrency
+
+Concurrency and parallelism are incredibly important topics in computer
+science, and are also a hot topic in industry today. Computers are gaining more
+and more cores, yet many programmers aren't prepared to fully utilize them.
+
+Rust's memory safety features also apply to its concurrency story too. Even
+concurrent Rust programs must be memory safe, having no data races. Rust's type
+system is up to the task, and gives you powerful ways to reason about
+concurrent code at compile time.
+
+Before we talk about the concurrency features that come with Rust, it's important
+to understand something: Rust is low-level enough that all of this is provided
+by the standard library, not by the language. This means that if you don't like
+some aspect of the way Rust handles concurrency, you can implement an alternative
+way of doing things. [mio](https://github.com/carllerche/mio) is a real-world
+example of this principle in action.
+
+## Background: `Send` and `Sync`
+
+Concurrency is difficult to reason about. In Rust, we have a strong, static
+type system to help us reason about our code. As such, Rust gives us two traits
+to help us make sense of code that can possibly be concurrent.
+
+### `Send`
+
+The first trait we're going to talk about is
+[`Send`](../std/marker/trait.Send.html). When a type `T` implements `Send`, it indicates
+to the compiler that something of this type is able to have ownership transferred
+safely between threads.
+
+This is important to enforce certain restrictions. For example, if we have a
+channel connecting two threads, we would want to be able to send some data
+down the channel and to the other thread. Therefore, we'd ensure that `Send` was
+implemented for that type.
+
+In the opposite way, if we were wrapping a library with FFI that isn't
+threadsafe, we wouldn't want to implement `Send`, and so the compiler will help
+us enforce that it can't leave the current thread.
+
+### `Sync`
+
+The second of these two trait is called [`Sync`](../std/marker/trait.Sync.html).
+When a type `T` implements `Sync`, it indicates to the compiler that something
+of this type has no possibility of introducing memory unsafety when used from
+multiple threads concurrently.
+
+For example, sharing immutable data with an atomic reference count is
+threadsafe. Rust provides a type like this, `Arc<T>`, and it implements `Sync`,
+so that it could be safely shared between threads.
+
+These two traits allow you to use the type system to make strong guarantees
+about the properties of your code under concurrency. Before we demonstrate
+why, we need to learn how to create a concurrent Rust program in the first
+place!
+
+## Threads
+
+Rust's standard library provides a library for 'threads', which allow you to
+run Rust code in parallel. Here's a basic example of using `Thread`:
+
+```
+use std::thread::Thread;
+
+fn main() {
+    Thread::scoped(|| {
+        println!("Hello from a thread!");
+    });
+}
+```
+
+The `Thread::scoped()` method accepts a closure, which is executed in a new
+thread. It's called `scoped` because this thread returns a join guard:
+
+```
+use std::thread::Thread;
+
+fn main() {
+    let guard = Thread::scoped(|| {
+        println!("Hello from a thread!");
+    });
+
+    // guard goes out of scope here
+}
+```
+
+When `guard` goes out of scope, it will block execution until the thread is
+finished. If we didn't want this behaviour, we could use `Thread::spawn()`:
+
+```
+use std::thread::Thread;
+use std::old_io::timer;
+use std::time::Duration;
+
+fn main() {
+    Thread::spawn(|| {
+        println!("Hello from a thread!");
+    });
+
+    timer::sleep(Duration::milliseconds(50));
+}
+```
+
+Or call `.detach()`:
+
+```
+use std::thread::Thread;
+use std::old_io::timer;
+use std::time::Duration;
+
+fn main() {
+    let guard = Thread::scoped(|| {
+        println!("Hello from a thread!");
+    });
+
+    guard.detach();
+
+    timer::sleep(Duration::milliseconds(50));
+}
+```
+
+We need to `sleep` here because when `main()` ends, it kills all of the
+running threads.
+
+[`scoped`](std/thread/struct.Builder.html#method.scoped) has an interesting
+type signature:
+
+```text
+fn scoped<'a, T, F>(self, f: F) -> JoinGuard<'a, T>
+    where T: Send + 'a,
+          F: FnOnce() -> T,
+          F: Send + 'a
+```
+
+Specifically, `F`, the closure that we pass to execute in the new thread. It
+has two restrictions: It must be a `FnOnce` from `()` to `T`. Using `FnOnce`
+allows the closure to take ownership of any data it mentions from the parent
+thread. The other restriction is that `F` must be `Send`. We aren't allowed to
+transfer this ownership unless the type thinks that's okay.
+
+Many languages have the ability to execute threads, but it's wildly unsafe.
+There are entire books about how to prevent errors that occur from shared
+mutable state. Rust helps out with its type system here as well, by preventing
+data races at compile time. Let's talk about how you actually share things
+between threads.
+
+## Safe Shared Mutable State
+
+Due to Rust's type system, we have a concept that sounds like a lie: "safe
+shared mutable state." Many programmers agree that shared mutable state is
+very, very bad.
+
+Someone once said this:
+
+> Shared mutable state is the root of all evil. Most languages attempt to deal
+> with this problem through the 'mutable' part, but Rust deals with it by
+> solving the 'shared' part.
+
+The same [ownership system](ownership.html) that helps prevent using pointers
+incorrectly also helps rule out data races, one of the worst kinds of
+concurrency bugs.
+
+As an example, here is a Rust program that would have a data race in many
+languages. It will not compile:
+
+```ignore
+use std::thread::Thread;
+use std::old_io::timer;
+use std::time::Duration;
+
+fn main() {
+    let mut data = vec![1u32, 2, 3];
+
+    for i in 0 .. 2 {
+        Thread::spawn(move || {
+            data[i] += 1;
+        });
+    }
+
+    timer::sleep(Duration::milliseconds(50));
+}
+```
+
+This gives us an error:
+
+```text
+12:17 error: capture of moved value: `data`
+        data[i] += 1;
+        ^~~~
+```
+
+In this case, we know that our code _should_ be safe, but Rust isn't sure. And
+it's actually not safe: if we had a reference to `data` in each thread, and the
+thread takes ownership of the reference, we have three owners! That's bad. We
+can fix this by using the `Arc<T>` type, which is an atomic reference counted
+pointer. The 'atomic' part means that it's safe to share across threads.
+
+`Arc<T>` assumes one more property about its contents to ensure that it is safe
+to share across threads: it assumes its contents are `Sync`. But in our
+case, we want to be able to mutate the value. We need a type that can ensure
+only one person at a time can mutate what's inside. For that, we can use the
+`Mutex<T>` type. Here's the second version of our code. It still doesn't work,
+but for a different reason:
+
+```ignore
+use std::thread::Thread;
+use std::old_io::timer;
+use std::time::Duration;
+use std::sync::Mutex;
+
+fn main() {
+    let mut data = Mutex::new(vec![1u32, 2, 3]);
+
+    for i in 0 .. 2 {
+        let data = data.lock().unwrap();
+        Thread::spawn(move || {
+            data[i] += 1;
+        });
+    }
+
+    timer::sleep(Duration::milliseconds(50));
+}
+```
+
+Here's the error:
+
+```text
+<anon>:11:9: 11:22 error: the trait `core::marker::Send` is not implemented for the type `std::sync::mutex::MutexGuard<'_, collections::vec::Vec<u32>>` [E0277]
+<anon>:11         Thread::spawn(move || {
+                  ^~~~~~~~~~~~~
+<anon>:11:9: 11:22 note: `std::sync::mutex::MutexGuard<'_, collections::vec::Vec<u32>>` cannot be sent between threads safely
+<anon>:11         Thread::spawn(move || {
+                  ^~~~~~~~~~~~~
+```
+
+You see, [`Mutex`](std/sync/struct.Mutex.html) has a
+[`lock`](http://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html#method.lock)
+method which has this signature:
+
+```ignore
+fn lock(&self) -> LockResult<MutexGuard<T>>
+```
+
+If we [look at the code for MutexGuard](https://github.com/rust-lang/rust/blob/ca4b9674c26c1de07a2042cb68e6a062d7184cef/src/libstd/sync/mutex.rs#L172), we'll see
+this:
+
+```ignore
+__marker: marker::NoSend,
+```
+
+Because our guard is `NoSend`, it's not `Send`. Which means we can't actually
+transfer the guard across thread boundaries, which gives us our error.
+
+We can use `Arc<T>` to fix this. Here's the working version:
+
+```
+use std::sync::{Arc, Mutex};
+use std::thread::Thread;
+use std::old_io::timer;
+use std::time::Duration;
+
+fn main() {
+    let data = Arc::new(Mutex::new(vec![1u32, 2, 3]));
+
+    for i in (0us..2) {
+        let data = data.clone();
+        Thread::spawn(move || {
+            let mut data = data.lock().unwrap();
+            data[i] += 1;
+        });
+    }
+
+    timer::sleep(Duration::milliseconds(50));
+}
+```
+
+We now call `clone()` on our `Arc`, which increases the internal count. This
+handle is then moved into the new thread. Let's examine the body of the
+thread more closely:
+
+```
+# use std::sync::{Arc, Mutex};
+# use std::thread::Thread;
+# use std::old_io::timer;
+# use std::time::Duration;
+# fn main() {
+#     let data = Arc::new(Mutex::new(vec![1u32, 2, 3]));
+#     for i in (0us..2) {
+#         let data = data.clone();
+Thread::spawn(move || {
+    let mut data = data.lock().unwrap();
+    data[i] += 1;
+});
+#     }
+# }
+```
+
+First, we call `lock()`, which acquires the mutex's lock. Because this may fail,
+it returns an `Result<T, E>`, and because this is just an example, we `unwrap()`
+it to get a reference to the data. Real code would have more robust error handling
+here. We're then free to mutate it, since we have the lock.
+
+This timer bit is a bit awkward, however. We have picked a reasonable amount of
+time to wait, but it's entirely possible that we've picked too high, and that
+we could be taking less time. It's also possible that we've picked too low,
+and that we aren't actually finishing this computation.
+
+Rust's standard library provides a few more mechanisms for two threads to
+synchronize with each other. Let's talk about one: channels.
+
+## Channels
+
+Here's a version of our code that uses channels for synchronization, rather
+than waiting for a specific time:
+
+```
+use std::sync::{Arc, Mutex};
+use std::thread::Thread;
+use std::sync::mpsc;
+
+fn main() {
+    let data = Arc::new(Mutex::new(0u32));
+
+    let (tx, rx) = mpsc::channel();
+
+    for _ in (0..10) {
+        let (data, tx) = (data.clone(), tx.clone());
+
+        Thread::spawn(move || {
+            let mut data = data.lock().unwrap();
+            *data += 1;
+
+            tx.send(());
+        });
+    }
+
+    for _ in 0 .. 10 {
+        rx.recv();
+    }
+}
+```
+
+We use the `mpsc::channel()` method to construct a new channel. We just `send`
+a simple `()` down the channel, and then wait for ten of them to come back.
+
+While this channel is just sending a generic signal, we can send any data that
+is `Send` over the channel!
+
+```
+use std::sync::{Arc, Mutex};
+use std::thread::Thread;
+use std::sync::mpsc;
+
+fn main() {
+    let (tx, rx) = mpsc::channel();
+
+    for _ in range(0, 10) {
+        let tx = tx.clone();
+
+        Thread::spawn(move || {
+            let answer = 42u32;
+
+            tx.send(answer);
+        });
+    }
+
+   rx.recv().ok().expect("Could not recieve answer");
+}
+```
+
+A `u32` is `Send` because we can make a copy. So we create a thread, ask it to calculate
+the answer, and then it `send()`s us the answer over the channel.
+
+
+## Panics
+
+A `panic!` will crash the currently executing thread. You can use Rust's
+threads as a simple isolation mechanism:
+
+```
+use std::thread::Thread;
+
+let result = Thread::scoped(move || {
+    panic!("oops!");
+}).join();
+
+assert!(result.is_err());
+```
+
+Our `Thread` gives us a `Result` back, which allows us to check if the thread
+has panicked or not.
index efeb201efe8474977dc617783a395ec41811625c..17b2cf7d0cc251ea98ff3959c1f002920da51d04 100644 (file)
@@ -551,6 +551,10 @@ module, we now have a `phrases::japanese::hello()` function and a
 `phrases::japanese::farewells::goodbye()`. Our internal organization doesn't
 define our external interface.
 
+Here we have a `pub use` for each function we want to bring into the 
+`japanese` scope. We could alternatively use the wildcard syntax to include
+everything from `greetings` into the current scope: `pub use self::greetings::*`. 
+
 Also, note that we `pub use`d before we declared our `mod`s. Rust requires that
 `use` declarations go first.
 
index 9e3a3f12d1d213f164003bba7b5b65f1bbb3ff59..3b5aa085e055a782b972aeb89cdf38fe2a319e40 100644 (file)
@@ -523,7 +523,7 @@ fn print<'a>(s: &'a str); // expanded
 fn debug(lvl: u32, s: &str); // elided
 fn debug<'a>(lvl: u32, s: &'a str); // expanded
 
-// In the preceeding example, `lvl` doesn't need a lifetime because it's not a
+// In the preceding example, `lvl` doesn't need a lifetime because it's not a
 // reference (`&`). Only things relating to references (such as a `struct`
 // which contains a reference) need lifetimes.
 
index 5ff233b4844157f78450859bc9a5cf7335595768..3dea1a66ffd72519732fcf64dafa452ed83ed8ad 100644 (file)
@@ -30,14 +30,14 @@ information.
 extend the compiler's behavior with new syntax extensions, lint checks, etc.
 
 A plugin is a dynamic library crate with a designated *registrar* function that
-registers extensions with `rustc`. Other crates can use these extensions by
-loading the plugin crate with `#[plugin] extern crate`. See the
+registers extensions with `rustc`. Other crates can load these extensions using
+the crate attribute `#![plugin(...)]`.  See the
 [`rustc::plugin`](../rustc/plugin/index.html) documentation for more about the
 mechanics of defining and loading a plugin.
 
-Arguments passed as `#[plugin=...]` or `#[plugin(...)]` are not interpreted by
-rustc itself.  They are provided to the plugin through the `Registry`'s [`args`
-method](../rustc/plugin/registry/struct.Registry.html#method.args).
+If present, arguments passed as `#![plugin(foo(... args ...))]` are not
+interpreted by rustc itself.  They are provided to the plugin through the
+`Registry`'s [`args` method](../rustc/plugin/registry/struct.Registry.html#method.args).
 
 # Syntax extensions
 
@@ -110,8 +110,7 @@ Then we can use `rn!()` like any other macro:
 
 ```ignore
 #![feature(plugin)]
-
-#[plugin] extern crate roman_numerals;
+#![plugin(roman_numerals)]
 
 fn main() {
     assert_eq!(rn!(MMXV), 2015);
@@ -219,7 +218,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
 Then code like
 
 ```ignore
-#[plugin] extern crate lint_plugin_test;
+#![plugin(lint_plugin_test)]
 
 fn lintme() { }
 ```
diff --git a/src/doc/trpl/rust-book.css b/src/doc/trpl/rust-book.css
deleted file mode 100644 (file)
index 3d08de4..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-
-@import url("//static.rust-lang.org/doc/master/rust.css");
-
-body {
-    max-width:none;
-}
-
-#toc {
-    position: absolute;
-    left: 0px;
-    top: 0px;
-    bottom: 0px;
-    width: 250px;
-    overflow-y: auto;
-    border-right: 1px solid rgba(0, 0, 0, 0.07);
-    padding: 10px 10px;
-    font-size: 16px;
-    background: none repeat scroll 0% 0% #FFF;
-    box-sizing: border-box;
-}
-
-#page-wrapper {
-    position: absolute;
-    overflow-y: auto;
-    left: 260px;
-    right: 0px;
-    top: 0px;
-    bottom: 0px;
-    box-sizing: border-box;
-    background: none repeat scroll 0% 0% #FFF;
-}
-
-#page {
-    margin-left: auto;
-    margin-right:auto;
-    width: 750px;
-}
-
-.chapter {
-    list-style: none outside none;
-    padding-left: 0px;
-    line-height: 30px;
-}
-
-.section {
-    list-style: none outside none;
-    padding-left: 20px;
-    line-height: 30px;
-}
-
-.section li {
-    text-overflow: ellipsis;
-    overflow: hidden;
-    white-space: nowrap;
-}
-
-.chapter li a {
-    color: #000000;
-}
diff --git a/src/doc/trpl/threads.md b/src/doc/trpl/threads.md
deleted file mode 100644 (file)
index a801a1a..0000000
+++ /dev/null
@@ -1,396 +0,0 @@
-% The Rust Threads and Communication Guide
-
-**NOTE** This guide is badly out of date and needs to be rewritten.
-
-# Introduction
-
-Rust provides safe concurrent abstractions through a number of core library
-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.
-
-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 thread. Unlike
-in languages such as Java and C++, there is no way to `catch` an exception.
-Instead, threads may monitor each other to see if they panic.
-
-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 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::thread::spawn;
-
-// 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 thread!"));
-```
-
-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.
-
-The `spawn` function has the type signature: `fn
-spawn<F:FnOnce()+Send>(f: F)`.  This indicates that it takes as
-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 thread for execution.
-
-```rust
-use std::thread::Thread;
-
-fn generate_thread_number() -> i32 { 4 } // a very simple generation
-
-// Generate some state locally
-let child_thread_number = generate_thread_number();
-
-Thread::spawn(move || {
-    // 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_thread_number);
-});
-```
-
-## Communication
-
-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.
-
-The simplest way to create a channel is to use the `channel` function to create a
-`(Sender, Receiver)` pair. In Rust parlance, a *sender* is a sending endpoint
-of a channel, and a *receiver* is the receiving endpoint. Consider the following
-example of calculating two results concurrently:
-
-```rust
-use std::thread::Thread;
-use std::sync::mpsc;
-
-let (tx, rx): (mpsc::Sender<u32>, mpsc::Receiver<u32>) = mpsc::channel();
-
-Thread::spawn(move || {
-    let result = some_expensive_computation();
-    tx.send(result);
-});
-
-some_other_expensive_computation();
-let result = rx.recv();
-
-fn some_expensive_computation() -> u32 { 42 } // very expensive ;)
-fn some_other_expensive_computation() {}      // even more so
-```
-
-Let's examine this example in detail. First, the `let` statement creates a
-stream for sending and receiving integers (the left-hand side of the `let`,
-`(tx, rx)`, is an example of a destructuring let: the pattern separates a tuple
-into its component parts).
-
-```rust
-# use std::sync::mpsc;
-let (tx, rx): (mpsc::Sender<u32>, mpsc::Receiver<u32>) = mpsc::channel();
-```
-
-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
-thread.
-
-```rust
-# use std::thread::Thread;
-# use std::sync::mpsc;
-# fn some_expensive_computation() -> u32 { 42 }
-# let (tx, rx) = mpsc::channel();
-Thread::spawn(move || {
-    let result = some_expensive_computation();
-    tx.send(result);
-});
-```
-
-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 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
-for the child's result to arrive on the receiver:
-
-```rust
-# use std::sync::mpsc;
-# fn some_other_expensive_computation() {}
-# let (tx, rx) = mpsc::channel::<u32>();
-# tx.send(0);
-some_other_expensive_computation();
-let result = rx.recv();
-```
-
-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 threads? The following program is ill-typed:
-
-```{rust,ignore}
-# use std::sync::mpsc;
-# fn some_expensive_computation() -> u32 { 42 }
-let (tx, rx) = mpsc::channel();
-
-spawn(move || {
-    tx.send(some_expensive_computation());
-});
-
-// ERROR! The previous spawn statement already owns the sender,
-// so the compiler will not allow it to be captured again
-spawn(move || {
-    tx.send(some_expensive_computation());
-});
-```
-
-Instead we can clone the `tx`, which allows for multiple senders.
-
-```rust
-use std::thread::Thread;
-use std::sync::mpsc;
-
-let (tx, rx) = mpsc::channel();
-
-for init_val in 0 .. 3 {
-    // Create a new channel handle to distribute to the child thread
-    let child_tx = tx.clone();
-    Thread::spawn(move || {
-        child_tx.send(some_expensive_computation(init_val));
-    });
-}
-
-let result = rx.recv().unwrap() + rx.recv().unwrap() + rx.recv().unwrap();
-# fn some_expensive_computation(_i: i32) -> i32 { 42 }
-```
-
-Cloning a `Sender` produces a new handle to the same channel, allowing multiple
-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.
-
-Note that the above cloning example is somewhat contrived since you could also
-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
-use std::thread::Thread;
-use std::sync::mpsc;
-
-// Create a vector of ports, one for each child thread
-let rxs = (0 .. 3).map(|&:init_val| {
-    let (tx, rx) = mpsc::channel();
-    Thread::spawn(move || {
-        tx.send(some_expensive_computation(init_val));
-    });
-    rx
-}).collect::<Vec<_>>();
-
-// Wait on each port, accumulating the results
-let result = rxs.iter().fold(0, |&:accum, rx| accum + rx.recv().unwrap() );
-# fn some_expensive_computation(_i: i32) -> i32 { 42 }
-```
-
-## Backgrounding computations: Futures
-
-With `sync::Future`, rust has a mechanism for requesting a computation and
-getting the result later.
-
-The basic example below illustrates this.
-
-```{rust,ignore}
-# #![allow(deprecated)]
-use std::sync::Future;
-
-# fn main() {
-# fn make_a_sandwich() {};
-fn fib(n: u64) -> u64 {
-    // lengthy computation returning an 64
-    12586269025
-}
-
-let mut delayed_fib = Future::spawn(move || fib(50));
-make_a_sandwich();
-println!("fib(50) = {}", delayed_fib.get())
-# }
-```
-
-The call to `future::spawn` immediately returns a `future` object regardless of
-how long it takes to run `fib(50)`. You can then make yourself a sandwich while
-the computation of `fib` is running. The result of the execution of the method
-is obtained by calling `get` on the future. This call will block until the
-value is available (*i.e.* the computation is complete). Note that the future
-needs to be mutable so that it can save the result for next time `get` is
-called.
-
-Here is another example showing how futures allow you to background
-computations. The workload will be distributed on the available cores.
-
-```{rust,ignore}
-# #![allow(deprecated)]
-# use std::num::Float;
-# use std::sync::Future;
-fn partial_sum(start: u64) -> f64 {
-    let mut local_sum = 0f64;
-    for num in range(start*100000, (start+1)*100000) {
-        local_sum += (num as f64 + 1.0).powf(-2.0);
-    }
-    local_sum
-}
-
-fn main() {
-    let mut futures = Vec::from_fn(200, |ind| Future::spawn(move || partial_sum(ind)));
-
-    let mut final_res = 0f64;
-    for ft in futures.iter_mut()  {
-        final_res += ft.get();
-    }
-    println!("π^2/6 is not far from : {}", final_res);
-}
-```
-
-## Sharing without copying: Arc
-
-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 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 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 thread needs the
-full vector to perform its duty.
-
-```{rust,ignore}
-use std::num::Float;
-use std::rand;
-use std::sync::Arc;
-
-fn pnorm(nums: &[f64], p: u64) -> f64 {
-    nums.iter().fold(0.0, |a, b| a + b.powf(p as f64)).powf(1.0 / (p as f64))
-}
-
-fn main() {
-    let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
-    let numbers_arc = Arc::new(numbers);
-
-    for num in range(1, 10) {
-        let thread_numbers = numbers_arc.clone();
-
-        spawn(move || {
-            println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
-        });
-    }
-}
-```
-
-The function `pnorm` performs a simple computation on the vector (it computes
-the sum of its items at the power given as argument and takes the inverse power
-of this value). The Arc on the vector is created by the line:
-
-```{rust,ignore}
-# use std::rand;
-# use std::sync::Arc;
-# fn main() {
-# let numbers = Vec::from_fn(1000000, |_| rand::random::<f64>());
-let numbers_arc = Arc::new(numbers);
-# }
-```
-
-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.
-
-```{rust,ignore}
-# use std::rand;
-# use std::sync::Arc;
-# fn pnorm(nums: &[f64], p: u64) -> f64 { 4.0 }
-# fn main() {
-# let numbers=Vec::from_fn(1000000, |_| rand::random::<f64>());
-# let numbers_arc = Arc::new(numbers);
-# let num = 4;
-let thread_numbers = numbers_arc.clone();
-spawn(move || {
-    // Capture thread_numbers and use it as if it was the underlying vector
-    println!("{}-norm = {}", num, pnorm(thread_numbers.as_slice(), num));
-});
-# }
-```
-
-# 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 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 thread: once a thread panics,
-there is no way to "catch" the exception.
-
-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 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 `i32`
-and `()`, callers can pattern-match on a result to check whether it's an `Ok`
-result with an `i32` field (representing a successful result) or an `Err` result
-(representing termination with an error).
-
-```{rust,ignore}
-# use std::thread::Thread;
-# fn some_condition() -> bool { false }
-# fn calculate_result() -> i32 { 0 }
-let result: Result<i32, Box<std::any::Any + Send>> = Thread::spawn(move || {
-    if some_condition() {
-        calculate_result()
-    } else {
-        panic!("oops!");
-    }
-}).join();
-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 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 thread does not currently produce a useful error
-> value (`try` always returns `Err(())`). In the
-> 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
-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 thread cannot proceed).
index 2bd86fa987f4be962bd3ec3086dd5ee2b8cf5b2e..b364d00f95c20b493640f3bd2e6d8f2cba024c44 100644 (file)
@@ -433,6 +433,7 @@ attribute attached to the crate.
 ```ignore
 // a minimal library
 #![crate_type="lib"]
+#![feature(no_std)]
 #![no_std]
 # // fn main() {} tricked you, rustdoc!
 ```
@@ -446,8 +447,8 @@ The function marked `#[start]` is passed the command line parameters
 in the same format as C:
 
 ```
+#![feature(lang_items, start, no_std)]
 #![no_std]
-#![feature(lang_items, start)]
 
 // Pull in the system libc library for what crt0.o likely requires
 extern crate libc;
@@ -473,6 +474,7 @@ correct ABI and the correct name, which requires overriding the
 compiler's name mangling too:
 
 ```ignore
+#![feature(no_std)]
 #![no_std]
 #![no_main]
 #![feature(lang_items, start)]
@@ -528,8 +530,8 @@ As an example, here is a program that will calculate the dot product of two
 vectors provided from C, using idiomatic Rust practices.
 
 ```
+#![feature(lang_items, start, no_std)]
 #![no_std]
-#![feature(lang_items, start)]
 
 # extern crate libc;
 extern crate core;
@@ -576,10 +578,6 @@ extern fn panic_fmt(args: &core::fmt::Arguments,
 #[lang = "eh_personality"] extern fn eh_personality() {}
 # #[start] fn start(argc: isize, argv: *const *const u8) -> isize { 0 }
 # fn main() {}
-# mod std {  // for-loops
-#     pub use core::iter;
-#     pub use core::option;
-# }
 ```
 
 Note that there is one extra lang item here which differs from the examples
@@ -656,8 +654,8 @@ and one for deallocation. A freestanding program that uses the `Box`
 sugar for dynamic allocations via `malloc` and `free`:
 
 ```
+#![feature(lang_items, box_syntax, start, no_std)]
 #![no_std]
-#![feature(lang_items, box_syntax, start)]
 
 extern crate libc;
 
index c940359abc118d8e0ef570c82fec5ccbab1572f7..7b11504f3cd8023b63c4948f7bb2a97f15f54b27 100644 (file)
@@ -15,6 +15,10 @@ import sys
 import os
 import re
 
+if len(sys.argv) < 2:
+    print "usage: errorck.py <src-dir>"
+    sys.exit(1)
+
 src_dir = sys.argv[1]
 errcode_map = {}
 error_re = re.compile("(E\d\d\d\d)")
@@ -54,8 +58,10 @@ for errcode, entries in errcode_map.items():
             print("{1}: {2}\n{3}".format(*entry))
         errors = True
 
-print("{0} error codes".format(len(errcode_map)))
-print("highest error code: " + max(all_errors))
+print
+print("* {0} error codes".format(len(errcode_map)))
+print("* highest error code: " + max(all_errors))
+print
 
 if errors:
     sys.exit(1)
index 064cf1d40ab36ce881aad53dad4d0ff841323284..ce972c91c8180a41d0cb6fffba7eff5aeadb82de 100644 (file)
 
 import sys, os, re
 
+if len(sys.argv) < 2:
+    print "usage: featurkck.py <src-dir>"
+    sys.exit(1)
+
 src_dir = sys.argv[1]
 
 # Features that are allowed to exist in both the language and the library
@@ -190,9 +194,9 @@ for name in lib_feature_stats:
         if not name in joint_features:
             print "error: feature '" + name + "' is both a lang and lib feature but not whitelisted"
             errors = True
-        lang_status = lang_feature_stats[name][3]
+        lang_status = language_feature_stats[name][3]
         lib_status = lib_feature_stats[name][3]
-        lang_stable_since = lang_feature_stats[name][4]
+        lang_stable_since = language_feature_stats[name][4]
         lib_stable_since = lib_feature_stats[name][4]
 
         if lang_status != lib_status and lib_status != "deprecated":
@@ -234,10 +238,8 @@ for s in stats:
 
 lines.sort()
 
-print
-print "Rust feature summary:"
 print
 for line in lines:
-    print line
+    print "* " + line
 print
 
index f38583ee1fb3774c8bf01c56304358b58992fe70..889b2c95a7ea88c5a740c8a4bfda2e607801d006 100644 (file)
@@ -22,11 +22,6 @@ u"""(#|//) Copyright .* The Rust Project Developers. See the COPYRIGHT
 \\1 except according to those terms.""")
 
 exceptions = [
-    "rt/rust_android_dummy.cpp", # BSD, chromium
-    "rt/rust_android_dummy.h", # BSD, chromium
-    "rt/isaac/randport.cpp", # public domain
-    "rt/isaac/rand.h", # public domain
-    "rt/isaac/standard.h", # public domain
     "libstd/sync/mpsc/mpsc_queue.rs", # BSD
     "libstd/sync/mpsc/spsc_queue.rs", # BSD
     "test/bench/shootout-binarytrees.rs", # BSD
index f5172feb5b60f1cb288973ae9459597cebaeea02..fd3309dce12cbd01e1c573e05beeddb096a7c2f1 100644 (file)
@@ -51,78 +51,155 @@ def do_license_check(name, contents):
     if not check_license(name, contents):
         report_error_name_no(name, 1, "incorrect license")
 
-
-file_names = [s for s in sys.argv[1:] if (not s.endswith("_gen.rs"))
-                                     and (not ".#" in s)]
-
 current_name = ""
 current_contents = ""
 check_tab = True
 check_cr = True
 check_linelength = True
 
+if len(sys.argv) < 2:
+    print "usage: tidy.py <src-dir>"
+    sys.exit(1)
+
+src_dir = sys.argv[1]
 
 try:
-    for line in fileinput.input(file_names,
+    count_lines = 0
+    count_non_blank_lines = 0
+
+    interesting_files = ['.rs', '.py', '.js', '.sh', '.c', '.h']
+
+    file_counts = {ext: 0 for ext in interesting_files}
+    file_counts['other'] = 0
+
+    def update_counts(current_name):
+        global file_counts
+        _, ext = os.path.splitext(current_name)
+
+        if ext in file_counts:
+            file_counts[ext] += 1
+        else:
+            file_counts['other'] += 1
+
+    all_paths = set()
+
+    for (dirpath, dirnames, filenames) in os.walk(src_dir):
+
+        # Skip some third-party directories
+        skippable_dirs = {
+            'src/jemalloc',
+            'src/llvm',
+            'src/gyp',
+            'src/libbacktrace',
+            'src/libuv',
+            'src/compiler-rt',
+            'src/rt/hoedown',
+            'src/rustllvm',
+            'src/rt/valgrind',
+            'src/rt/msvc',
+            'src/rust-installer'
+        }
+
+        if any(d in dirpath for d in skippable_dirs):
+            continue
+
+        def interesting_file(f):
+            if "miniz.c" in f \
+            or "jquery" in f \
+            or "rust_android_dummy" in f:
+                return False
+
+            return any(os.path.splitext(f)[1] == ext for ext in interesting_files)
+
+        file_names = [os.path.join(dirpath, f) for f in filenames
+                      if interesting_file(f)
+                      and not f.endswith("_gen.rs")
+                      and not ".#" is f]
+
+        if not file_names:
+            continue
+
+        for line in fileinput.input(file_names,
                                 openhook=fileinput.hook_encoded("utf-8")):
 
-        if "tidy.py" not in fileinput.filename():
+            filename = fileinput.filename()
+
+            if "tidy.py" not in filename:
+                if "TODO" in line:
+                    report_err("TODO is deprecated; use FIXME")
+                match = re.match(r'^.*/(\*|/!?)\s*XXX', line)
+                if match:
+                    report_err("XXX is no longer necessary, use FIXME")
+                match = re.match(r'^.*//\s*(NOTE.*)$', line)
+                if match and "TRAVIS" not in os.environ:
+                    m = match.group(1)
+                    if "snap" in m.lower():
+                        report_warn(match.group(1))
+                match = re.match(r'^.*//\s*SNAP\s+(\w+)', line)
+                if match:
+                    hsh = match.group(1)
+                    date, rev = snapshot.curr_snapshot_rev()
+                    if not hsh.startswith(rev):
+                        report_err("snapshot out of date (" + date
+                            + "): " + line)
+                else:
+                    if "SNAP" in line:
+                        report_warn("unmatched SNAP line: " + line)
+
             if cr_flag in line:
                 check_cr = False
             if tab_flag in line:
                 check_tab = False
             if linelength_flag in line:
                 check_linelength = False
-            if "TODO" in line:
-                report_err("TODO is deprecated; use FIXME")
-            match = re.match(r'^.*/(\*|/!?)\s*XXX', line)
-            if match:
-                report_err("XXX is no longer necessary, use FIXME")
-            match = re.match(r'^.*//\s*(NOTE.*)$', line)
-            if match and "TRAVIS" not in os.environ:
-                m = match.group(1)
-                if "snap" in m.lower():
-                    report_warn(match.group(1))
-            match = re.match(r'^.*//\s*SNAP\s+(\w+)', line)
-            if match:
-                hsh = match.group(1)
-                date, rev = snapshot.curr_snapshot_rev()
-                if not hsh.startswith(rev):
-                    report_err("snapshot out of date (" + date
-                               + "): " + line)
-            else:
-                if "SNAP" in line:
-                    report_warn("unmatched SNAP line: " + line)
-
-        if check_tab and ('\t' in line and
-                          "Makefile" not in fileinput.filename()):
-            report_err("tab character")
-        if check_cr and not autocrlf and '\r' in line:
-            report_err("CR character")
-        if line.endswith(" \n") or line.endswith("\t\n"):
-            report_err("trailing whitespace")
-        line_len = len(line)-2 if autocrlf else len(line)-1
-
-        if check_linelength and line_len > cols:
-            report_err("line longer than %d chars" % cols)
-
-        if fileinput.isfirstline() and current_name != "":
-            do_license_check(current_name, current_contents)
-
-        if fileinput.isfirstline():
-            current_name = fileinput.filename()
-            current_contents = ""
-            check_cr = True
-            check_tab = True
-            check_linelength = True
-
-        current_contents += line
+
+            if check_tab and ('\t' in line and
+                              "Makefile" not in filename):
+                report_err("tab character")
+            if check_cr and not autocrlf and '\r' in line:
+                report_err("CR character")
+            if line.endswith(" \n") or line.endswith("\t\n"):
+                report_err("trailing whitespace")
+            line_len = len(line)-2 if autocrlf else len(line)-1
+
+            if check_linelength and line_len > cols:
+                report_err("line longer than %d chars" % cols)
+
+            if fileinput.isfirstline():
+                # This happens at the end of each file except the last.
+                if current_name != "":
+                    update_counts(current_name)
+                    assert len(current_contents) > 0
+                    do_license_check(current_name, current_contents)
+
+                current_name = filename
+                current_contents = ""
+                check_cr = True
+                check_tab = True
+                check_linelength = True
+
+            # Put a reasonable limit on the amount of header data we use for
+            # the licenseck
+            if len(current_contents) < 1000:
+                current_contents += line
+
+            count_lines += 1
+            if line.strip():
+                count_non_blank_lines += 1
 
     if current_name != "":
+        update_counts(current_name)
+        assert len(current_contents) > 0
         do_license_check(current_name, current_contents)
 
 except UnicodeDecodeError as e:
     report_err("UTF-8 decoding error " + str(e))
 
+print
+for ext in file_counts:
+    print "* linted " + str(file_counts[ext]) + " " + ext + " files"
+print "* total lines of code: " + str(count_lines)
+print "* total non-blank lines of code: " + str(count_non_blank_lines)
+print
 
 sys.exit(err)
index cb269bbdb0ade0dc343bc3513bc9ce82698a0119..b5be3daa13e1d01b4f294f61b81b94f42dc1011f 100755 (executable)
@@ -1,5 +1,7 @@
 #!/bin/sh
 
+# ignore-license
+
 # Run the reference lexer against libsyntax and compare the tokens and spans.
 # If "// ignore-lexer-test" is present in the file, it will be ignored.
 
index 24185ed65d5c50df01c13d95783a97c63387121a..d3d3a2b997c994a2786880e82703f50462630cd2 100644 (file)
@@ -1195,7 +1195,7 @@ maybe_stmts
 //
 // There are also two other expr subtypes: first, nonparen_expr
 // disallows exprs surrounded by parens (including tuple expressions),
-// this is neccesary for BOX (place) expressions, so a parens expr
+// this is necessary for BOX (place) expressions, so a parens expr
 // following the BOX is always parsed as the place. There is also
 // expr_norange used in index_expr, which disallows '..' in
 // expressions as that has special meaning inside of brackets.
index 38e57be288b240f3d2b4e780ac02a6f9aa3ef803..37be41b935f84b4e1434ba9f76d8aa8b25ed4c98 100755 (executable)
@@ -9,6 +9,9 @@
 # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 # option. This file may not be copied, modified, or distributed
 # except according to those terms.
+
+# ignore-tidy-linelength
+
 import sys
 
 import os
@@ -32,34 +35,42 @@ for parser in args.parser:
     ok[parser] = 0
     bad[parser] = []
 devnull = open(os.devnull, 'w')
-print "\n"
+print("\n")
 
 for base, dirs, files in os.walk(args.source_dir[0]):
     for f in filter(lambda p: p.endswith('.rs'), files):
         p = os.path.join(base, f)
-        compile_fail = 'compile-fail' in p
-        ignore = any('ignore-test' in line or 'ignore-lexer-test' in line
-                     for line in open(p).readlines())
-        if compile_fail or ignore:
+        parse_fail = 'parse-fail' in p
+        if sys.version_info.major == 3:
+            lines = open(p, encoding='utf-8').readlines()
+        else:
+            lines = open(p).readlines()
+        if any('ignore-test' in line or 'ignore-lexer-test' in line for line in lines):
             continue
         total += 1
         for parser in args.parser:
             if subprocess.call(parser, stdin=open(p), stderr=subprocess.STDOUT, stdout=devnull) == 0:
-                ok[parser] += 1
+                if parse_fail:
+                    bad[parser].append(p)
+                else:
+                    ok[parser] += 1
             else:
-                bad[parser].append(p)
+                if parse_fail:
+                    ok[parser] += 1
+                else:
+                    bad[parser].append(p)
         parser_stats = ', '.join(['{}: {}'.format(parser, ok[parser]) for parser in args.parser])
         sys.stdout.write("\033[K\r total: {}, {}, scanned {}"
                          .format(total, os.path.relpath(parser_stats), os.path.relpath(p)))
 
 devnull.close()
 
-print "\n"
+print("\n")
 
 for parser in args.parser:
     filename = os.path.basename(parser) + '.bad'
-    print("writing {} files that failed to parse with {} to {}".format(len(bad[parser]), parser, filename))
+    print("writing {} files that did not yield the correct result with {} to {}".format(len(bad[parser]), parser, filename))
     with open(filename, "w") as f:
-          for p in bad[parser]:
-              f.write(p)
-              f.write("\n")
+        for p in bad[parser]:
+            f.write(p)
+            f.write("\n")
index bb72b066e0963022a85117ba4557fdc5c491b536..75b56f54cccc79efc4a5c48f8bd246b8fc986960 100644 (file)
@@ -179,7 +179,7 @@ fn parse_antlr_token(s: &str, tokens: &HashMap<String, token::Token>) -> TokenAn
     let toknum = &s[content_end + 3 .. toknum_end];
 
     let proto_tok = tokens.get(toknum).expect(format!("didn't find token {:?} in the map",
-                                                              toknum).as_slice());
+                                                              toknum));
 
     let nm = parse::token::intern(content);
 
@@ -242,8 +242,8 @@ fn next(r: &mut lexer::StringReader) -> TokenAndSpan {
 
     let args = std::os::args();
 
-    let mut token_file = File::open(&Path::new(args[2].as_slice()));
-    let token_map = parse_token_list(token_file.read_to_string().unwrap().as_slice());
+    let mut token_file = File::open(&Path::new(args[2]));
+    let token_map = parse_token_list(token_file.read_to_string().unwrap());
 
     let mut stdin = std::io::stdin();
     let mut lock = stdin.lock();
@@ -251,7 +251,7 @@ fn next(r: &mut lexer::StringReader) -> TokenAndSpan {
     let mut antlr_tokens = lines.map(|l| parse_antlr_token(l.unwrap().trim(),
                                                                    &token_map));
 
-    let code = File::open(&Path::new(args[1].as_slice())).unwrap().read_to_string().unwrap();
+    let code = File::open(&Path::new(args[1])).unwrap().read_to_string().unwrap();
     let options = config::basic_options();
     let session = session::build_session(options, None,
                                          syntax::diagnostics::registry::Registry::new(&[]));
index 21b9c060f6f3bea330c797f205833a77154c374c..24b4abbff4ae26527c8785993b219819d0e59c9c 100644 (file)
@@ -311,7 +311,7 @@ impl<T: Sync + Send> Drop for Arc<T> {
     ///
     ///     // stuff
     ///
-    ///     drop(five); // explict drop
+    ///     drop(five); // explicit drop
     /// }
     /// {
     ///     let five = Arc::new(5);
@@ -441,7 +441,7 @@ impl<T: Sync + Send> Drop for Weak<T> {
     ///
     ///     // stuff
     ///
-    ///     drop(weak_five); // explict drop
+    ///     drop(weak_five); // explicit drop
     /// }
     /// {
     ///     let five = Arc::new(5);
index 99423349020393721ac3b32c6d7de92ec7e85dc9..81391fd63eb85cb2a14532dc2409a41ab088ab42 100644 (file)
@@ -65,6 +65,7 @@
        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
        html_root_url = "http://doc.rust-lang.org/nightly/")]
 
+#![feature(no_std)]
 #![no_std]
 #![feature(lang_items, unsafe_destructor)]
 #![feature(box_syntax)]
@@ -73,7 +74,9 @@
 #![feature(unboxed_closures)]
 #![feature(core)]
 #![feature(hash)]
-#![feature(libc)]
+#![cfg_attr(all(not(feature = "external_funcs"), not(feature = "external_crate")),
+            feature(libc))]
+
 
 #[macro_use]
 extern crate core;
@@ -124,7 +127,8 @@ pub fn oom() -> ! {
 #[doc(hidden)]
 pub fn fixme_14344_be_sure_to_link_to_collections() {}
 
-#[cfg(not(test))]
+// NOTE: remove after next snapshot
+#[cfg(all(stage0, not(test)))]
 #[doc(hidden)]
 mod std {
     pub use core::fmt;
index 464f20e9cac53f03df5344363567837614a4d0f2..54ff4c1865472ee1656d81c432db56a22447bf50 100644 (file)
 use core::ptr::{self, PtrExt};
 use core::result::Result;
 use core::result::Result::{Ok, Err};
+use core::intrinsics::assume;
 
 use heap::deallocate;
 
@@ -171,7 +172,7 @@ struct RcBox<T> {
 
 /// An immutable reference-counted pointer type.
 ///
-/// See the [module level documentation](../index.html) for more details.
+/// See the [module level documentation](./index.html) for more details.
 #[unsafe_no_drop_flag]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Rc<T> {
@@ -382,7 +383,7 @@ impl<T> Drop for Rc<T> {
     ///
     ///     // stuff
     ///
-    ///     drop(five); // explict drop
+    ///     drop(five); // explicit drop
     /// }
     /// {
     ///     let five = Rc::new(5);
@@ -623,7 +624,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 ///
 /// Weak references do not count when determining if the inner value should be dropped.
 ///
-/// See the [module level documentation](../index.html) for more.
+/// See the [module level documentation](./index.html) for more.
 #[unsafe_no_drop_flag]
 #[unstable(feature = "alloc",
            reason = "Weak pointers may not belong in this module.")]
@@ -687,7 +688,7 @@ impl<T> Drop for Weak<T> {
     ///
     ///     // stuff
     ///
-    ///     drop(weak_five); // explict drop
+    ///     drop(weak_five); // explicit drop
     /// }
     /// {
     ///     let five = Rc::new(5);
@@ -769,12 +770,34 @@ fn weak(&self) -> uint { self.inner().weak.get() }
 
 impl<T> RcBoxPtr<T> for Rc<T> {
     #[inline(always)]
-    fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
+    fn inner(&self) -> &RcBox<T> {
+        unsafe {
+            // Safe to assume this here, as if it weren't true, we'd be breaking
+            // the contract anyway.
+            // This allows the null check to be elided in the destructor if we
+            // manipulated the reference count in the same function.
+            if cfg!(not(stage0)) { // NOTE remove cfg after next snapshot
+                assume(!self._ptr.is_null());
+            }
+            &(**self._ptr)
+        }
+    }
 }
 
 impl<T> RcBoxPtr<T> for Weak<T> {
     #[inline(always)]
-    fn inner(&self) -> &RcBox<T> { unsafe { &(**self._ptr) } }
+    fn inner(&self) -> &RcBox<T> {
+        unsafe {
+            // Safe to assume this here, as if it weren't true, we'd be breaking
+            // the contract anyway.
+            // This allows the null check to be elided in the destructor if we
+            // manipulated the reference count in the same function.
+            if cfg!(not(stage0)) { // NOTE remove cfg after next snapshot
+                assume(!self._ptr.is_null());
+            }
+            &(**self._ptr)
+        }
+    }
 }
 
 #[cfg(test)]
index 9301bf5e4ab47c701a57ef29f3a91fbbc868c10e..b0a5911720a40aa384c75374604c84b7c0d42967 100644 (file)
 use std::rand::Rng;
 use test::{Bencher, black_box};
 
-pub fn insert_rand_n<M, I, R>(n: uint,
+pub fn insert_rand_n<M, I, R>(n: usize,
                               map: &mut M,
                               b: &mut Bencher,
                               mut insert: I,
                               mut remove: R) where
-    I: FnMut(&mut M, uint),
-    R: FnMut(&mut M, uint),
+    I: FnMut(&mut M, usize),
+    R: FnMut(&mut M, usize),
 {
     // setup
     let mut rng = rand::weak_rng();
 
     for _ in 0..n {
-        insert(map, rng.gen::<uint>() % n);
+        insert(map, rng.gen::<usize>() % n);
     }
 
     // measure
     b.iter(|| {
-        let k = rng.gen::<uint>() % n;
+        let k = rng.gen::<usize>() % n;
         insert(map, k);
         remove(map, k);
     });
     black_box(map);
 }
 
-pub fn insert_seq_n<M, I, R>(n: uint,
+pub fn insert_seq_n<M, I, R>(n: usize,
                              map: &mut M,
                              b: &mut Bencher,
                              mut insert: I,
                              mut remove: R) where
-    I: FnMut(&mut M, uint),
-    R: FnMut(&mut M, uint),
+    I: FnMut(&mut M, usize),
+    R: FnMut(&mut M, usize),
 {
     // setup
-    for i in 0u..n {
+    for i in 0..n {
         insert(map, i * 2);
     }
 
@@ -60,24 +60,23 @@ pub fn insert_seq_n<M, I, R>(n: uint,
     black_box(map);
 }
 
-pub fn find_rand_n<M, T, I, F>(n: uint,
+pub fn find_rand_n<M, T, I, F>(n: usize,
                                map: &mut M,
                                b: &mut Bencher,
                                mut insert: I,
                                mut find: F) where
-    I: FnMut(&mut M, uint),
-    F: FnMut(&M, uint) -> T,
+    I: FnMut(&mut M, usize),
+    F: FnMut(&M, usize) -> T,
 {
     // setup
     let mut rng = rand::weak_rng();
-    let mut keys = (0..n).map(|_| rng.gen::<uint>() % n)
-                              .collect::<Vec<_>>();
+    let mut keys: Vec<_> = (0..n).map(|_| rng.gen::<usize>() % n).collect();
 
     for k in &keys {
         insert(map, *k);
     }
 
-    rng.shuffle(keys.as_mut_slice());
+    rng.shuffle(&mut keys);
 
     // measure
     let mut i = 0;
@@ -88,16 +87,16 @@ pub fn find_rand_n<M, T, I, F>(n: uint,
     })
 }
 
-pub fn find_seq_n<M, T, I, F>(n: uint,
+pub fn find_seq_n<M, T, I, F>(n: usize,
                               map: &mut M,
                               b: &mut Bencher,
                               mut insert: I,
                               mut find: F) where
-    I: FnMut(&mut M, uint),
-    F: FnMut(&M, uint) -> T,
+    I: FnMut(&mut M, usize),
+    F: FnMut(&M, usize) -> T,
 {
     // setup
-    for i in 0u..n {
+    for i in 0..n {
         insert(map, i);
     }
 
index b51ec13335e0eb721ef52d8a73f5d90e0ab5cb0b..275fc34f8132659c3c35bfc381d7755e45168bc7 100644 (file)
 //! ```
 //! use std::cmp::Ordering;
 //! use std::collections::BinaryHeap;
-//! use std::uint;
+//! use std::usize;
 //!
 //! #[derive(Copy, Eq, PartialEq)]
 //! struct State {
-//!     cost: uint,
-//!     position: uint,
+//!     cost: usize,
+//!     position: usize,
 //! }
 //!
 //! // The priority queue depends on `Ord`.
 //!     }
 //! }
 //!
-//! // Each node is represented as an `uint`, for a shorter implementation.
+//! // Each node is represented as an `usize`, for a shorter implementation.
 //! struct Edge {
-//!     node: uint,
-//!     cost: uint,
+//!     node: usize,
+//!     cost: usize,
 //! }
 //!
 //! // Dijkstra's shortest path algorithm.
 //!
 //! // Start at `start` and use `dist` to track the current shortest distance
 //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
-//! // nodes in the queue. It also uses `uint::MAX` as a sentinel value,
+//! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
 //! // for a simpler implementation.
-//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: uint, goal: uint) -> uint {
+//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> usize {
 //!     // dist[node] = current shortest distance from `start` to `node`
-//!     let mut dist: Vec<_> = (0..adj_list.len()).map(|_| uint::MAX).collect();
+//!     let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
 //!
 //!     let mut heap = BinaryHeap::new();
 //!
@@ -98,7 +98,7 @@
 //!     }
 //!
 //!     // Goal not reachable
-//!     uint::MAX
+//!     usize::MAX
 //! }
 //!
 //! fn main() {
 //!     assert_eq!(shortest_path(&graph, 0, 3), 3);
 //!     assert_eq!(shortest_path(&graph, 3, 0), 7);
 //!     assert_eq!(shortest_path(&graph, 0, 4), 5);
-//!     assert_eq!(shortest_path(&graph, 4, 0), uint::MAX);
+//!     assert_eq!(shortest_path(&graph, 4, 0), usize::MAX);
 //! }
 //! ```
 
@@ -183,7 +183,7 @@ impl<T: Ord> BinaryHeap<T> {
     /// ```
     /// use std::collections::BinaryHeap;
     /// let mut heap = BinaryHeap::new();
-    /// heap.push(4u);
+    /// heap.push(4);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
@@ -198,10 +198,10 @@ pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
     /// ```
     /// use std::collections::BinaryHeap;
     /// let mut heap = BinaryHeap::with_capacity(10);
-    /// heap.push(4u);
+    /// heap.push(4);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(capacity: uint) -> BinaryHeap<T> {
+    pub fn with_capacity(capacity: usize) -> BinaryHeap<T> {
         BinaryHeap { data: Vec::with_capacity(capacity) }
     }
 
@@ -292,10 +292,10 @@ pub fn peek(&self) -> Option<&T> {
     /// use std::collections::BinaryHeap;
     /// let mut heap = BinaryHeap::with_capacity(100);
     /// assert!(heap.capacity() >= 100);
-    /// heap.push(4u);
+    /// heap.push(4);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint { self.data.capacity() }
+    pub fn capacity(&self) -> usize { self.data.capacity() }
 
     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
     /// given `BinaryHeap`. Does nothing if the capacity is already sufficient.
@@ -306,7 +306,7 @@ pub fn capacity(&self) -> uint { self.data.capacity() }
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -315,10 +315,10 @@ pub fn capacity(&self) -> uint { self.data.capacity() }
     /// let mut heap = BinaryHeap::new();
     /// heap.reserve_exact(100);
     /// assert!(heap.capacity() >= 100);
-    /// heap.push(4u);
+    /// heap.push(4);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_exact(&mut self, additional: uint) {
+    pub fn reserve_exact(&mut self, additional: usize) {
         self.data.reserve_exact(additional);
     }
 
@@ -327,7 +327,7 @@ pub fn reserve_exact(&mut self, additional: uint) {
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -336,10 +336,10 @@ pub fn reserve_exact(&mut self, additional: uint) {
     /// let mut heap = BinaryHeap::new();
     /// heap.reserve(100);
     /// assert!(heap.capacity() >= 100);
-    /// heap.push(4u);
+    /// heap.push(4);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve(&mut self, additional: uint) {
+    pub fn reserve(&mut self, additional: usize) {
         self.data.reserve(additional);
     }
 
@@ -497,7 +497,7 @@ pub fn into_sorted_vec(mut self) -> Vec<T> {
     // zeroed element), shift along the others and move it back into the
     // vector over the junk element. This reduces the constant factor
     // compared to using swaps, which involves twice as many moves.
-    fn sift_up(&mut self, start: uint, mut pos: uint) {
+    fn sift_up(&mut self, start: usize, mut pos: usize) {
         unsafe {
             let new = replace(&mut self.data[pos], zeroed());
 
@@ -514,7 +514,7 @@ fn sift_up(&mut self, start: uint, mut pos: uint) {
         }
     }
 
-    fn sift_down_range(&mut self, mut pos: uint, end: uint) {
+    fn sift_down_range(&mut self, mut pos: usize, end: usize) {
         unsafe {
             let start = pos;
             let new = replace(&mut self.data[pos], zeroed());
@@ -536,14 +536,14 @@ fn sift_down_range(&mut self, mut pos: uint, end: uint) {
         }
     }
 
-    fn sift_down(&mut self, pos: uint) {
+    fn sift_down(&mut self, pos: usize) {
         let len = self.len();
         self.sift_down_range(pos, len);
     }
 
     /// Returns the length of the binary heap.
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { self.data.len() }
+    pub fn len(&self) -> usize { self.data.len() }
 
     /// Checks if the binary heap is empty.
     #[stable(feature = "rust1", since = "1.0.0")]
@@ -584,7 +584,7 @@ impl<'a, T> Iterator for Iter<'a, T> {
     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -610,7 +610,7 @@ impl<T> Iterator for IntoIter<T> {
     fn next(&mut self) -> Option<T> { self.iter.next() }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -636,7 +636,7 @@ impl<'a, T: 'a> Iterator for Drain<'a, T> {
     fn next(&mut self) -> Option<T> { self.iter.next() }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -692,7 +692,7 @@ mod tests {
 
     #[test]
     fn test_iterator() {
-        let data = vec!(5, 9, 3);
+        let data = vec![5, 9, 3];
         let iterout = [9, 5, 3];
         let heap = BinaryHeap::from_vec(data);
         let mut i = 0;
@@ -704,27 +704,27 @@ fn test_iterator() {
 
     #[test]
     fn test_iterator_reverse() {
-        let data = vec!(5, 9, 3);
-        let iterout = vec!(3, 5, 9);
+        let data = vec![5, 9, 3];
+        let iterout = vec![3, 5, 9];
         let pq = BinaryHeap::from_vec(data);
 
-        let v: Vec<int> = pq.iter().rev().map(|&x| x).collect();
+        let v: Vec<_> = pq.iter().rev().cloned().collect();
         assert_eq!(v, iterout);
     }
 
     #[test]
     fn test_move_iter() {
-        let data = vec!(5, 9, 3);
-        let iterout = vec!(9, 5, 3);
+        let data = vec![5, 9, 3];
+        let iterout = vec![9, 5, 3];
         let pq = BinaryHeap::from_vec(data);
 
-        let v: Vec<int> = pq.into_iter().collect();
+        let v: Vec<_> = pq.into_iter().collect();
         assert_eq!(v, iterout);
     }
 
     #[test]
     fn test_move_iter_size_hint() {
-        let data = vec!(5, 9);
+        let data = vec![5, 9];
         let pq = BinaryHeap::from_vec(data);
 
         let mut it = pq.into_iter();
@@ -741,17 +741,17 @@ fn test_move_iter_size_hint() {
 
     #[test]
     fn test_move_iter_reverse() {
-        let data = vec!(5, 9, 3);
-        let iterout = vec!(3, 5, 9);
+        let data = vec![5, 9, 3];
+        let iterout = vec![3, 5, 9];
         let pq = BinaryHeap::from_vec(data);
 
-        let v: Vec<int> = pq.into_iter().rev().collect();
+        let v: Vec<_> = pq.into_iter().rev().collect();
         assert_eq!(v, iterout);
     }
 
     #[test]
     fn test_peek_and_pop() {
-        let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
+        let data = vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1];
         let mut sorted = data.clone();
         sorted.sort();
         let mut heap = BinaryHeap::from_vec(data);
@@ -763,7 +763,7 @@ fn test_peek_and_pop() {
 
     #[test]
     fn test_push() {
-        let mut heap = BinaryHeap::from_vec(vec!(2, 4, 9));
+        let mut heap = BinaryHeap::from_vec(vec![2, 4, 9]);
         assert_eq!(heap.len(), 3);
         assert!(*heap.peek().unwrap() == 9);
         heap.push(11);
@@ -785,7 +785,7 @@ fn test_push() {
 
     #[test]
     fn test_push_unique() {
-        let mut heap = BinaryHeap::from_vec(vec!(box 2, box 4, box 9));
+        let mut heap = BinaryHeap::from_vec(vec![box 2, box 4, box 9]);
         assert_eq!(heap.len(), 3);
         assert!(*heap.peek().unwrap() == box 9);
         heap.push(box 11);
@@ -807,7 +807,7 @@ fn test_push_unique() {
 
     #[test]
     fn test_push_pop() {
-        let mut heap = BinaryHeap::from_vec(vec!(5, 5, 2, 1, 3));
+        let mut heap = BinaryHeap::from_vec(vec![5, 5, 2, 1, 3]);
         assert_eq!(heap.len(), 5);
         assert_eq!(heap.push_pop(6), 6);
         assert_eq!(heap.len(), 5);
@@ -821,7 +821,7 @@ fn test_push_pop() {
 
     #[test]
     fn test_replace() {
-        let mut heap = BinaryHeap::from_vec(vec!(5, 5, 2, 1, 3));
+        let mut heap = BinaryHeap::from_vec(vec![5, 5, 2, 1, 3]);
         assert_eq!(heap.len(), 5);
         assert_eq!(heap.replace(6).unwrap(), 5);
         assert_eq!(heap.len(), 5);
@@ -833,7 +833,7 @@ fn test_replace() {
         assert_eq!(heap.len(), 5);
     }
 
-    fn check_to_vec(mut data: Vec<int>) {
+    fn check_to_vec(mut data: Vec<i32>) {
         let heap = BinaryHeap::from_vec(data.clone());
         let mut v = heap.clone().into_vec();
         v.sort();
@@ -845,44 +845,44 @@ fn check_to_vec(mut data: Vec<int>) {
 
     #[test]
     fn test_to_vec() {
-        check_to_vec(vec!());
-        check_to_vec(vec!(5));
-        check_to_vec(vec!(3, 2));
-        check_to_vec(vec!(2, 3));
-        check_to_vec(vec!(5, 1, 2));
-        check_to_vec(vec!(1, 100, 2, 3));
-        check_to_vec(vec!(1, 3, 5, 7, 9, 2, 4, 6, 8, 0));
-        check_to_vec(vec!(2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
-        check_to_vec(vec!(9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
-        check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
-        check_to_vec(vec!(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
-        check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
-        check_to_vec(vec!(5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
+        check_to_vec(vec![]);
+        check_to_vec(vec![5]);
+        check_to_vec(vec![3, 2]);
+        check_to_vec(vec![2, 3]);
+        check_to_vec(vec![5, 1, 2]);
+        check_to_vec(vec![1, 100, 2, 3]);
+        check_to_vec(vec![1, 3, 5, 7, 9, 2, 4, 6, 8, 0]);
+        check_to_vec(vec![2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1]);
+        check_to_vec(vec![9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0]);
+        check_to_vec(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+        check_to_vec(vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
+        check_to_vec(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2]);
+        check_to_vec(vec![5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]);
     }
 
     #[test]
     fn test_empty_pop() {
-        let mut heap = BinaryHeap::<int>::new();
+        let mut heap = BinaryHeap::<i32>::new();
         assert!(heap.pop().is_none());
     }
 
     #[test]
     fn test_empty_peek() {
-        let empty = BinaryHeap::<int>::new();
+        let empty = BinaryHeap::<i32>::new();
         assert!(empty.peek().is_none());
     }
 
     #[test]
     fn test_empty_replace() {
-        let mut heap = BinaryHeap::<int>::new();
+        let mut heap = BinaryHeap::new();
         assert!(heap.replace(5).is_none());
     }
 
     #[test]
     fn test_from_iter() {
-        let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
+        let xs = vec![9, 8, 7, 6, 5, 4, 3, 2, 1];
 
-        let mut q: BinaryHeap<uint> = xs.iter().rev().map(|&x| x).collect();
+        let mut q: BinaryHeap<_> = xs.iter().rev().cloned().collect();
 
         for &x in &xs {
             assert_eq!(q.pop().unwrap(), x);
@@ -891,8 +891,7 @@ fn test_from_iter() {
 
     #[test]
     fn test_drain() {
-        let mut q: BinaryHeap<_> =
-            [9u, 8, 7, 6, 5, 4, 3, 2, 1].iter().cloned().collect();
+        let mut q: BinaryHeap<_> = [9, 8, 7, 6, 5, 4, 3, 2, 1].iter().cloned().collect();
 
         assert_eq!(q.drain().take(5).count(), 5);
 
index 3e603f6ebaf86862703e047e0d2ccca269cdfb40..8ba0eb9b7efe5180e5e9d3236796b0af26ab1a03 100644 (file)
@@ -18,7 +18,7 @@
 // rather `or` and `and`.
 
 // (1) Be careful, most things can overflow here because the amount of bits in
-//     memory can overflow `uint`.
+//     memory can overflow `usize`.
 // (2) Make sure that the underlying vector has no excess length:
 //     E. g. `nbits == 16`, `storage.len() == 2` would be excess length,
 //     because the last word isn't used at all. This is important because some
@@ -54,7 +54,7 @@
 //!     bv.set(0, false);
 //!     bv.set(1, false);
 //!
-//!     for i in iter::range_inclusive(2, (max_prime as f64).sqrt() as uint) {
+//!     for i in iter::range_inclusive(2, (max_prime as f64).sqrt() as usize) {
 //!         // if i is a prime
 //!         if bv[i] {
 //!             // Mark all multiples of i as non-prime (any multiples below i * i
@@ -66,7 +66,7 @@
 //! };
 //!
 //! // Simple primality tests below our max bound
-//! let print_primes = 20u;
+//! let print_primes = 20;
 //! print!("The primes below {} are: ", print_primes);
 //! for x in 0..print_primes {
 //!     if primes.contains(&x) {
@@ -93,7 +93,7 @@
 use core::num::Int;
 use core::ops::Index;
 use core::slice;
-use core::{u8, u32, uint};
+use core::{u8, u32, usize};
 use bitv_set; //so meta
 
 use Vec;
@@ -162,15 +162,15 @@ pub struct Bitv {
     /// Internal representation of the bit vector
     storage: Vec<u32>,
     /// The number of valid bits in the internal representation
-    nbits: uint
+    nbits: usize
 }
 
 // FIXME(Gankro): NopeNopeNopeNopeNope (wait for IndexGet to be a thing)
-impl Index<uint> for Bitv {
+impl Index<usize> for Bitv {
     type Output = bool;
 
     #[inline]
-    fn index(&self, i: &uint) -> &bool {
+    fn index(&self, i: &usize) -> &bool {
         if self.get(*i).expect("index out of bounds") {
             &TRUE
         } else {
@@ -180,7 +180,7 @@ fn index(&self, i: &uint) -> &bool {
 }
 
 /// Computes how many blocks are needed to store that many bits
-fn blocks_for_bits(bits: uint) -> uint {
+fn blocks_for_bits(bits: usize) -> usize {
     // If we want 17 bits, dividing by 32 will produce 0. So we add 1 to make sure we
     // reserve enough. But if we want exactly a multiple of 32, this will actually allocate
     // one too many. So we need to check if that's the case. We can do that by computing if
@@ -188,7 +188,7 @@ fn blocks_for_bits(bits: uint) -> uint {
     // superior modulo operator on a power of two to this.
     //
     // Note that we can technically avoid this branch with the expression
-    // `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost uint::MAX this will overflow.
+    // `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
     if bits % u32::BITS == 0 {
         bits / u32::BITS
     } else {
@@ -197,7 +197,7 @@ fn blocks_for_bits(bits: uint) -> uint {
 }
 
 /// Computes the bitmask for the final word of the vector
-fn mask_for_bits(bits: uint) -> u32 {
+fn mask_for_bits(bits: usize) -> u32 {
     // Note especially that a perfect multiple of u32::BITS should mask all 1s.
     !0u32 >> (u32::BITS - bits % u32::BITS) % u32::BITS
 }
@@ -266,13 +266,13 @@ pub fn new() -> Bitv {
     /// ```
     /// use std::collections::Bitv;
     ///
-    /// let mut bv = Bitv::from_elem(10u, false);
-    /// assert_eq!(bv.len(), 10u);
+    /// let mut bv = Bitv::from_elem(10, false);
+    /// assert_eq!(bv.len(), 10);
     /// for x in bv.iter() {
     ///     assert_eq!(x, false);
     /// }
     /// ```
-    pub fn from_elem(nbits: uint, bit: bool) -> Bitv {
+    pub fn from_elem(nbits: usize, bit: bool) -> Bitv {
         let nblocks = blocks_for_bits(nbits);
         let mut bitv = Bitv {
             storage: repeat(if bit { !0u32 } else { 0u32 }).take(nblocks).collect(),
@@ -290,7 +290,7 @@ pub fn from_elem(nbits: uint, bit: bool) -> Bitv {
     /// It is important to note that this function does not specify the
     /// *length* of the returned bitvector, but only the *capacity*.
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(nbits: uint) -> Bitv {
+    pub fn with_capacity(nbits: usize) -> Bitv {
         Bitv {
             storage: Vec::with_capacity(blocks_for_bits(nbits)),
             nbits: 0,
@@ -351,9 +351,9 @@ pub fn from_bytes(bytes: &[u8]) -> Bitv {
     /// let bv = Bitv::from_fn(5, |i| { i % 2 == 0 });
     /// assert!(bv.eq_vec(&[true, false, true, false, true]));
     /// ```
-    pub fn from_fn<F>(len: uint, mut f: F) -> Bitv where F: FnMut(uint) -> bool {
+    pub fn from_fn<F>(len: usize, mut f: F) -> Bitv where F: FnMut(usize) -> bool {
         let mut bitv = Bitv::from_elem(len, false);
-        for i in 0u..len {
+        for i in 0..len {
             bitv.set(i, f(i));
         }
         bitv
@@ -376,7 +376,7 @@ pub fn from_fn<F>(len: uint, mut f: F) -> Bitv where F: FnMut(uint) -> bool {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get(&self, i: uint) -> Option<bool> {
+    pub fn get(&self, i: usize) -> Option<bool> {
         if i >= self.nbits {
             return None;
         }
@@ -405,7 +405,7 @@ pub fn get(&self, i: uint) -> Option<bool> {
     #[inline]
     #[unstable(feature = "collections",
                reason = "panic semantics are likely to change in the future")]
-    pub fn set(&mut self, i: uint, x: bool) {
+    pub fn set(&mut self, i: usize, x: bool) {
         assert!(i < self.nbits);
         let w = i / u32::BITS;
         let b = i % u32::BITS;
@@ -649,7 +649,7 @@ pub fn any(&self) -> bool {
     /// assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000));
     /// ```
     pub fn to_bytes(&self) -> Vec<u8> {
-        fn bit(bitv: &Bitv, byte: uint, bit: uint) -> u8 {
+        fn bit(bitv: &Bitv, byte: usize, bit: usize) -> u8 {
             let offset = byte * 8 + bit;
             if offset >= bitv.nbits {
                 0
@@ -709,7 +709,7 @@ pub fn eq_vec(&self, v: &[bool]) -> bool {
     /// assert!(bv.eq_vec(&[false, true]));
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn truncate(&mut self, len: uint) {
+    pub fn truncate(&mut self, len: usize) {
         if len < self.len() {
             self.nbits = len;
             // This fixes (2).
@@ -723,7 +723,7 @@ pub fn truncate(&mut self, len: uint) {
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -736,7 +736,7 @@ pub fn truncate(&mut self, len: uint) {
     /// assert!(bv.capacity() >= 13);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve(&mut self, additional: uint) {
+    pub fn reserve(&mut self, additional: usize) {
         let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
         let storage_len = self.storage.len();
         if desired_cap > self.capacity() {
@@ -753,7 +753,7 @@ pub fn reserve(&mut self, additional: uint) {
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -766,7 +766,7 @@ pub fn reserve(&mut self, additional: uint) {
     /// assert!(bv.capacity() >= 13);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_exact(&mut self, additional: uint) {
+    pub fn reserve_exact(&mut self, additional: usize) {
         let desired_cap = self.len().checked_add(additional).expect("capacity overflow");
         let storage_len = self.storage.len();
         if desired_cap > self.capacity() {
@@ -788,15 +788,15 @@ pub fn reserve_exact(&mut self, additional: uint) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint {
-        self.storage.capacity().checked_mul(u32::BITS).unwrap_or(uint::MAX)
+    pub fn capacity(&self) -> usize {
+        self.storage.capacity().checked_mul(u32::BITS).unwrap_or(usize::MAX)
     }
 
     /// Grows the `Bitv` in-place, adding `n` copies of `value` to the `Bitv`.
     ///
     /// # Panics
     ///
-    /// Panics if the new len overflows a `uint`.
+    /// Panics if the new len overflows a `usize`.
     ///
     /// # Examples
     ///
@@ -808,7 +808,7 @@ pub fn capacity(&self) -> uint {
     /// assert_eq!(bv.len(), 10);
     /// assert_eq!(bv.to_bytes(), vec!(0b01001011, 0b11000000));
     /// ```
-    pub fn grow(&mut self, n: uint, value: bool) {
+    pub fn grow(&mut self, n: usize, value: bool) {
         // Note: we just bulk set all the bits in the last word in this fn in multiple places
         // which is technically wrong if not all of these bits are to be used. However, at the end
         // of this fn we call `fix_last_block` at the end of this fn, which should fix this.
@@ -901,7 +901,7 @@ pub fn push(&mut self, elem: bool) {
     /// Return the total number of bits in this vector
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { self.nbits }
+    pub fn len(&self) -> usize { self.nbits }
 
     /// Returns true if there are no bits in this vector
     #[inline]
@@ -1012,8 +1012,8 @@ impl cmp::Eq for Bitv {}
 #[derive(Clone)]
 pub struct Iter<'a> {
     bitv: &'a Bitv,
-    next_idx: uint,
-    end_idx: uint,
+    next_idx: usize,
+    end_idx: usize,
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -1031,7 +1031,7 @@ fn next(&mut self) -> Option<bool> {
         }
     }
 
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         let rem = self.end_idx - self.next_idx;
         (rem, Some(rem))
     }
@@ -1056,12 +1056,12 @@ impl<'a> ExactSizeIterator for Iter<'a> {}
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a> RandomAccessIterator for Iter<'a> {
     #[inline]
-    fn indexable(&self) -> uint {
+    fn indexable(&self) -> usize {
         self.end_idx - self.next_idx
     }
 
     #[inline]
-    fn idx(&mut self, index: uint) -> Option<bool> {
+    fn idx(&mut self, index: usize) -> Option<bool> {
         if index >= self.indexable() {
             None
         } else {
@@ -1083,7 +1083,7 @@ fn into_iter(self) -> Iter<'a> {
 ///
 /// It should also be noted that the amount of storage necessary for holding a
 /// set of objects is proportional to the maximum of the objects when viewed
-/// as a `uint`.
+/// as a `usize`.
 ///
 /// # Examples
 ///
@@ -1130,8 +1130,8 @@ fn default() -> BitvSet { BitvSet::new() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl FromIterator<uint> for BitvSet {
-    fn from_iter<I:Iterator<Item=uint>>(iterator: I) -> BitvSet {
+impl FromIterator<usize> for BitvSet {
+    fn from_iter<I:Iterator<Item=usize>>(iterator: I) -> BitvSet {
         let mut ret = BitvSet::new();
         ret.extend(iterator);
         ret
@@ -1139,9 +1139,9 @@ fn from_iter<I:Iterator<Item=uint>>(iterator: I) -> BitvSet {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl Extend<uint> for BitvSet {
+impl Extend<usize> for BitvSet {
     #[inline]
-    fn extend<I: Iterator<Item=uint>>(&mut self, iterator: I) {
+    fn extend<I: Iterator<Item=usize>>(&mut self, iterator: I) {
         for i in iterator {
             self.insert(i);
         }
@@ -1207,7 +1207,7 @@ pub fn new() -> BitvSet {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(nbits: uint) -> BitvSet {
+    pub fn with_capacity(nbits: usize) -> BitvSet {
         let bitv = Bitv::from_elem(nbits, false);
         BitvSet::from_bitv(bitv)
     }
@@ -1245,7 +1245,7 @@ pub fn from_bitv(bitv: Bitv) -> BitvSet {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint {
+    pub fn capacity(&self) -> usize {
         self.bitv.capacity()
     }
 
@@ -1266,7 +1266,7 @@ pub fn capacity(&self) -> uint {
     /// assert!(s.capacity() >= 10);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_len(&mut self, len: uint) {
+    pub fn reserve_len(&mut self, len: usize) {
         let cur_len = self.bitv.len();
         if len >= cur_len {
             self.bitv.reserve(len - cur_len);
@@ -1292,7 +1292,7 @@ pub fn reserve_len(&mut self, len: uint) {
     /// assert!(s.capacity() >= 10);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_len_exact(&mut self, len: uint) {
+    pub fn reserve_len_exact(&mut self, len: usize) {
         let cur_len = self.bitv.len();
         if len >= cur_len {
             self.bitv.reserve_exact(len - cur_len);
@@ -1415,7 +1415,7 @@ pub fn shrink_to_fit(&mut self) {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn iter(&self) -> bitv_set::Iter {
-        SetIter {set: self, next_idx: 0u}
+        SetIter {set: self, next_idx: 0}
     }
 
     /// Iterator over each u32 stored in `self` union `other`.
@@ -1443,12 +1443,12 @@ fn or(w1: u32, w2: u32) -> u32 { w1 | w2 }
             set: self,
             other: other,
             merge: or,
-            current_word: 0u32,
-            next_idx: 0u
+            current_word: 0,
+            next_idx: 0
         })
     }
 
-    /// Iterator over each uint stored in `self` intersect `other`.
+    /// Iterator over each usize stored in `self` intersect `other`.
     /// See [intersect_with](#method.intersect_with) for an efficient in-place version.
     ///
     /// # Examples
@@ -1473,12 +1473,12 @@ fn bitand(w1: u32, w2: u32) -> u32 { w1 & w2 }
             set: self,
             other: other,
             merge: bitand,
-            current_word: 0u32,
+            current_word: 0,
             next_idx: 0
         }.take(min))
     }
 
-    /// Iterator over each uint stored in the `self` setminus `other`.
+    /// Iterator over each usize stored in the `self` setminus `other`.
     /// See [difference_with](#method.difference_with) for an efficient in-place version.
     ///
     /// # Examples
@@ -1510,7 +1510,7 @@ fn diff(w1: u32, w2: u32) -> u32 { w1 & !w2 }
             set: self,
             other: other,
             merge: diff,
-            current_word: 0u32,
+            current_word: 0,
             next_idx: 0
         })
     }
@@ -1541,7 +1541,7 @@ fn bitxor(w1: u32, w2: u32) -> u32 { w1 ^ w2 }
             set: self,
             other: other,
             merge: bitxor,
-            current_word: 0u32,
+            current_word: 0,
             next_idx: 0
         })
     }
@@ -1651,7 +1651,7 @@ pub fn symmetric_difference_with(&mut self, other: &BitvSet) {
     /// Return the number of set bits in this set.
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint  {
+    pub fn len(&self) -> usize  {
         self.bitv.blocks().fold(0, |acc, n| acc + n.count_ones())
     }
 
@@ -1672,7 +1672,7 @@ pub fn clear(&mut self) {
     /// Returns `true` if this set contains the specified integer.
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn contains(&self, value: &uint) -> bool {
+    pub fn contains(&self, value: &usize) -> bool {
         let bitv = &self.bitv;
         *value < bitv.nbits && bitv[*value]
     }
@@ -1709,7 +1709,7 @@ pub fn is_superset(&self, other: &BitvSet) -> bool {
     /// Adds a value to the set. Returns `true` if the value was not already
     /// present in the set.
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn insert(&mut self, value: uint) -> bool {
+    pub fn insert(&mut self, value: usize) -> bool {
         if self.contains(&value) {
             return false;
         }
@@ -1727,7 +1727,7 @@ pub fn insert(&mut self, value: uint) -> bool {
     /// Removes a value from the set. Returns `true` if the value was
     /// present in the set.
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn remove(&mut self, value: &uint) -> bool {
+    pub fn remove(&mut self, value: &usize) -> bool {
         if !self.contains(value) {
             return false;
         }
@@ -1767,7 +1767,7 @@ fn hash(&self, state: &mut S) {
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct SetIter<'a> {
     set: &'a BitvSet,
-    next_idx: uint
+    next_idx: usize
 }
 
 /// An iterator combining two `BitvSet` iterators.
@@ -1777,7 +1777,7 @@ struct TwoBitPositions<'a> {
     other: &'a BitvSet,
     merge: fn(u32, u32) -> u32,
     current_word: u32,
-    next_idx: uint
+    next_idx: usize
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -1791,9 +1791,9 @@ struct TwoBitPositions<'a> {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a> Iterator for SetIter<'a> {
-    type Item = uint;
+    type Item = usize;
 
-    fn next(&mut self) -> Option<uint> {
+    fn next(&mut self) -> Option<usize> {
         while self.next_idx < self.set.bitv.len() {
             let idx = self.next_idx;
             self.next_idx += 1;
@@ -1807,16 +1807,16 @@ fn next(&mut self) -> Option<uint> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         (0, Some(self.set.bitv.len() - self.next_idx))
     }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a> Iterator for TwoBitPositions<'a> {
-    type Item = uint;
+    type Item = usize;
 
-    fn next(&mut self) -> Option<uint> {
+    fn next(&mut self) -> Option<usize> {
         while self.next_idx < self.set.bitv.len() ||
               self.next_idx < self.other.bitv.len() {
             let bit_idx = self.next_idx % u32::BITS;
@@ -1844,7 +1844,7 @@ fn next(&mut self) -> Option<uint> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         let cap = cmp::max(self.set.bitv.len(), self.other.bitv.len());
         (0, Some(cap - self.next_idx))
     }
@@ -1852,34 +1852,34 @@ fn size_hint(&self) -> (uint, Option<uint>) {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a> Iterator for Union<'a> {
-    type Item = uint;
+    type Item = usize;
 
-    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
-    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
+    #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
+    #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a> Iterator for Intersection<'a> {
-    type Item = uint;
+    type Item = usize;
 
-    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
-    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
+    #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
+    #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a> Iterator for Difference<'a> {
-    type Item = uint;
+    type Item = usize;
 
-    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
-    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
+    #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
+    #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a> Iterator for SymmetricDifference<'a> {
-    type Item = uint;
+    type Item = usize;
 
-    #[inline] fn next(&mut self) -> Option<uint> { self.0.next() }
-    #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.0.size_hint() }
+    #[inline] fn next(&mut self) -> Option<usize> { self.0.next() }
+    #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() }
 }
 
 impl<'a> IntoIterator for &'a BitvSet {
@@ -1902,7 +1902,7 @@ fn test_to_str() {
         let zerolen = Bitv::new();
         assert_eq!(format!("{:?}", zerolen), "");
 
-        let eightbits = Bitv::from_elem(8u, false);
+        let eightbits = Bitv::from_elem(8, false);
         assert_eq!(format!("{:?}", eightbits), "00000000")
     }
 
@@ -1910,16 +1910,16 @@ fn test_to_str() {
     fn test_0_elements() {
         let act = Bitv::new();
         let exp = Vec::new();
-        assert!(act.eq_vec(exp.as_slice()));
+        assert!(act.eq_vec(&exp));
         assert!(act.none() && act.all());
     }
 
     #[test]
     fn test_1_element() {
-        let mut act = Bitv::from_elem(1u, false);
+        let mut act = Bitv::from_elem(1, false);
         assert!(act.eq_vec(&[false]));
         assert!(act.none() && !act.all());
-        act = Bitv::from_elem(1u, true);
+        act = Bitv::from_elem(1, true);
         assert!(act.eq_vec(&[true]));
         assert!(!act.none() && act.all());
     }
@@ -1938,42 +1938,42 @@ fn test_10_elements() {
         let mut act;
         // all 0
 
-        act = Bitv::from_elem(10u, false);
+        act = Bitv::from_elem(10, false);
         assert!((act.eq_vec(
                     &[false, false, false, false, false, false, false, false, false, false])));
         assert!(act.none() && !act.all());
         // all 1
 
-        act = Bitv::from_elem(10u, true);
+        act = Bitv::from_elem(10, true);
         assert!((act.eq_vec(&[true, true, true, true, true, true, true, true, true, true])));
         assert!(!act.none() && act.all());
         // mixed
 
-        act = Bitv::from_elem(10u, false);
-        act.set(0u, true);
-        act.set(1u, true);
-        act.set(2u, true);
-        act.set(3u, true);
-        act.set(4u, true);
+        act = Bitv::from_elem(10, false);
+        act.set(0, true);
+        act.set(1, true);
+        act.set(2, true);
+        act.set(3, true);
+        act.set(4, true);
         assert!((act.eq_vec(&[true, true, true, true, true, false, false, false, false, false])));
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(10u, false);
-        act.set(5u, true);
-        act.set(6u, true);
-        act.set(7u, true);
-        act.set(8u, true);
-        act.set(9u, true);
+        act = Bitv::from_elem(10, false);
+        act.set(5, true);
+        act.set(6, true);
+        act.set(7, true);
+        act.set(8, true);
+        act.set(9, true);
         assert!((act.eq_vec(&[false, false, false, false, false, true, true, true, true, true])));
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(10u, false);
-        act.set(0u, true);
-        act.set(3u, true);
-        act.set(6u, true);
-        act.set(9u, true);
+        act = Bitv::from_elem(10, false);
+        act.set(0, true);
+        act.set(3, true);
+        act.set(6, true);
+        act.set(9, true);
         assert!((act.eq_vec(&[true, false, false, true, false, false, true, false, false, true])));
         assert!(!act.none() && !act.all());
     }
@@ -1983,7 +1983,7 @@ fn test_31_elements() {
         let mut act;
         // all 0
 
-        act = Bitv::from_elem(31u, false);
+        act = Bitv::from_elem(31, false);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -1991,7 +1991,7 @@ fn test_31_elements() {
         assert!(act.none() && !act.all());
         // all 1
 
-        act = Bitv::from_elem(31u, true);
+        act = Bitv::from_elem(31, true);
         assert!(act.eq_vec(
                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
                   true, true, true, true, true, true, true, true, true, true, true, true, true,
@@ -1999,15 +1999,15 @@ fn test_31_elements() {
         assert!(!act.none() && act.all());
         // mixed
 
-        act = Bitv::from_elem(31u, false);
-        act.set(0u, true);
-        act.set(1u, true);
-        act.set(2u, true);
-        act.set(3u, true);
-        act.set(4u, true);
-        act.set(5u, true);
-        act.set(6u, true);
-        act.set(7u, true);
+        act = Bitv::from_elem(31, false);
+        act.set(0, true);
+        act.set(1, true);
+        act.set(2, true);
+        act.set(3, true);
+        act.set(4, true);
+        act.set(5, true);
+        act.set(6, true);
+        act.set(7, true);
         assert!(act.eq_vec(
                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -2015,15 +2015,15 @@ fn test_31_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(31u, false);
-        act.set(16u, true);
-        act.set(17u, true);
-        act.set(18u, true);
-        act.set(19u, true);
-        act.set(20u, true);
-        act.set(21u, true);
-        act.set(22u, true);
-        act.set(23u, true);
+        act = Bitv::from_elem(31, false);
+        act.set(16, true);
+        act.set(17, true);
+        act.set(18, true);
+        act.set(19, true);
+        act.set(20, true);
+        act.set(21, true);
+        act.set(22, true);
+        act.set(23, true);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, true, true, true, true, true, true, true, true,
@@ -2031,14 +2031,14 @@ fn test_31_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(31u, false);
-        act.set(24u, true);
-        act.set(25u, true);
-        act.set(26u, true);
-        act.set(27u, true);
-        act.set(28u, true);
-        act.set(29u, true);
-        act.set(30u, true);
+        act = Bitv::from_elem(31, false);
+        act.set(24, true);
+        act.set(25, true);
+        act.set(26, true);
+        act.set(27, true);
+        act.set(28, true);
+        act.set(29, true);
+        act.set(30, true);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -2046,10 +2046,10 @@ fn test_31_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(31u, false);
-        act.set(3u, true);
-        act.set(17u, true);
-        act.set(30u, true);
+        act = Bitv::from_elem(31, false);
+        act.set(3, true);
+        act.set(17, true);
+        act.set(30, true);
         assert!(act.eq_vec(
                 &[false, false, false, true, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, true, false, false, false, false, false, false,
@@ -2062,7 +2062,7 @@ fn test_32_elements() {
         let mut act;
         // all 0
 
-        act = Bitv::from_elem(32u, false);
+        act = Bitv::from_elem(32, false);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -2070,7 +2070,7 @@ fn test_32_elements() {
         assert!(act.none() && !act.all());
         // all 1
 
-        act = Bitv::from_elem(32u, true);
+        act = Bitv::from_elem(32, true);
         assert!(act.eq_vec(
                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
                   true, true, true, true, true, true, true, true, true, true, true, true, true,
@@ -2078,15 +2078,15 @@ fn test_32_elements() {
         assert!(!act.none() && act.all());
         // mixed
 
-        act = Bitv::from_elem(32u, false);
-        act.set(0u, true);
-        act.set(1u, true);
-        act.set(2u, true);
-        act.set(3u, true);
-        act.set(4u, true);
-        act.set(5u, true);
-        act.set(6u, true);
-        act.set(7u, true);
+        act = Bitv::from_elem(32, false);
+        act.set(0, true);
+        act.set(1, true);
+        act.set(2, true);
+        act.set(3, true);
+        act.set(4, true);
+        act.set(5, true);
+        act.set(6, true);
+        act.set(7, true);
         assert!(act.eq_vec(
                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -2094,15 +2094,15 @@ fn test_32_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(32u, false);
-        act.set(16u, true);
-        act.set(17u, true);
-        act.set(18u, true);
-        act.set(19u, true);
-        act.set(20u, true);
-        act.set(21u, true);
-        act.set(22u, true);
-        act.set(23u, true);
+        act = Bitv::from_elem(32, false);
+        act.set(16, true);
+        act.set(17, true);
+        act.set(18, true);
+        act.set(19, true);
+        act.set(20, true);
+        act.set(21, true);
+        act.set(22, true);
+        act.set(23, true);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, true, true, true, true, true, true, true, true,
@@ -2110,15 +2110,15 @@ fn test_32_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(32u, false);
-        act.set(24u, true);
-        act.set(25u, true);
-        act.set(26u, true);
-        act.set(27u, true);
-        act.set(28u, true);
-        act.set(29u, true);
-        act.set(30u, true);
-        act.set(31u, true);
+        act = Bitv::from_elem(32, false);
+        act.set(24, true);
+        act.set(25, true);
+        act.set(26, true);
+        act.set(27, true);
+        act.set(28, true);
+        act.set(29, true);
+        act.set(30, true);
+        act.set(31, true);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -2126,11 +2126,11 @@ fn test_32_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(32u, false);
-        act.set(3u, true);
-        act.set(17u, true);
-        act.set(30u, true);
-        act.set(31u, true);
+        act = Bitv::from_elem(32, false);
+        act.set(3, true);
+        act.set(17, true);
+        act.set(30, true);
+        act.set(31, true);
         assert!(act.eq_vec(
                 &[false, false, false, true, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, true, false, false, false, false, false, false,
@@ -2143,7 +2143,7 @@ fn test_33_elements() {
         let mut act;
         // all 0
 
-        act = Bitv::from_elem(33u, false);
+        act = Bitv::from_elem(33, false);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -2151,7 +2151,7 @@ fn test_33_elements() {
         assert!(act.none() && !act.all());
         // all 1
 
-        act = Bitv::from_elem(33u, true);
+        act = Bitv::from_elem(33, true);
         assert!(act.eq_vec(
                 &[true, true, true, true, true, true, true, true, true, true, true, true, true,
                   true, true, true, true, true, true, true, true, true, true, true, true, true,
@@ -2159,15 +2159,15 @@ fn test_33_elements() {
         assert!(!act.none() && act.all());
         // mixed
 
-        act = Bitv::from_elem(33u, false);
-        act.set(0u, true);
-        act.set(1u, true);
-        act.set(2u, true);
-        act.set(3u, true);
-        act.set(4u, true);
-        act.set(5u, true);
-        act.set(6u, true);
-        act.set(7u, true);
+        act = Bitv::from_elem(33, false);
+        act.set(0, true);
+        act.set(1, true);
+        act.set(2, true);
+        act.set(3, true);
+        act.set(4, true);
+        act.set(5, true);
+        act.set(6, true);
+        act.set(7, true);
         assert!(act.eq_vec(
                 &[true, true, true, true, true, true, true, true, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -2175,15 +2175,15 @@ fn test_33_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(33u, false);
-        act.set(16u, true);
-        act.set(17u, true);
-        act.set(18u, true);
-        act.set(19u, true);
-        act.set(20u, true);
-        act.set(21u, true);
-        act.set(22u, true);
-        act.set(23u, true);
+        act = Bitv::from_elem(33, false);
+        act.set(16, true);
+        act.set(17, true);
+        act.set(18, true);
+        act.set(19, true);
+        act.set(20, true);
+        act.set(21, true);
+        act.set(22, true);
+        act.set(23, true);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, true, true, true, true, true, true, true, true,
@@ -2191,15 +2191,15 @@ fn test_33_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(33u, false);
-        act.set(24u, true);
-        act.set(25u, true);
-        act.set(26u, true);
-        act.set(27u, true);
-        act.set(28u, true);
-        act.set(29u, true);
-        act.set(30u, true);
-        act.set(31u, true);
+        act = Bitv::from_elem(33, false);
+        act.set(24, true);
+        act.set(25, true);
+        act.set(26, true);
+        act.set(27, true);
+        act.set(28, true);
+        act.set(29, true);
+        act.set(30, true);
+        act.set(31, true);
         assert!(act.eq_vec(
                 &[false, false, false, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, false, false, false, false, false, false,
@@ -2207,12 +2207,12 @@ fn test_33_elements() {
         assert!(!act.none() && !act.all());
         // mixed
 
-        act = Bitv::from_elem(33u, false);
-        act.set(3u, true);
-        act.set(17u, true);
-        act.set(30u, true);
-        act.set(31u, true);
-        act.set(32u, true);
+        act = Bitv::from_elem(33, false);
+        act.set(3, true);
+        act.set(17, true);
+        act.set(30, true);
+        act.set(31, true);
+        act.set(32, true);
         assert!(act.eq_vec(
                 &[false, false, false, true, false, false, false, false, false, false, false, false,
                   false, false, false, false, false, true, false, false, false, false, false, false,
@@ -2222,15 +2222,15 @@ fn test_33_elements() {
 
     #[test]
     fn test_equal_differing_sizes() {
-        let v0 = Bitv::from_elem(10u, false);
-        let v1 = Bitv::from_elem(11u, false);
+        let v0 = Bitv::from_elem(10, false);
+        let v1 = Bitv::from_elem(11, false);
         assert!(v0 != v1);
     }
 
     #[test]
     fn test_equal_greatly_differing_sizes() {
-        let v0 = Bitv::from_elem(10u, false);
-        let v1 = Bitv::from_elem(110u, false);
+        let v0 = Bitv::from_elem(10, false);
+        let v1 = Bitv::from_elem(110, false);
         assert!(v0 != v1);
     }
 
@@ -2248,12 +2248,12 @@ fn test_equal_sneaky_small() {
     #[test]
     fn test_equal_sneaky_big() {
         let mut a = Bitv::from_elem(100, false);
-        for i in 0u..100 {
+        for i in 0..100 {
             a.set(i, true);
         }
 
         let mut b = Bitv::from_elem(100, true);
-        for i in 0u..100 {
+        for i in 0..100 {
             b.set(i, true);
         }
 
@@ -2288,7 +2288,7 @@ fn test_from_bools() {
 
     #[test]
     fn test_to_bools() {
-        let bools = vec!(false, false, true, false, false, true, true, false);
+        let bools = vec![false, false, true, false, false, true, true, false];
         assert_eq!(Bitv::from_bytes(&[0b00100110]).iter().collect::<Vec<bool>>(), bools);
     }
 
@@ -2299,7 +2299,7 @@ fn test_bitv_iterator() {
 
         assert_eq!(bitv.iter().collect::<Vec<bool>>(), bools);
 
-        let long = (0i32..10000).map(|i| i % 2 == 0).collect::<Vec<_>>();
+        let long: Vec<_> = (0i32..10000).map(|i| i % 2 == 0).collect();
         let bitv: Bitv = long.iter().map(|n| *n).collect();
         assert_eq!(bitv.iter().collect::<Vec<bool>>(), long)
     }
@@ -2350,8 +2350,8 @@ fn test_big_clear() {
 
     #[test]
     fn test_bitv_lt() {
-        let mut a = Bitv::from_elem(5u, false);
-        let mut b = Bitv::from_elem(5u, false);
+        let mut a = Bitv::from_elem(5, false);
+        let mut b = Bitv::from_elem(5, false);
 
         assert!(!(a < b) && !(b < a));
         b.set(2, true);
@@ -2366,8 +2366,8 @@ fn test_bitv_lt() {
 
     #[test]
     fn test_ord() {
-        let mut a = Bitv::from_elem(5u, false);
-        let mut b = Bitv::from_elem(5u, false);
+        let mut a = Bitv::from_elem(5, false);
+        let mut b = Bitv::from_elem(5, false);
 
         assert!(a <= b && a >= b);
         a.set(1, true);
@@ -2530,7 +2530,7 @@ mod bitv_bench {
 
     use super::Bitv;
 
-    static BENCH_BITS : uint = 1 << 14;
+    static BENCH_BITS : usize = 1 << 14;
 
     fn rng() -> rand::IsaacRng {
         let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
@@ -2538,12 +2538,12 @@ fn rng() -> rand::IsaacRng {
     }
 
     #[bench]
-    fn bench_uint_small(b: &mut Bencher) {
+    fn bench_usize_small(b: &mut Bencher) {
         let mut r = rng();
-        let mut bitv = 0 as uint;
+        let mut bitv = 0 as usize;
         b.iter(|| {
-            for _ in 0u..100 {
-                bitv |= 1 << ((r.next_u32() as uint) % u32::BITS);
+            for _ in 0..100 {
+                bitv |= 1 << ((r.next_u32() as usize) % u32::BITS);
             }
             black_box(&bitv);
         });
@@ -2554,8 +2554,8 @@ fn bench_bitv_set_big_fixed(b: &mut Bencher) {
         let mut r = rng();
         let mut bitv = Bitv::from_elem(BENCH_BITS, false);
         b.iter(|| {
-            for _ in 0u..100 {
-                bitv.set((r.next_u32() as uint) % BENCH_BITS, true);
+            for _ in 0..100 {
+                bitv.set((r.next_u32() as usize) % BENCH_BITS, true);
             }
             black_box(&bitv);
         });
@@ -2566,8 +2566,8 @@ fn bench_bitv_set_big_variable(b: &mut Bencher) {
         let mut r = rng();
         let mut bitv = Bitv::from_elem(BENCH_BITS, false);
         b.iter(|| {
-            for _ in 0u..100 {
-                bitv.set((r.next_u32() as uint) % BENCH_BITS, r.gen());
+            for _ in 0..100 {
+                bitv.set((r.next_u32() as usize) % BENCH_BITS, r.gen());
             }
             black_box(&bitv);
         });
@@ -2578,8 +2578,8 @@ fn bench_bitv_set_small(b: &mut Bencher) {
         let mut r = rng();
         let mut bitv = Bitv::from_elem(u32::BITS, false);
         b.iter(|| {
-            for _ in 0u..100 {
-                bitv.set((r.next_u32() as uint) % u32::BITS, true);
+            for _ in 0..100 {
+                bitv.set((r.next_u32() as usize) % u32::BITS, true);
             }
             black_box(&bitv);
         });
@@ -2598,10 +2598,10 @@ fn bench_bitv_big_union(b: &mut Bencher) {
     fn bench_bitv_small_iter(b: &mut Bencher) {
         let bitv = Bitv::from_elem(u32::BITS, false);
         b.iter(|| {
-            let mut sum = 0u;
-            for _ in 0u..10 {
+            let mut sum = 0;
+            for _ in 0..10 {
                 for pres in &bitv {
-                    sum += pres as uint;
+                    sum += pres as usize;
                 }
             }
             sum
@@ -2612,9 +2612,9 @@ fn bench_bitv_small_iter(b: &mut Bencher) {
     fn bench_bitv_big_iter(b: &mut Bencher) {
         let bitv = Bitv::from_elem(BENCH_BITS, false);
         b.iter(|| {
-            let mut sum = 0u;
+            let mut sum = 0;
             for pres in &bitv {
-                sum += pres as uint;
+                sum += pres as usize;
             }
             sum
         })
@@ -2645,9 +2645,9 @@ fn test_bitv_set_show() {
     }
 
     #[test]
-    fn test_bitv_set_from_uints() {
-        let uints = vec![0, 2, 2, 3];
-        let a: BitvSet = uints.into_iter().collect();
+    fn test_bitv_set_from_usizes() {
+        let usizes = vec![0, 2, 2, 3];
+        let a: BitvSet = usizes.into_iter().collect();
         let mut b = BitvSet::new();
         b.insert(0);
         b.insert(2);
@@ -2657,16 +2657,16 @@ fn test_bitv_set_from_uints() {
 
     #[test]
     fn test_bitv_set_iterator() {
-        let uints = vec![0, 2, 2, 3];
-        let bitv: BitvSet = uints.into_iter().collect();
+        let usizes = vec![0, 2, 2, 3];
+        let bitv: BitvSet = usizes.into_iter().collect();
 
-        let idxs: Vec<uint> = bitv.iter().collect();
+        let idxs: Vec<_> = bitv.iter().collect();
         assert_eq!(idxs, vec![0, 2, 3]);
 
-        let long: BitvSet = (0u..10000).filter(|&n| n % 2 == 0).collect();
-        let real = range_step(0, 10000, 2).collect::<Vec<uint>>();
+        let long: BitvSet = (0..10000).filter(|&n| n % 2 == 0).collect();
+        let real: Vec<_> = range_step(0, 10000, 2).collect();
 
-        let idxs: Vec<uint> = long.iter().collect();
+        let idxs: Vec<_> = long.iter().collect();
         assert_eq!(idxs, real);
     }
 
@@ -2677,8 +2677,8 @@ fn test_bitv_set_frombitv_init() {
         for &b in &bools {
             for &l in &lengths {
                 let bitset = BitvSet::from_bitv(Bitv::from_elem(l, b));
-                assert_eq!(bitset.contains(&1u), b);
-                assert_eq!(bitset.contains(&(l-1u)), b);
+                assert_eq!(bitset.contains(&1), b);
+                assert_eq!(bitset.contains(&(l-1)), b);
                 assert!(!bitset.contains(&l));
             }
         }
@@ -2731,7 +2731,7 @@ fn test_bitv_set_intersection() {
         assert!(b.insert(3));
 
         let expected = [3, 5, 11, 77];
-        let actual = a.intersection(&b).collect::<Vec<uint>>();
+        let actual: Vec<_> = a.intersection(&b).collect();
         assert_eq!(actual, expected);
     }
 
@@ -2750,7 +2750,7 @@ fn test_bitv_set_difference() {
         assert!(b.insert(200));
 
         let expected = [1, 5, 500];
-        let actual = a.difference(&b).collect::<Vec<uint>>();
+        let actual: Vec<_> = a.difference(&b).collect();
         assert_eq!(actual, expected);
     }
 
@@ -2771,7 +2771,7 @@ fn test_bitv_set_symmetric_difference() {
         assert!(b.insert(220));
 
         let expected = [1, 5, 11, 14, 220];
-        let actual = a.symmetric_difference(&b).collect::<Vec<uint>>();
+        let actual: Vec<_> = a.symmetric_difference(&b).collect();
         assert_eq!(actual, expected);
     }
 
@@ -2796,7 +2796,7 @@ fn test_bitv_set_union() {
         assert!(b.insert(19));
 
         let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160, 200];
-        let actual = a.union(&b).collect::<Vec<uint>>();
+        let actual: Vec<_> = a.union(&b).collect();
         assert_eq!(actual, expected);
     }
 
@@ -3025,7 +3025,7 @@ mod bitv_set_bench {
 
     use super::{Bitv, BitvSet};
 
-    static BENCH_BITS : uint = 1 << 14;
+    static BENCH_BITS : usize = 1 << 14;
 
     fn rng() -> rand::IsaacRng {
         let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
@@ -3037,8 +3037,8 @@ fn bench_bitvset_small(b: &mut Bencher) {
         let mut r = rng();
         let mut bitv = BitvSet::new();
         b.iter(|| {
-            for _ in 0u..100 {
-                bitv.insert((r.next_u32() as uint) % u32::BITS);
+            for _ in 0..100 {
+                bitv.insert((r.next_u32() as usize) % u32::BITS);
             }
             black_box(&bitv);
         });
@@ -3049,8 +3049,8 @@ fn bench_bitvset_big(b: &mut Bencher) {
         let mut r = rng();
         let mut bitv = BitvSet::new();
         b.iter(|| {
-            for _ in 0u..100 {
-                bitv.insert((r.next_u32() as uint) % BENCH_BITS);
+            for _ in 0..100 {
+                bitv.insert((r.next_u32() as usize) % BENCH_BITS);
             }
             black_box(&bitv);
         });
@@ -3061,9 +3061,9 @@ fn bench_bitvset_iter(b: &mut Bencher) {
         let bitv = BitvSet::from_bitv(Bitv::from_fn(BENCH_BITS,
                                               |idx| {idx % 3 == 0}));
         b.iter(|| {
-            let mut sum = 0u;
+            let mut sum = 0;
             for idx in &bitv {
-                sum += idx as uint;
+                sum += idx as usize;
             }
             sum
         })
index 99ee5957913dc5659e21c07f7bfb9c703d4c8886..aec50d5380880e24891e760d5247a3fbaad862f1 100644 (file)
@@ -15,7 +15,7 @@
 // writing (August 2014) freely licensed under the following Creative Commons Attribution
 // License: [CC BY 2.5 CA](http://creativecommons.org/licenses/by/2.5/ca/).
 
-pub use self::Entry::*;
+use self::Entry::*;
 
 use core::prelude::*;
 
 /// would like to further explore choosing the optimal search strategy based on the choice of B,
 /// and possibly other factors. Using linear search, searching for a random element is expected
 /// to take O(B log<sub>B</sub>n) comparisons, which is generally worse than a BST. In practice,
-/// however, performance is excellent. `BTreeMap` is able to readily outperform `TreeMap` under
-/// many workloads, and is competitive where it doesn't. BTreeMap also generally *scales* better
-/// than TreeMap, making it more appropriate for large datasets.
-///
-/// However, `TreeMap` may still be more appropriate to use in many contexts. If elements are very
-/// large or expensive to compare, `TreeMap` may be more appropriate. It won't allocate any
-/// more space than is needed, and will perform the minimal number of comparisons necessary.
-/// `TreeMap` also provides much better performance stability guarantees. Generally, very few
-/// changes need to be made to update a BST, and two updates are expected to take about the same
-/// amount of time on roughly equal sized BSTs. However a B-Tree's performance is much more
-/// amortized. If a node is overfull, it must be split into two nodes. If a node is underfull, it
-/// may be merged with another. Both of these operations are relatively expensive to perform, and
-/// it's possible to force one to occur at every single level of the tree in a single insertion or
-/// deletion. In fact, a malicious or otherwise unlucky sequence of insertions and deletions can
-/// force this degenerate behaviour to occur on every operation. While the total amount of work
-/// done on each operation isn't *catastrophic*, and *is* still bounded by O(B log<sub>B</sub>n),
-/// it is certainly much slower when it does.
+/// however, performance is excellent.
 #[derive(Clone)]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct BTreeMap<K, V> {
     root: Node<K, V>,
-    length: uint,
-    depth: uint,
-    b: uint,
+    length: usize,
+    depth: usize,
+    b: usize,
 }
 
 /// An abstract base over-which all other BTree iterators are built.
 struct AbsIter<T> {
     traversals: RingBuf<T>,
-    size: uint,
+    size: usize,
 }
 
 /// An iterator over a BTreeMap's entries.
@@ -171,7 +155,7 @@ pub fn new() -> BTreeMap<K, V> {
     /// Makes a new empty BTreeMap with the given B.
     ///
     /// B cannot be less than 2.
-    pub fn with_b(b: uint) -> BTreeMap<K, V> {
+    pub fn with_b(b: usize) -> BTreeMap<K, V> {
         assert!(b > 1, "B must be greater than 1");
         BTreeMap {
             length: 0,
@@ -189,7 +173,7 @@ pub fn with_b(b: uint) -> BTreeMap<K, V> {
     /// use std::collections::BTreeMap;
     ///
     /// let mut a = BTreeMap::new();
-    /// a.insert(1u, "a");
+    /// a.insert(1, "a");
     /// a.clear();
     /// assert!(a.is_empty());
     /// ```
@@ -219,7 +203,7 @@ pub fn clear(&mut self) {
     /// use std::collections::BTreeMap;
     ///
     /// let mut map = BTreeMap::new();
-    /// map.insert(1u, "a");
+    /// map.insert(1, "a");
     /// assert_eq!(map.get(&1), Some(&"a"));
     /// assert_eq!(map.get(&2), None);
     /// ```
@@ -251,7 +235,7 @@ pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> where Q: BorrowFrom<K> + Ord
     /// use std::collections::BTreeMap;
     ///
     /// let mut map = BTreeMap::new();
-    /// map.insert(1u, "a");
+    /// map.insert(1, "a");
     /// assert_eq!(map.contains_key(&1), true);
     /// assert_eq!(map.contains_key(&2), false);
     /// ```
@@ -271,7 +255,7 @@ pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where Q: BorrowFrom<K> +
     /// use std::collections::BTreeMap;
     ///
     /// let mut map = BTreeMap::new();
-    /// map.insert(1u, "a");
+    /// map.insert(1, "a");
     /// match map.get_mut(&1) {
     ///     Some(x) => *x = "b",
     ///     None => (),
@@ -333,7 +317,7 @@ pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V> where Q: BorrowF
     /// use std::collections::BTreeMap;
     ///
     /// let mut map = BTreeMap::new();
-    /// assert_eq!(map.insert(37u, "a"), None);
+    /// assert_eq!(map.insert(37, "a"), None);
     /// assert_eq!(map.is_empty(), false);
     ///
     /// map.insert(37, "b");
@@ -445,7 +429,7 @@ pub fn insert(&mut self, mut key: K, mut value: V) -> Option<V> {
     /// use std::collections::BTreeMap;
     ///
     /// let mut map = BTreeMap::new();
-    /// map.insert(1u, "a");
+    /// map.insert(1, "a");
     /// assert_eq!(map.remove(&1), Some("a"));
     /// assert_eq!(map.remove(&1), None);
     /// ```
@@ -926,8 +910,6 @@ fn index(&self, key: &Q) -> &V {
 impl<K: Ord, Q: ?Sized, V> IndexMut<Q> for BTreeMap<K, V>
     where Q: BorrowFrom<K> + Ord
 {
-    type Output = V;
-
     fn index_mut(&mut self, key: &Q) -> &mut V {
         self.get_mut(key).expect("no entry found for key")
     }
@@ -1001,7 +983,7 @@ fn next(&mut self) -> Option<(K, V)> {
         }
     }
 
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         (self.size, Some(self.size))
     }
 }
@@ -1038,7 +1020,7 @@ impl<'a, K, V> Iterator for Iter<'a, K, V> {
     type Item = (&'a K, &'a V);
 
     fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
@@ -1052,7 +1034,7 @@ impl<'a, K, V> Iterator for IterMut<'a, K, V> {
     type Item = (&'a K, &'a mut V);
 
     fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
@@ -1066,7 +1048,7 @@ impl<K, V> Iterator for IntoIter<K, V> {
     type Item = (K, V);
 
     fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
@@ -1080,7 +1062,7 @@ impl<'a, K, V> Iterator for Keys<'a, K, V> {
     type Item = &'a K;
 
     fn next(&mut self) -> Option<(&'a K)> { self.inner.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
@@ -1095,7 +1077,7 @@ impl<'a, K, V> Iterator for Values<'a, K, V> {
     type Item = &'a V;
 
     fn next(&mut self) -> Option<(&'a V)> { self.inner.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
@@ -1137,8 +1119,7 @@ pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
 impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
     /// Sets the value of the entry with the VacantEntry's key,
     /// and returns a mutable reference to it.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn insert(self, value: V) -> &'a mut V {
         self.stack.insert(self.key, value)
     }
@@ -1146,38 +1127,33 @@ pub fn insert(self, value: V) -> &'a mut V {
 
 impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
     /// Gets a reference to the value in the entry.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn get(&self) -> &V {
         self.stack.peek()
     }
 
     /// Gets a mutable reference to the value in the entry.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn get_mut(&mut self) -> &mut V {
         self.stack.peek_mut()
     }
 
     /// Converts the entry into a mutable reference to its value.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn into_mut(self) -> &'a mut V {
         self.stack.into_top()
     }
 
     /// Sets the value of the entry with the OccupiedEntry's key,
     /// and returns the entry's old value.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn insert(&mut self, mut value: V) -> V {
         mem::swap(self.stack.peek_mut(), &mut value);
         value
     }
 
     /// Takes the value of the entry out of the map, and returns it.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn remove(self) -> V {
         self.stack.remove()
     }
@@ -1192,16 +1168,16 @@ impl<K, V> BTreeMap<K, V> {
     /// use std::collections::BTreeMap;
     ///
     /// let mut map = BTreeMap::new();
-    /// map.insert(1u, "a");
-    /// map.insert(2u, "b");
-    /// map.insert(3u, "c");
+    /// map.insert(1, "a");
+    /// map.insert(2, "b");
+    /// map.insert(3, "c");
     ///
     /// for (key, value) in map.iter() {
     ///     println!("{}: {}", key, value);
     /// }
     ///
     /// let (first_key, first_value) = map.iter().next().unwrap();
-    /// assert_eq!((*first_key, *first_value), (1u, "a"));
+    /// assert_eq!((*first_key, *first_value), (1, "a"));
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn iter(&self) -> Iter<K, V> {
@@ -1225,9 +1201,9 @@ pub fn iter(&self) -> Iter<K, V> {
     /// use std::collections::BTreeMap;
     ///
     /// let mut map = BTreeMap::new();
-    /// map.insert("a", 1u);
-    /// map.insert("b", 2u);
-    /// map.insert("c", 3u);
+    /// map.insert("a", 1);
+    /// map.insert("b", 2);
+    /// map.insert("c", 3);
     ///
     /// // add 10 to the value if the key isn't "a"
     /// for (key, value) in map.iter_mut() {
@@ -1257,9 +1233,9 @@ pub fn iter_mut(&mut self) -> IterMut<K, V> {
     /// use std::collections::BTreeMap;
     ///
     /// let mut map = BTreeMap::new();
-    /// map.insert(1u, "a");
-    /// map.insert(2u, "b");
-    /// map.insert(3u, "c");
+    /// map.insert(1, "a");
+    /// map.insert(2, "b");
+    /// map.insert(3, "c");
     ///
     /// for (key, value) in map.into_iter() {
     ///     println!("{}: {}", key, value);
@@ -1286,11 +1262,11 @@ pub fn into_iter(self) -> IntoIter<K, V> {
     /// use std::collections::BTreeMap;
     ///
     /// let mut a = BTreeMap::new();
-    /// a.insert(1u, "a");
-    /// a.insert(2u, "b");
+    /// a.insert(1, "a");
+    /// a.insert(2, "b");
     ///
-    /// let keys: Vec<uint> = a.keys().cloned().collect();
-    /// assert_eq!(keys, vec![1u,2,]);
+    /// let keys: Vec<usize> = a.keys().cloned().collect();
+    /// assert_eq!(keys, vec![1,2,]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
@@ -1308,8 +1284,8 @@ fn first<A, B>((a, _): (A, B)) -> A { a }
     /// use std::collections::BTreeMap;
     ///
     /// let mut a = BTreeMap::new();
-    /// a.insert(1u, "a");
-    /// a.insert(2u, "b");
+    /// a.insert(1, "a");
+    /// a.insert(2, "b");
     ///
     /// let values: Vec<&str> = a.values().cloned().collect();
     /// assert_eq!(values, vec!["a","b"]);
@@ -1331,11 +1307,11 @@ fn second<A, B>((_, b): (A, B)) -> B { b }
     ///
     /// let mut a = BTreeMap::new();
     /// assert_eq!(a.len(), 0);
-    /// a.insert(1u, "a");
+    /// a.insert(1, "a");
     /// assert_eq!(a.len(), 1);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { self.length }
+    pub fn len(&self) -> usize { self.length }
 
     /// Return true if the map contains no elements.
     ///
@@ -1346,7 +1322,7 @@ pub fn len(&self) -> uint { self.length }
     ///
     /// let mut a = BTreeMap::new();
     /// assert!(a.is_empty());
-    /// a.insert(1u, "a");
+    /// a.insert(1, "a");
     /// assert!(!a.is_empty());
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
@@ -1496,13 +1472,13 @@ impl<K: Ord, V> BTreeMap<K, V> {
     /// use std::collections::Bound::{Included, Unbounded};
     ///
     /// let mut map = BTreeMap::new();
-    /// map.insert(3u, "a");
-    /// map.insert(5u, "b");
-    /// map.insert(8u, "c");
+    /// map.insert(3, "a");
+    /// map.insert(5, "b");
+    /// map.insert(8, "c");
     /// for (&key, &value) in map.range(Included(&4), Included(&8)) {
     ///     println!("{}: {}", key, value);
     /// }
-    /// assert_eq!(Some((&5u, &"b")), map.range(Included(&4), Unbounded).next());
+    /// assert_eq!(Some((&5, &"b")), map.range(Included(&4), Unbounded).next());
     /// ```
     #[unstable(feature = "collections",
                reason = "matches collection reform specification, waiting for dust to settle")]
@@ -1546,7 +1522,7 @@ pub fn range_mut<'a>(&'a mut self, min: Bound<&K>, max: Bound<&K>) -> RangeMut<'
     /// use std::collections::BTreeMap;
     /// use std::collections::btree_map::Entry;
     ///
-    /// let mut count: BTreeMap<&str, uint> = BTreeMap::new();
+    /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
     ///
     /// // count the number of occurrences of letters in the vec
     /// for x in vec!["a","b","a","c","a","b"].iter() {
@@ -1561,12 +1537,10 @@ pub fn range_mut<'a>(&'a mut self, min: Bound<&K>, max: Bound<&K>) -> RangeMut<'
     ///     }
     /// }
     ///
-    /// assert_eq!(count["a"], 3u);
+    /// assert_eq!(count["a"], 3);
     /// ```
-    /// The key must have the same ordering before or after `.to_owned()` is called.
-    #[unstable(feature = "collections",
-               reason = "precise API still under development")]
-    pub fn entry<'a>(&'a mut self, mut key: K) -> Entry<'a, K, V> {
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub fn entry(&mut self, mut key: K) -> Entry<K, V> {
         // same basic logic of `swap` and `pop`, blended together
         let mut stack = stack::PartialSearchStack::new(self);
         loop {
@@ -1616,13 +1590,14 @@ mod test {
     use prelude::*;
     use std::iter::range_inclusive;
 
-    use super::{BTreeMap, Occupied, Vacant};
+    use super::BTreeMap;
+    use super::Entry::{Occupied, Vacant};
     use Bound::{self, Included, Excluded, Unbounded};
 
     #[test]
     fn test_basic_large() {
         let mut map = BTreeMap::new();
-        let size = 10000u;
+        let size = 10000;
         assert_eq!(map.len(), 0);
 
         for i in 0..size {
@@ -1669,7 +1644,7 @@ fn test_basic_small() {
         let mut map = BTreeMap::new();
         assert_eq!(map.remove(&1), None);
         assert_eq!(map.get(&1), None);
-        assert_eq!(map.insert(1u, 1u), None);
+        assert_eq!(map.insert(1, 1), None);
         assert_eq!(map.get(&1), Some(&1));
         assert_eq!(map.insert(1, 2), Some(1));
         assert_eq!(map.get(&1), Some(&2));
@@ -1682,12 +1657,12 @@ fn test_basic_small() {
 
     #[test]
     fn test_iter() {
-        let size = 10000u;
+        let size = 10000;
 
         // Forwards
-        let mut map: BTreeMap<uint, uint> = (0..size).map(|i| (i, i)).collect();
+        let mut map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
 
-        fn test<T>(size: uint, mut iter: T) where T: Iterator<Item=(uint, uint)> {
+        fn test<T>(size: usize, mut iter: T) where T: Iterator<Item=(usize, usize)> {
             for i in 0..size {
                 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
                 assert_eq!(iter.next().unwrap(), (i, i));
@@ -1702,12 +1677,12 @@ fn test<T>(size: uint, mut iter: T) where T: Iterator<Item=(uint, uint)> {
 
     #[test]
     fn test_iter_rev() {
-        let size = 10000u;
+        let size = 10000;
 
         // Forwards
-        let mut map: BTreeMap<uint, uint> = (0..size).map(|i| (i, i)).collect();
+        let mut map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
 
-        fn test<T>(size: uint, mut iter: T) where T: Iterator<Item=(uint, uint)> {
+        fn test<T>(size: usize, mut iter: T) where T: Iterator<Item=(usize, usize)> {
             for i in 0..size {
                 assert_eq!(iter.size_hint(), (size - i, Some(size - i)));
                 assert_eq!(iter.next().unwrap(), (size - i - 1, size - i - 1));
@@ -1722,13 +1697,13 @@ fn test<T>(size: uint, mut iter: T) where T: Iterator<Item=(uint, uint)> {
 
     #[test]
     fn test_iter_mixed() {
-        let size = 10000u;
+        let size = 10000;
 
         // Forwards
-        let mut map: BTreeMap<uint, uint> = (0..size).map(|i| (i, i)).collect();
+        let mut map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
 
-        fn test<T>(size: uint, mut iter: T)
-                where T: Iterator<Item=(uint, uint)> + DoubleEndedIterator {
+        fn test<T>(size: usize, mut iter: T)
+                where T: Iterator<Item=(usize, usize)> + DoubleEndedIterator {
             for i in 0..size / 4 {
                 assert_eq!(iter.size_hint(), (size - i * 2, Some(size - i * 2)));
                 assert_eq!(iter.next().unwrap(), (i, i));
@@ -1748,13 +1723,13 @@ fn test<T>(size: uint, mut iter: T)
 
     #[test]
     fn test_range_small() {
-        let size = 5u;
+        let size = 5;
 
         // Forwards
-        let map: BTreeMap<uint, uint> = (0..size).map(|i| (i, i)).collect();
+        let map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
 
-        let mut j = 0u;
-        for ((&k, &v), i) in map.range(Included(&2), Unbounded).zip(2u..size) {
+        let mut j = 0;
+        for ((&k, &v), i) in map.range(Included(&2), Unbounded).zip(2..size) {
             assert_eq!(k, i);
             assert_eq!(v, i);
             j += 1;
@@ -1764,10 +1739,10 @@ fn test_range_small() {
 
     #[test]
     fn test_range_1000() {
-        let size = 1000u;
-        let map: BTreeMap<uint, uint> = (0..size).map(|i| (i, i)).collect();
+        let size = 1000;
+        let map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
 
-        fn test(map: &BTreeMap<uint, uint>, size: uint, min: Bound<&uint>, max: Bound<&uint>) {
+        fn test(map: &BTreeMap<u32, u32>, size: u32, min: Bound<&u32>, max: Bound<&u32>) {
             let mut kvs = map.range(min, max).map(|(&k, &v)| (k, v));
             let mut pairs = (0..size).map(|i| (i, i));
 
@@ -1787,8 +1762,8 @@ fn test(map: &BTreeMap<uint, uint>, size: uint, min: Bound<&uint>, max: Bound<&u
 
     #[test]
     fn test_range() {
-        let size = 200u;
-        let map: BTreeMap<uint, uint> = (0..size).map(|i| (i, i)).collect();
+        let size = 200;
+        let map: BTreeMap<_, _> = (0..size).map(|i| (i, i)).collect();
 
         for i in 0..size {
             for j in i..size {
@@ -1808,7 +1783,7 @@ fn test_range() {
     fn test_entry(){
         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
 
-        let mut map: BTreeMap<int, int> = xs.iter().map(|&x| x).collect();
+        let mut map: BTreeMap<_, _> = xs.iter().map(|&x| x).collect();
 
         // Existing key (insert)
         match map.entry(1) {
@@ -1872,7 +1847,7 @@ mod bench {
 
     #[bench]
     pub fn insert_rand_100(b: &mut Bencher) {
-        let mut m : BTreeMap<uint,uint> = BTreeMap::new();
+        let mut m = BTreeMap::new();
         insert_rand_n(100, &mut m, b,
                       |m, i| { m.insert(i, 1); },
                       |m, i| { m.remove(&i); });
@@ -1880,7 +1855,7 @@ pub fn insert_rand_100(b: &mut Bencher) {
 
     #[bench]
     pub fn insert_rand_10_000(b: &mut Bencher) {
-        let mut m : BTreeMap<uint,uint> = BTreeMap::new();
+        let mut m = BTreeMap::new();
         insert_rand_n(10_000, &mut m, b,
                       |m, i| { m.insert(i, 1); },
                       |m, i| { m.remove(&i); });
@@ -1889,7 +1864,7 @@ pub fn insert_rand_10_000(b: &mut Bencher) {
     // Insert seq
     #[bench]
     pub fn insert_seq_100(b: &mut Bencher) {
-        let mut m : BTreeMap<uint,uint> = BTreeMap::new();
+        let mut m = BTreeMap::new();
         insert_seq_n(100, &mut m, b,
                      |m, i| { m.insert(i, 1); },
                      |m, i| { m.remove(&i); });
@@ -1897,7 +1872,7 @@ pub fn insert_seq_100(b: &mut Bencher) {
 
     #[bench]
     pub fn insert_seq_10_000(b: &mut Bencher) {
-        let mut m : BTreeMap<uint,uint> = BTreeMap::new();
+        let mut m = BTreeMap::new();
         insert_seq_n(10_000, &mut m, b,
                      |m, i| { m.insert(i, 1); },
                      |m, i| { m.remove(&i); });
@@ -1906,7 +1881,7 @@ pub fn insert_seq_10_000(b: &mut Bencher) {
     // Find rand
     #[bench]
     pub fn find_rand_100(b: &mut Bencher) {
-        let mut m : BTreeMap<uint,uint> = BTreeMap::new();
+        let mut m = BTreeMap::new();
         find_rand_n(100, &mut m, b,
                     |m, i| { m.insert(i, 1); },
                     |m, i| { m.get(&i); });
@@ -1914,7 +1889,7 @@ pub fn find_rand_100(b: &mut Bencher) {
 
     #[bench]
     pub fn find_rand_10_000(b: &mut Bencher) {
-        let mut m : BTreeMap<uint,uint> = BTreeMap::new();
+        let mut m = BTreeMap::new();
         find_rand_n(10_000, &mut m, b,
                     |m, i| { m.insert(i, 1); },
                     |m, i| { m.get(&i); });
@@ -1923,7 +1898,7 @@ pub fn find_rand_10_000(b: &mut Bencher) {
     // Find seq
     #[bench]
     pub fn find_seq_100(b: &mut Bencher) {
-        let mut m : BTreeMap<uint,uint> = BTreeMap::new();
+        let mut m = BTreeMap::new();
         find_seq_n(100, &mut m, b,
                    |m, i| { m.insert(i, 1); },
                    |m, i| { m.get(&i); });
@@ -1931,14 +1906,14 @@ pub fn find_seq_100(b: &mut Bencher) {
 
     #[bench]
     pub fn find_seq_10_000(b: &mut Bencher) {
-        let mut m : BTreeMap<uint,uint> = BTreeMap::new();
+        let mut m = BTreeMap::new();
         find_seq_n(10_000, &mut m, b,
                    |m, i| { m.insert(i, 1); },
                    |m, i| { m.get(&i); });
     }
 
-    fn bench_iter(b: &mut Bencher, size: uint) {
-        let mut map = BTreeMap::<uint, uint>::new();
+    fn bench_iter(b: &mut Bencher, size: i32) {
+        let mut map = BTreeMap::<i32, i32>::new();
         let mut rng = weak_rng();
 
         for _ in 0..size {
index 8fdfe9ed56a4882014fdcce5f8e1dea865bbbaa1..bfe74cc6fb46cfbfe12855ff343bf88e400bfd2d 100644 (file)
@@ -65,7 +65,7 @@ pub struct Node<K, V> {
     //
     // Note: instead of accessing this field directly, please call the `len()` method, which should
     // be more stable in the face of representation changes.
-    _len: uint,
+    _len: usize,
 
     // FIXME(gereeter) It shouldn't be necessary to store the capacity in every node, as it should
     // be constant throughout the tree. Once a solution to this is found, it might be possible to
@@ -74,7 +74,7 @@ pub struct Node<K, V> {
     //
     // Note: instead of accessing this field directly, please call the `capacity()` method, which
     // should be more stable in the face of representation changes.
-    _capacity: uint,
+    _capacity: usize,
 }
 
 struct NodeSlice<'a, K: 'a, V: 'a> {
@@ -102,7 +102,7 @@ struct MutNodeSlice<'a, K: 'a, V: 'a> {
 ///
 /// Fails if `target_alignment` is not a power of two.
 #[inline]
-fn round_up_to_next(unrounded: uint, target_alignment: uint) -> uint {
+fn round_up_to_next(unrounded: usize, target_alignment: usize) -> usize {
     assert!(num::UnsignedInt::is_power_of_two(target_alignment));
     (unrounded + target_alignment - 1) & !(target_alignment - 1)
 }
@@ -120,10 +120,10 @@ fn test_rounding() {
 // Returns a tuple of (val_offset, edge_offset),
 // from the start of a mallocated array.
 #[inline]
-fn calculate_offsets(keys_size: uint,
-                     vals_size: uint, vals_align: uint,
-                     edges_align: uint)
-                     -> (uint, uint) {
+fn calculate_offsets(keys_size: usize,
+                     vals_size: usize, vals_align: usize,
+                     edges_align: usize)
+                     -> (usize, usize) {
     let vals_offset = round_up_to_next(keys_size, vals_align);
     let end_of_vals = vals_offset + vals_size;
 
@@ -135,10 +135,10 @@ fn calculate_offsets(keys_size: uint,
 // Returns a tuple of (minimum required alignment, array_size),
 // from the start of a mallocated array.
 #[inline]
-fn calculate_allocation(keys_size: uint, keys_align: uint,
-                        vals_size: uint, vals_align: uint,
-                        edges_size: uint, edges_align: uint)
-                        -> (uint, uint) {
+fn calculate_allocation(keys_size: usize, keys_align: usize,
+                        vals_size: usize, vals_align: usize,
+                        edges_size: usize, edges_align: usize)
+                        -> (usize, usize) {
     let (_, edges_offset) = calculate_offsets(keys_size,
                                               vals_size, vals_align,
                                                          edges_align);
@@ -159,7 +159,7 @@ fn test_offset_calculation() {
     assert_eq!(calculate_offsets(6, 12, 4, 8), (8, 24));
 }
 
-fn calculate_allocation_generic<K, V>(capacity: uint, is_leaf: bool) -> (uint, uint) {
+fn calculate_allocation_generic<K, V>(capacity: usize, is_leaf: bool) -> (usize, usize) {
     let (keys_size, keys_align) = (capacity * mem::size_of::<K>(), mem::min_align_of::<K>());
     let (vals_size, vals_align) = (capacity * mem::size_of::<V>(), mem::min_align_of::<V>());
     let (edges_size, edges_align) = if is_leaf {
@@ -175,7 +175,7 @@ fn calculate_allocation_generic<K, V>(capacity: uint, is_leaf: bool) -> (uint, u
     )
 }
 
-fn calculate_offsets_generic<K, V>(capacity: uint, is_leaf: bool) -> (uint, uint) {
+fn calculate_offsets_generic<K, V>(capacity: usize, is_leaf: bool) -> (usize, usize) {
     let keys_size = capacity * mem::size_of::<K>();
     let vals_size = capacity * mem::size_of::<V>();
     let vals_align = mem::min_align_of::<V>();
@@ -203,16 +203,16 @@ unsafe fn from_slice(slice: &[T]) -> RawItems<T> {
         RawItems::from_parts(slice.as_ptr(), slice.len())
     }
 
-    unsafe fn from_parts(ptr: *const T, len: uint) -> RawItems<T> {
+    unsafe fn from_parts(ptr: *const T, len: usize) -> RawItems<T> {
         if mem::size_of::<T>() == 0 {
             RawItems {
                 head: ptr,
-                tail: (ptr as uint + len) as *const T,
+                tail: (ptr as usize + len) as *const T,
             }
         } else {
             RawItems {
                 head: ptr,
-                tail: ptr.offset(len as int),
+                tail: ptr.offset(len as isize),
             }
         }
     }
@@ -221,7 +221,7 @@ unsafe fn push(&mut self, val: T) {
         ptr::write(self.tail as *mut T, val);
 
         if mem::size_of::<T>() == 0 {
-            self.tail = (self.tail as uint + 1) as *const T;
+            self.tail = (self.tail as usize + 1) as *const T;
         } else {
             self.tail = self.tail.offset(1);
         }
@@ -239,7 +239,7 @@ fn next(&mut self) -> Option<T> {
                 let ret = Some(ptr::read(self.head));
 
                 if mem::size_of::<T>() == 0 {
-                    self.head = (self.head as uint + 1) as *const T;
+                    self.head = (self.head as usize + 1) as *const T;
                 } else {
                     self.head = self.head.offset(1);
                 }
@@ -257,7 +257,7 @@ fn next_back(&mut self) -> Option<T> {
         } else {
             unsafe {
                 if mem::size_of::<T>() == 0 {
-                    self.tail = (self.tail as uint - 1) as *const T;
+                    self.tail = (self.tail as usize - 1) as *const T;
                 } else {
                     self.tail = self.tail.offset(-1);
                 }
@@ -299,7 +299,7 @@ fn drop(&mut self) {
 impl<K, V> Node<K, V> {
     /// Make a new internal node. The caller must initialize the result to fix the invariant that
     /// there are `len() + 1` edges.
-    unsafe fn new_internal(capacity: uint) -> Node<K, V> {
+    unsafe fn new_internal(capacity: usize) -> Node<K, V> {
         let (alignment, size) = calculate_allocation_generic::<K, V>(capacity, false);
 
         let buffer = heap::allocate(size, alignment);
@@ -309,15 +309,15 @@ unsafe fn new_internal(capacity: uint) -> Node<K, V> {
 
         Node {
             keys: Unique(buffer as *mut K),
-            vals: Unique(buffer.offset(vals_offset as int) as *mut V),
-            edges: Unique(buffer.offset(edges_offset as int) as *mut Node<K, V>),
+            vals: Unique(buffer.offset(vals_offset as isize) as *mut V),
+            edges: Unique(buffer.offset(edges_offset as isize) as *mut Node<K, V>),
             _len: 0,
             _capacity: capacity,
         }
     }
 
     /// Make a new leaf node
-    fn new_leaf(capacity: uint) -> Node<K, V> {
+    fn new_leaf(capacity: usize) -> Node<K, V> {
         let (alignment, size) = calculate_allocation_generic::<K, V>(capacity, true);
 
         let buffer = unsafe { heap::allocate(size, alignment) };
@@ -327,7 +327,7 @@ fn new_leaf(capacity: uint) -> Node<K, V> {
 
         Node {
             keys: Unique(buffer as *mut K),
-            vals: Unique(unsafe { buffer.offset(vals_offset as int) as *mut V }),
+            vals: Unique(unsafe { buffer.offset(vals_offset as isize) as *mut V }),
             edges: Unique(ptr::null_mut()),
             _len: 0,
             _capacity: capacity,
@@ -479,15 +479,15 @@ fn clone(&self) -> Node<K, V> {
 ///
 /// ```rust,ignore
 /// struct Nasty<'a> {
-///     first: &'a Node<uint, uint>,
-///     second: &'a Node<uint, uint>,
+///     first: &'a Node<usize, usize>,
+///     second: &'a Node<usize, usize>,
 ///     flag: &'a Cell<bool>,
 /// }
 ///
 /// impl<'a> Deref for Nasty<'a> {
-///     type Target = Node<uint, uint>;
+///     type Target = Node<usize, usize>;
 ///
-///     fn deref(&self) -> &Node<uint, uint> {
+///     fn deref(&self) -> &Node<usize, usize> {
 ///         if self.flag.get() {
 ///             &*self.second
 ///         } else {
@@ -524,7 +524,7 @@ fn clone(&self) -> Node<K, V> {
 #[derive(Copy)]
 pub struct Handle<NodeRef, Type, NodeType> {
     node: NodeRef,
-    index: uint
+    index: usize
 }
 
 pub mod handle {
@@ -546,7 +546,7 @@ pub fn search<Q: ?Sized, NodeRef: Deref<Target=Node<K, V>>>(node: NodeRef, key:
                   -> SearchResult<NodeRef> where Q: BorrowFrom<K> + Ord {
         // FIXME(Gankro): Tune when to search linear or binary based on B (and maybe K/V).
         // For the B configured as of this writing (B = 6), binary search was *significantly*
-        // worse for uints.
+        // worse for usizes.
         match node.as_slices_internal().search_linear(key) {
             (index, true) => Found(Handle { node: node, index: index }),
             (index, false) => GoDown(Handle { node: node, index: index }),
@@ -557,12 +557,12 @@ pub fn search<Q: ?Sized, NodeRef: Deref<Target=Node<K, V>>>(node: NodeRef, key:
 // Public interface
 impl <K, V> Node<K, V> {
     /// Make a leaf root from scratch
-    pub fn make_leaf_root(b: uint) -> Node<K, V> {
+    pub fn make_leaf_root(b: usize) -> Node<K, V> {
         Node::new_leaf(capacity_from_b(b))
     }
 
     /// Make an internal root and swap it with an old root
-    pub fn make_internal_root(left_and_out: &mut Node<K,V>, b: uint, key: K, value: V,
+    pub fn make_internal_root(left_and_out: &mut Node<K,V>, b: usize, key: K, value: V,
             right: Node<K,V>) {
         let node = mem::replace(left_and_out, unsafe { Node::new_internal(capacity_from_b(b)) });
         left_and_out._len = 1;
@@ -575,12 +575,12 @@ pub fn make_internal_root(left_and_out: &mut Node<K,V>, b: uint, key: K, value:
     }
 
     /// How many key-value pairs the node contains
-    pub fn len(&self) -> uint {
+    pub fn len(&self) -> usize {
         self._len
     }
 
     /// How many key-value pairs the node can fit
-    pub fn capacity(&self) -> uint {
+    pub fn capacity(&self) -> usize {
         self._capacity
     }
 
@@ -669,7 +669,7 @@ pub fn into_edge_mut(self) -> &'a mut Node<K, V> {
 
 impl<K, V, NodeRef: Deref<Target=Node<K, V>>> Handle<NodeRef, handle::Edge, handle::Internal> {
     // This doesn't exist because there are no uses for it,
-    // but is fine to add, analagous to edge_mut.
+    // but is fine to add, analogous to edge_mut.
     //
     // /// Returns a reference to the edge pointed-to by this handle. This should not be
     // /// confused with `node`, which references the parent node of what is returned here.
@@ -1038,7 +1038,7 @@ impl<K, V> Node<K, V> {
     /// # Panics (in debug build)
     ///
     /// Panics if the given index is out of bounds.
-    pub fn kv_handle(&mut self, index: uint) -> Handle<&mut Node<K, V>, handle::KV,
+    pub fn kv_handle(&mut self, index: usize) -> Handle<&mut Node<K, V>, handle::KV,
                                                        handle::LeafOrInternal> {
         // Necessary for correctness, but in a private module
         debug_assert!(index < self.len(), "kv_handle index out of bounds");
@@ -1114,15 +1114,15 @@ unsafe fn push_edge(&mut self, edge: Node<K, V>) {
 
     // This must be followed by insert_edge on an internal node.
     #[inline]
-    unsafe fn insert_kv(&mut self, index: uint, key: K, val: V) -> &mut V {
+    unsafe fn insert_kv(&mut self, index: usize, key: K, val: V) -> &mut V {
         ptr::copy_memory(
-            self.keys_mut().as_mut_ptr().offset(index as int + 1),
-            self.keys().as_ptr().offset(index as int),
+            self.keys_mut().as_mut_ptr().offset(index as isize + 1),
+            self.keys().as_ptr().offset(index as isize),
             self.len() - index
         );
         ptr::copy_memory(
-            self.vals_mut().as_mut_ptr().offset(index as int + 1),
-            self.vals().as_ptr().offset(index as int),
+            self.vals_mut().as_mut_ptr().offset(index as isize + 1),
+            self.vals().as_ptr().offset(index as isize),
             self.len() - index
         );
 
@@ -1136,10 +1136,10 @@ unsafe fn insert_kv(&mut self, index: uint, key: K, val: V) -> &mut V {
 
     // This can only be called immediately after a call to insert_kv.
     #[inline]
-    unsafe fn insert_edge(&mut self, index: uint, edge: Node<K, V>) {
+    unsafe fn insert_edge(&mut self, index: usize, edge: Node<K, V>) {
         ptr::copy_memory(
-            self.edges_mut().as_mut_ptr().offset(index as int + 1),
-            self.edges().as_ptr().offset(index as int),
+            self.edges_mut().as_mut_ptr().offset(index as isize + 1),
+            self.edges().as_ptr().offset(index as isize),
             self.len() - index
         );
         ptr::write(self.edges_mut().get_unchecked_mut(index), edge);
@@ -1166,18 +1166,18 @@ unsafe fn pop_edge(&mut self) -> Node<K, V> {
 
     // This must be followed by remove_edge on an internal node.
     #[inline]
-    unsafe fn remove_kv(&mut self, index: uint) -> (K, V) {
+    unsafe fn remove_kv(&mut self, index: usize) -> (K, V) {
         let key = ptr::read(self.keys().get_unchecked(index));
         let val = ptr::read(self.vals().get_unchecked(index));
 
         ptr::copy_memory(
-            self.keys_mut().as_mut_ptr().offset(index as int),
-            self.keys().as_ptr().offset(index as int + 1),
+            self.keys_mut().as_mut_ptr().offset(index as isize),
+            self.keys().as_ptr().offset(index as isize + 1),
             self.len() - index - 1
         );
         ptr::copy_memory(
-            self.vals_mut().as_mut_ptr().offset(index as int),
-            self.vals().as_ptr().offset(index as int + 1),
+            self.vals_mut().as_mut_ptr().offset(index as isize),
+            self.vals().as_ptr().offset(index as isize + 1),
             self.len() - index - 1
         );
 
@@ -1188,12 +1188,12 @@ unsafe fn remove_kv(&mut self, index: uint) -> (K, V) {
 
     // This can only be called immediately after a call to remove_kv.
     #[inline]
-    unsafe fn remove_edge(&mut self, index: uint) -> Node<K, V> {
+    unsafe fn remove_edge(&mut self, index: usize) -> Node<K, V> {
         let edge = ptr::read(self.edges().get_unchecked(index));
 
         ptr::copy_memory(
-            self.edges_mut().as_mut_ptr().offset(index as int),
-            self.edges().as_ptr().offset(index as int + 1),
+            self.edges_mut().as_mut_ptr().offset(index as isize),
+            self.edges().as_ptr().offset(index as isize + 1),
             self.len() - index + 1
         );
 
@@ -1220,18 +1220,18 @@ fn split(&mut self) -> (K, V, Node<K, V>) {
             let right_offset = self.len() - right.len();
             ptr::copy_nonoverlapping_memory(
                 right.keys_mut().as_mut_ptr(),
-                self.keys().as_ptr().offset(right_offset as int),
+                self.keys().as_ptr().offset(right_offset as isize),
                 right.len()
             );
             ptr::copy_nonoverlapping_memory(
                 right.vals_mut().as_mut_ptr(),
-                self.vals().as_ptr().offset(right_offset as int),
+                self.vals().as_ptr().offset(right_offset as isize),
                 right.len()
             );
             if !self.is_leaf() {
                 ptr::copy_nonoverlapping_memory(
                     right.edges_mut().as_mut_ptr(),
-                    self.edges().as_ptr().offset(right_offset as int),
+                    self.edges().as_ptr().offset(right_offset as isize),
                     right.len() + 1
                 );
             }
@@ -1260,18 +1260,18 @@ fn absorb(&mut self, key: K, val: V, mut right: Node<K, V>) {
             ptr::write(self.vals_mut().get_unchecked_mut(old_len), val);
 
             ptr::copy_nonoverlapping_memory(
-                self.keys_mut().as_mut_ptr().offset(old_len as int + 1),
+                self.keys_mut().as_mut_ptr().offset(old_len as isize + 1),
                 right.keys().as_ptr(),
                 right.len()
             );
             ptr::copy_nonoverlapping_memory(
-                self.vals_mut().as_mut_ptr().offset(old_len as int + 1),
+                self.vals_mut().as_mut_ptr().offset(old_len as isize + 1),
                 right.vals().as_ptr(),
                 right.len()
             );
             if !self.is_leaf() {
                 ptr::copy_nonoverlapping_memory(
-                    self.edges_mut().as_mut_ptr().offset(old_len as int + 1),
+                    self.edges_mut().as_mut_ptr().offset(old_len as isize + 1),
                     right.edges().as_ptr(),
                     right.len() + 1
                 );
@@ -1284,12 +1284,12 @@ fn absorb(&mut self, key: K, val: V, mut right: Node<K, V>) {
 }
 
 /// Get the capacity of a node from the order of the parent B-Tree
-fn capacity_from_b(b: uint) -> uint {
+fn capacity_from_b(b: usize) -> usize {
     2 * b - 1
 }
 
 /// Get the minimum load of a node from its capacity
-fn min_load_from_capacity(cap: uint) -> uint {
+fn min_load_from_capacity(cap: usize) -> usize {
     // B - 1
     cap / 2
 }
@@ -1334,7 +1334,7 @@ struct MoveTraversalImpl<K, V> {
 
     // For deallocation when we are done iterating.
     ptr: *mut u8,
-    capacity: uint,
+    capacity: usize,
     is_leaf: bool
 }
 
@@ -1490,7 +1490,7 @@ macro_rules! node_slice_impl {
      $as_slices_internal:ident, $index:ident, $iter:ident) => {
         impl<'a, K: Ord + 'a, V: 'a> $NodeSlice<'a, K, V> {
             /// Performs linear search in a slice. Returns a tuple of (index, is_exact_match).
-            fn search_linear<Q: ?Sized>(&self, key: &Q) -> (uint, bool)
+            fn search_linear<Q: ?Sized>(&self, key: &Q) -> (usize, bool)
                     where Q: BorrowFrom<K> + Ord {
                 for (i, k) in self.keys.iter().enumerate() {
                     match key.cmp(BorrowFrom::borrow_from(k)) {
index 1997fe189be44d21baed70551e5bfb7f9ba14764..c888a261f9d21851e426c654c687eca504b0a283 100644 (file)
@@ -101,7 +101,7 @@ pub fn new() -> BTreeSet<T> {
     /// B cannot be less than 2.
     #[unstable(feature = "collections",
                reason = "probably want this to be on the type, eventually")]
-    pub fn with_b(b: uint) -> BTreeSet<T> {
+    pub fn with_b(b: usize) -> BTreeSet<T> {
         BTreeSet { map: BTreeMap::with_b(b) }
     }
 }
@@ -114,14 +114,14 @@ impl<T> BTreeSet<T> {
     /// ```
     /// use std::collections::BTreeSet;
     ///
-    /// let set: BTreeSet<uint> = [1u, 2, 3, 4].iter().map(|&x| x).collect();
+    /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().map(|&x| x).collect();
     ///
     /// for x in set.iter() {
     ///     println!("{}", x);
     /// }
     ///
-    /// let v: Vec<uint> = set.iter().map(|&x| x).collect();
-    /// assert_eq!(v, vec![1u,2,3,4]);
+    /// let v: Vec<usize> = set.iter().map(|&x| x).collect();
+    /// assert_eq!(v, vec![1,2,3,4]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn iter(&self) -> Iter<T> {
@@ -135,10 +135,10 @@ pub fn iter(&self) -> Iter<T> {
     /// ```
     /// use std::collections::BTreeSet;
     ///
-    /// let set: BTreeSet<uint> = [1u, 2, 3, 4].iter().map(|&x| x).collect();
+    /// let set: BTreeSet<usize> = [1, 2, 3, 4].iter().map(|&x| x).collect();
     ///
-    /// let v: Vec<uint> = set.into_iter().collect();
-    /// assert_eq!(v, vec![1u,2,3,4]);
+    /// let v: Vec<usize> = set.into_iter().collect();
+    /// assert_eq!(v, vec![1,2,3,4]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn into_iter(self) -> IntoIter<T> {
@@ -162,13 +162,13 @@ impl<T: Ord> BTreeSet<T> {
     /// use std::collections::Bound::{Included, Unbounded};
     ///
     /// let mut set = BTreeSet::new();
-    /// set.insert(3u);
-    /// set.insert(5u);
-    /// set.insert(8u);
+    /// set.insert(3);
+    /// set.insert(5);
+    /// set.insert(8);
     /// for &elem in set.range(Included(&4), Included(&8)) {
     ///     println!("{}", elem);
     /// }
-    /// assert_eq!(Some(&5u), set.range(Included(&4), Unbounded).next());
+    /// assert_eq!(Some(&5), set.range(Included(&4), Unbounded).next());
     /// ```
     #[unstable(feature = "collections",
                reason = "matches collection reform specification, waiting for dust to settle")]
@@ -189,15 +189,15 @@ impl<T: Ord> BTreeSet<T> {
     /// use std::collections::BTreeSet;
     ///
     /// let mut a = BTreeSet::new();
-    /// a.insert(1u);
-    /// a.insert(2u);
+    /// a.insert(1);
+    /// a.insert(2);
     ///
     /// let mut b = BTreeSet::new();
-    /// b.insert(2u);
-    /// b.insert(3u);
+    /// b.insert(2);
+    /// b.insert(3);
     ///
-    /// let diff: Vec<uint> = a.difference(&b).cloned().collect();
-    /// assert_eq!(diff, vec![1u]);
+    /// let diff: Vec<usize> = a.difference(&b).cloned().collect();
+    /// assert_eq!(diff, vec![1]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
@@ -212,15 +212,15 @@ pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T> {
     /// use std::collections::BTreeSet;
     ///
     /// let mut a = BTreeSet::new();
-    /// a.insert(1u);
-    /// a.insert(2u);
+    /// a.insert(1);
+    /// a.insert(2);
     ///
     /// let mut b = BTreeSet::new();
-    /// b.insert(2u);
-    /// b.insert(3u);
+    /// b.insert(2);
+    /// b.insert(3);
     ///
-    /// let sym_diff: Vec<uint> = a.symmetric_difference(&b).cloned().collect();
-    /// assert_eq!(sym_diff, vec![1u,3]);
+    /// let sym_diff: Vec<usize> = a.symmetric_difference(&b).cloned().collect();
+    /// assert_eq!(sym_diff, vec![1,3]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>)
@@ -236,15 +236,15 @@ pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>)
     /// use std::collections::BTreeSet;
     ///
     /// let mut a = BTreeSet::new();
-    /// a.insert(1u);
-    /// a.insert(2u);
+    /// a.insert(1);
+    /// a.insert(2);
     ///
     /// let mut b = BTreeSet::new();
-    /// b.insert(2u);
-    /// b.insert(3u);
+    /// b.insert(2);
+    /// b.insert(3);
     ///
-    /// let intersection: Vec<uint> = a.intersection(&b).cloned().collect();
-    /// assert_eq!(intersection, vec![2u]);
+    /// let intersection: Vec<usize> = a.intersection(&b).cloned().collect();
+    /// assert_eq!(intersection, vec![2]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>)
@@ -260,13 +260,13 @@ pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>)
     /// use std::collections::BTreeSet;
     ///
     /// let mut a = BTreeSet::new();
-    /// a.insert(1u);
+    /// a.insert(1);
     ///
     /// let mut b = BTreeSet::new();
-    /// b.insert(2u);
+    /// b.insert(2);
     ///
-    /// let union: Vec<uint> = a.union(&b).cloned().collect();
-    /// assert_eq!(union, vec![1u,2]);
+    /// let union: Vec<usize> = a.union(&b).cloned().collect();
+    /// assert_eq!(union, vec![1,2]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
@@ -286,7 +286,7 @@ pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T> {
     /// assert_eq!(v.len(), 1);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { self.map.len() }
+    pub fn len(&self) -> usize { self.map.len() }
 
     /// Returns true if the set contains no elements
     ///
@@ -625,7 +625,7 @@ impl<'a, T> Iterator for Iter<'a, T> {
     type Item = &'a T;
 
     fn next(&mut self) -> Option<&'a T> { self.iter.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
@@ -640,7 +640,7 @@ impl<T> Iterator for IntoIter<T> {
     type Item = T;
 
     fn next(&mut self) -> Option<T> { self.iter.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> DoubleEndedIterator for IntoIter<T> {
@@ -770,23 +770,23 @@ fn test_hash() {
     }
 
     struct Counter<'a, 'b> {
-        i: &'a mut uint,
-        expected: &'b [int],
+        i: &'a mut usize,
+        expected: &'b [i32],
     }
 
-    impl<'a, 'b, 'c> FnMut<(&'c int,)> for Counter<'a, 'b> {
+    impl<'a, 'b, 'c> FnMut<(&'c i32,)> for Counter<'a, 'b> {
         type Output = bool;
 
-        extern "rust-call" fn call_mut(&mut self, (&x,): (&'c int,)) -> bool {
+        extern "rust-call" fn call_mut(&mut self, (&x,): (&'c i32,)) -> bool {
             assert_eq!(x, self.expected[*self.i]);
             *self.i += 1;
             true
         }
     }
 
-    fn check<F>(a: &[int], b: &[int], expected: &[int], f: F) where
+    fn check<F>(a: &[i32], b: &[i32], expected: &[i32], f: F) where
         // FIXME Replace Counter with `Box<FnMut(_) -> _>`
-        F: FnOnce(&BTreeSet<int>, &BTreeSet<int>, Counter) -> bool,
+        F: FnOnce(&BTreeSet<i32>, &BTreeSet<i32>, Counter) -> bool,
     {
         let mut set_a = BTreeSet::new();
         let mut set_b = BTreeSet::new();
@@ -801,7 +801,7 @@ fn check<F>(a: &[int], b: &[int], expected: &[int], f: F) where
 
     #[test]
     fn test_intersection() {
-        fn check_intersection(a: &[int], b: &[int], expected: &[int]) {
+        fn check_intersection(a: &[i32], b: &[i32], expected: &[i32]) {
             check(a, b, expected, |x, y, f| x.intersection(y).all(f))
         }
 
@@ -817,7 +817,7 @@ fn check_intersection(a: &[int], b: &[int], expected: &[int]) {
 
     #[test]
     fn test_difference() {
-        fn check_difference(a: &[int], b: &[int], expected: &[int]) {
+        fn check_difference(a: &[i32], b: &[i32], expected: &[i32]) {
             check(a, b, expected, |x, y, f| x.difference(y).all(f))
         }
 
@@ -834,8 +834,7 @@ fn check_difference(a: &[int], b: &[int], expected: &[int]) {
 
     #[test]
     fn test_symmetric_difference() {
-        fn check_symmetric_difference(a: &[int], b: &[int],
-                                      expected: &[int]) {
+        fn check_symmetric_difference(a: &[i32], b: &[i32], expected: &[i32]) {
             check(a, b, expected, |x, y, f| x.symmetric_difference(y).all(f))
         }
 
@@ -849,8 +848,7 @@ fn check_symmetric_difference(a: &[int], b: &[int],
 
     #[test]
     fn test_union() {
-        fn check_union(a: &[int], b: &[int],
-                                      expected: &[int]) {
+        fn check_union(a: &[i32], b: &[i32], expected: &[i32]) {
             check(a, b, expected, |x, y, f| x.union(y).all(f))
         }
 
@@ -865,9 +863,9 @@ fn check_union(a: &[int], b: &[int],
     #[test]
     fn test_zip() {
         let mut x = BTreeSet::new();
-        x.insert(5u);
-        x.insert(12u);
-        x.insert(11u);
+        x.insert(5);
+        x.insert(12);
+        x.insert(11);
 
         let mut y = BTreeSet::new();
         y.insert("foo");
@@ -878,13 +876,13 @@ fn test_zip() {
         let mut z = x.iter().zip(y.iter());
 
         // FIXME: #5801: this needs a type hint to compile...
-        let result: Option<(&uint, & &'static str)> = z.next();
-        assert_eq!(result.unwrap(), (&5u, &("bar")));
+        let result: Option<(&usize, & &'static str)> = z.next();
+        assert_eq!(result.unwrap(), (&5, &("bar")));
 
-        let result: Option<(&uint, & &'static str)> = z.next();
-        assert_eq!(result.unwrap(), (&11u, &("foo")));
+        let result: Option<(&usize, & &'static str)> = z.next();
+        assert_eq!(result.unwrap(), (&11, &("foo")));
 
-        let result: Option<(&uint, & &'static str)> = z.next();
+        let result: Option<(&usize, & &'static str)> = z.next();
         assert!(result.is_none());
     }
 
@@ -892,7 +890,7 @@ fn test_zip() {
     fn test_from_iter() {
         let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 
-        let set: BTreeSet<int> = xs.iter().map(|&x| x).collect();
+        let set: BTreeSet<_> = xs.iter().cloned().collect();
 
         for x in &xs {
             assert!(set.contains(x));
@@ -901,8 +899,8 @@ fn test_from_iter() {
 
     #[test]
     fn test_show() {
-        let mut set: BTreeSet<int> = BTreeSet::new();
-        let empty: BTreeSet<int> = BTreeSet::new();
+        let mut set = BTreeSet::new();
+        let empty = BTreeSet::<i32>::new();
 
         set.insert(1);
         set.insert(2);
index d85e9ee32265e134fcfc9f2858b2eca5baecf26c..748230c5d24cf9765a1dc9ba12fe5c0b64c0ab92 100644 (file)
@@ -35,7 +35,7 @@
 /// A doubly-linked list.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct DList<T> {
-    length: uint,
+    length: usize,
     list_head: Link<T>,
     list_tail: Rawlink<Node<T>>,
 }
@@ -61,7 +61,7 @@ struct Node<T> {
 pub struct Iter<'a, T:'a> {
     head: &'a Link<T>,
     tail: Rawlink<Node<T>>,
-    nelem: uint,
+    nelem: usize,
 }
 
 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
@@ -82,7 +82,7 @@ pub struct IterMut<'a, T:'a> {
     list: &'a mut DList<T>,
     head: Rawlink<Node<T>>,
     tail: Rawlink<Node<T>>,
-    nelem: uint,
+    nelem: usize,
 }
 
 /// An iterator over mutable references to the items of a `DList`.
@@ -345,7 +345,7 @@ pub fn is_empty(&self) -> bool {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint {
+    pub fn len(&self) -> usize {
         self.length
     }
 
@@ -578,7 +578,7 @@ pub fn pop_back(&mut self) -> Option<T> {
     /// assert_eq!(splitted.pop_front(), None);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn split_off(&mut self, at: uint) -> DList<T> {
+    pub fn split_off(&mut self, at: usize) -> DList<T> {
         let len = self.len();
         assert!(at < len, "Cannot split off at a nonexistent index");
         if at == 0 {
@@ -659,7 +659,7 @@ fn next(&mut self) -> Option<&'a A> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         (self.nelem, Some(self.nelem))
     }
 }
@@ -701,7 +701,7 @@ fn next(&mut self) -> Option<&'a mut A> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         (self.nelem, Some(self.nelem))
     }
 }
@@ -810,7 +810,7 @@ impl<A> Iterator for IntoIter<A> {
     fn next(&mut self) -> Option<A> { self.list.pop_front() }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         (self.list.length, Some(self.list.length))
     }
 }
@@ -935,11 +935,11 @@ mod tests {
     use super::{DList, Node};
 
     pub fn check_links<T>(list: &DList<T>) {
-        let mut len = 0u;
+        let mut len = 0;
         let mut last_ptr: Option<&Node<T>> = None;
         let mut node_ptr: &Node<T>;
         match list.list_head {
-            None => { assert_eq!(0u, list.length); return }
+            None => { assert_eq!(0, list.length); return }
             Some(ref node) => node_ptr = &**node,
         }
         loop {
@@ -968,7 +968,7 @@ pub fn check_links<T>(list: &DList<T>) {
 
     #[test]
     fn test_basic() {
-        let mut m: DList<Box<int>> = DList::new();
+        let mut m = DList::new();
         assert_eq!(m.pop_front(), None);
         assert_eq!(m.pop_back(), None);
         assert_eq!(m.pop_front(), None);
@@ -1007,7 +1007,7 @@ fn test_basic() {
     }
 
     #[cfg(test)]
-    fn generate_test() -> DList<int> {
+    fn generate_test() -> DList<i32> {
         list_from(&[0,1,2,3,4,5,6])
     }
 
@@ -1020,7 +1020,7 @@ fn list_from<T: Clone>(v: &[T]) -> DList<T> {
     fn test_append() {
         // Empty to empty
         {
-            let mut m: DList<int> = DList::new();
+            let mut m = DList::<i32>::new();
             let mut n = DList::new();
             m.append(&mut n);
             check_links(&m);
@@ -1054,12 +1054,12 @@ fn test_append() {
         // Non-empty to non-empty
         let v = vec![1,2,3,4,5];
         let u = vec![9,8,1,2,3,4,5];
-        let mut m = list_from(v.as_slice());
-        let mut n = list_from(u.as_slice());
+        let mut m = list_from(&v);
+        let mut n = list_from(&u);
         m.append(&mut n);
         check_links(&m);
         let mut sum = v;
-        sum.push_all(u.as_slice());
+        sum.push_all(&u);
         assert_eq!(sum.len(), m.len());
         for elt in sum {
             assert_eq!(m.pop_front(), Some(elt))
@@ -1090,7 +1090,7 @@ fn test_split_off() {
         // not singleton, forwards
         {
             let u = vec![1,2,3,4,5];
-            let mut m = list_from(u.as_slice());
+            let mut m = list_from(&u);
             let mut n = m.split_off(2);
             assert_eq!(m.len(), 2);
             assert_eq!(n.len(), 3);
@@ -1104,7 +1104,7 @@ fn test_split_off() {
         // not singleton, backwards
         {
             let u = vec![1,2,3,4,5];
-            let mut m = list_from(u.as_slice());
+            let mut m = list_from(&u);
             let mut n = m.split_off(4);
             assert_eq!(m.len(), 4);
             assert_eq!(n.len(), 1);
@@ -1122,7 +1122,7 @@ fn test_split_off() {
     fn test_iterator() {
         let m = generate_test();
         for (i, elt) in m.iter().enumerate() {
-            assert_eq!(i as int, *elt);
+            assert_eq!(i as i32, *elt);
         }
         let mut n = DList::new();
         assert_eq!(n.iter().next(), None);
@@ -1170,7 +1170,7 @@ fn test_iterator_double_end() {
     fn test_rev_iter() {
         let m = generate_test();
         for (i, elt) in m.iter().rev().enumerate() {
-            assert_eq!((6 - i) as int, *elt);
+            assert_eq!((6 - i) as i32, *elt);
         }
         let mut n = DList::new();
         assert_eq!(n.iter().rev().next(), None);
@@ -1187,7 +1187,7 @@ fn test_mut_iter() {
         let mut m = generate_test();
         let mut len = m.len();
         for (i, elt) in m.iter_mut().enumerate() {
-            assert_eq!(i as int, *elt);
+            assert_eq!(i as i32, *elt);
             len -= 1;
         }
         assert_eq!(len, 0);
@@ -1245,14 +1245,14 @@ fn test_insert_prev() {
         }
         check_links(&m);
         assert_eq!(m.len(), 3 + len * 2);
-        assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
+        assert_eq!(m.into_iter().collect::<Vec<_>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
     }
 
     #[test]
     fn test_mut_rev_iter() {
         let mut m = generate_test();
         for (i, elt) in m.iter_mut().rev().enumerate() {
-            assert_eq!((6-i) as int, *elt);
+            assert_eq!((6 - i) as i32, *elt);
         }
         let mut n = DList::new();
         assert!(n.iter_mut().rev().next().is_none());
@@ -1268,13 +1268,13 @@ fn test_send() {
         Thread::scoped(move || {
             check_links(&n);
             let a: &[_] = &[&1,&2,&3];
-            assert_eq!(a, n.iter().collect::<Vec<&int>>());
+            assert_eq!(a, n.iter().collect::<Vec<_>>());
         }).join().ok().unwrap();
     }
 
     #[test]
     fn test_eq() {
-        let mut n: DList<u8> = list_from(&[]);
+        let mut n = list_from(&[]);
         let mut m = list_from(&[]);
         assert!(n == m);
         n.push_front(1);
@@ -1307,7 +1307,7 @@ fn test_hash() {
 
     #[test]
     fn test_ord() {
-        let n: DList<int> = list_from(&[]);
+        let n = list_from(&[]);
         let m = list_from(&[1,2,3]);
         assert!(n < m);
         assert!(m > n);
@@ -1349,7 +1349,7 @@ fn test_ord_nan() {
 
     #[test]
     fn test_fuzz() {
-        for _ in 0u..25 {
+        for _ in 0..25 {
             fuzz_test(3);
             fuzz_test(16);
             fuzz_test(189);
@@ -1358,18 +1358,16 @@ fn test_fuzz() {
 
     #[test]
     fn test_show() {
-        let list: DList<i32> = (0..10).collect();
+        let list: DList<_> = (0..10).collect();
         assert_eq!(format!("{:?}", list), "DList [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
 
-        let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
-                                                                   .map(|&s| s)
-                                                                   .collect();
+        let list: DList<_> = vec!["just", "one", "test", "more"].iter().cloned().collect();
         assert_eq!(format!("{:?}", list), "DList [\"just\", \"one\", \"test\", \"more\"]");
     }
 
     #[cfg(test)]
-    fn fuzz_test(sz: int) {
-        let mut m: DList<int> = DList::new();
+    fn fuzz_test(sz: i32) {
+        let mut m: DList<_> = DList::new();
         let mut v = vec![];
         for i in 0..sz {
             check_links(&m);
@@ -1398,7 +1396,7 @@ fn fuzz_test(sz: int) {
 
         check_links(&m);
 
-        let mut i = 0u;
+        let mut i = 0;
         for (a, &b) in m.into_iter().zip(v.iter()) {
             i += 1;
             assert_eq!(a, b);
@@ -1410,13 +1408,13 @@ fn fuzz_test(sz: int) {
     fn bench_collect_into(b: &mut test::Bencher) {
         let v = &[0; 64];
         b.iter(|| {
-            let _: DList<int> = v.iter().map(|x| *x).collect();
+            let _: DList<_> = v.iter().cloned().collect();
         })
     }
 
     #[bench]
     fn bench_push_front(b: &mut test::Bencher) {
-        let mut m: DList<int> = DList::new();
+        let mut m: DList<_> = DList::new();
         b.iter(|| {
             m.push_front(0);
         })
@@ -1424,7 +1422,7 @@ fn bench_push_front(b: &mut test::Bencher) {
 
     #[bench]
     fn bench_push_back(b: &mut test::Bencher) {
-        let mut m: DList<int> = DList::new();
+        let mut m: DList<_> = DList::new();
         b.iter(|| {
             m.push_back(0);
         })
@@ -1432,7 +1430,7 @@ fn bench_push_back(b: &mut test::Bencher) {
 
     #[bench]
     fn bench_push_back_pop_back(b: &mut test::Bencher) {
-        let mut m: DList<int> = DList::new();
+        let mut m: DList<_> = DList::new();
         b.iter(|| {
             m.push_back(0);
             m.pop_back();
@@ -1441,7 +1439,7 @@ fn bench_push_back_pop_back(b: &mut test::Bencher) {
 
     #[bench]
     fn bench_push_front_pop_front(b: &mut test::Bencher) {
-        let mut m: DList<int> = DList::new();
+        let mut m: DList<_> = DList::new();
         b.iter(|| {
             m.push_front(0);
             m.pop_front();
@@ -1451,7 +1449,7 @@ fn bench_push_front_pop_front(b: &mut test::Bencher) {
     #[bench]
     fn bench_iter(b: &mut test::Bencher) {
         let v = &[0; 128];
-        let m: DList<int> = v.iter().map(|&x|x).collect();
+        let m: DList<_> = v.iter().cloned().collect();
         b.iter(|| {
             assert!(m.iter().count() == 128);
         })
@@ -1459,7 +1457,7 @@ fn bench_iter(b: &mut test::Bencher) {
     #[bench]
     fn bench_iter_mut(b: &mut test::Bencher) {
         let v = &[0; 128];
-        let mut m: DList<int> = v.iter().map(|&x|x).collect();
+        let mut m: DList<_> = v.iter().cloned().collect();
         b.iter(|| {
             assert!(m.iter_mut().count() == 128);
         })
@@ -1467,7 +1465,7 @@ fn bench_iter_mut(b: &mut test::Bencher) {
     #[bench]
     fn bench_iter_rev(b: &mut test::Bencher) {
         let v = &[0; 128];
-        let m: DList<int> = v.iter().map(|&x|x).collect();
+        let m: DList<_> = v.iter().cloned().collect();
         b.iter(|| {
             assert!(m.iter().rev().count() == 128);
         })
@@ -1475,7 +1473,7 @@ fn bench_iter_rev(b: &mut test::Bencher) {
     #[bench]
     fn bench_iter_mut_rev(b: &mut test::Bencher) {
         let v = &[0; 128];
-        let mut m: DList<int> = v.iter().map(|&x|x).collect();
+        let mut m: DList<_> = v.iter().cloned().collect();
         b.iter(|| {
             assert!(m.iter_mut().rev().count() == 128);
         })
index 8cbf50d29f23b02ebe9347b89c83dd619499e653..da146506077478a22dd1ff58e56f17393cb785c2 100644 (file)
@@ -26,7 +26,7 @@
 pub struct EnumSet<E> {
     // We must maintain the invariant that no bits are set
     // for which no variant exists
-    bits: uint
+    bits: usize
 }
 
 impl<E> Copy for EnumSet<E> {}
@@ -47,37 +47,37 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-/// An interface for casting C-like enum to uint and back.
+/// An interface for casting C-like enum to usize and back.
 /// A typically implementation is as below.
 ///
 /// ```{rust,ignore}
-/// #[repr(uint)]
+/// #[repr(usize)]
 /// enum Foo {
 ///     A, B, C
 /// }
 ///
 /// impl CLike for Foo {
-///     fn to_uint(&self) -> uint {
-///         *self as uint
+///     fn to_usize(&self) -> usize {
+///         *self as usize
 ///     }
 ///
-///     fn from_uint(v: uint) -> Foo {
+///     fn from_usize(v: usize) -> Foo {
 ///         unsafe { mem::transmute(v) }
 ///     }
 /// }
 /// ```
 pub trait CLike {
-    /// Converts a C-like enum to a `uint`.
-    fn to_uint(&self) -> uint;
-    /// Converts a `uint` to a C-like enum.
-    fn from_uint(uint) -> Self;
+    /// Converts a C-like enum to a `usize`.
+    fn to_usize(&self) -> usize;
+    /// Converts a `usize` to a C-like enum.
+    fn from_usize(usize) -> Self;
 }
 
-fn bit<E:CLike>(e: &E) -> uint {
-    use core::uint;
-    let value = e.to_uint();
-    assert!(value < uint::BITS,
-            "EnumSet only supports up to {} variants.", uint::BITS - 1);
+fn bit<E:CLike>(e: &E) -> usize {
+    use core::usize;
+    let value = e.to_usize();
+    assert!(value < usize::BITS,
+            "EnumSet only supports up to {} variants.", usize::BITS - 1);
     1 << value
 }
 
@@ -92,7 +92,7 @@ pub fn new() -> EnumSet<E> {
     /// Returns the number of elements in the given `EnumSet`.
     #[unstable(feature = "collections",
                reason = "matches collection reform specification, waiting for dust to settle")]
-    pub fn len(&self) -> uint {
+    pub fn len(&self) -> usize {
         self.bits.count_ones()
     }
 
@@ -205,8 +205,8 @@ fn bitxor(self, e: EnumSet<E>) -> EnumSet<E> {
 
 /// An iterator over an EnumSet
 pub struct Iter<E> {
-    index: uint,
-    bits: uint,
+    index: usize,
+    bits: usize,
 }
 
 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
@@ -220,7 +220,7 @@ fn clone(&self) -> Iter<E> {
 }
 
 impl<E:CLike> Iter<E> {
-    fn new(bits: uint) -> Iter<E> {
+    fn new(bits: usize) -> Iter<E> {
         Iter { index: 0, bits: bits }
     }
 }
@@ -237,13 +237,13 @@ fn next(&mut self) -> Option<E> {
             self.index += 1;
             self.bits >>= 1;
         }
-        let elem = CLike::from_uint(self.index);
+        let elem = CLike::from_usize(self.index);
         self.index += 1;
         self.bits >>= 1;
         Some(elem)
     }
 
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         let exact = self.bits.count_ones();
         (exact, Some(exact))
     }
@@ -282,17 +282,17 @@ mod test {
     use super::{EnumSet, CLike};
 
     #[derive(Copy, PartialEq, Debug)]
-    #[repr(uint)]
+    #[repr(usize)]
     enum Foo {
         A, B, C
     }
 
     impl CLike for Foo {
-        fn to_uint(&self) -> uint {
-            *self as uint
+        fn to_usize(&self) -> usize {
+            *self as usize
         }
 
-        fn from_uint(v: uint) -> Foo {
+        fn from_usize(v: usize) -> Foo {
             unsafe { mem::transmute(v) }
         }
     }
@@ -486,7 +486,7 @@ fn test_operators() {
     fn test_overflow() {
         #[allow(dead_code)]
         #[derive(Copy)]
-        #[repr(uint)]
+        #[repr(usize)]
         enum Bar {
             V00, V01, V02, V03, V04, V05, V06, V07, V08, V09,
             V10, V11, V12, V13, V14, V15, V16, V17, V18, V19,
@@ -498,11 +498,11 @@ enum Bar {
         }
 
         impl CLike for Bar {
-            fn to_uint(&self) -> uint {
-                *self as uint
+            fn to_usize(&self) -> usize {
+                *self as usize
             }
 
-            fn from_uint(v: uint) -> Bar {
+            fn from_usize(v: usize) -> Bar {
                 unsafe { mem::transmute(v) }
             }
         }
diff --git a/src/libcollections/fmt.rs b/src/libcollections/fmt.rs
new file mode 100644 (file)
index 0000000..5f33752
--- /dev/null
@@ -0,0 +1,448 @@
+// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+//
+// ignore-lexer-test FIXME #15679
+
+//! Utilities for formatting and printing strings
+//!
+//! This module contains the runtime support for the `format!` syntax extension.
+//! This macro is implemented in the compiler to emit calls to this module in
+//! order to format arguments at runtime into strings and streams.
+//!
+//! ## Usage
+//!
+//! The `format!` macro is intended to be familiar to those coming from C's
+//! printf/fprintf functions or Python's `str.format` function. In its current
+//! revision, the `format!` macro returns a `String` type which is the result of
+//! the formatting. In the future it will also be able to pass in a stream to
+//! format arguments directly while performing minimal allocations.
+//!
+//! Some examples of the `format!` extension are:
+//!
+//! ```
+//! format!("Hello");                  // => "Hello"
+//! format!("Hello, {}!", "world");    // => "Hello, world!"
+//! format!("The number is {}", 1);   // => "The number is 1"
+//! format!("{:?}", (3, 4));         // => "(3, 4)"
+//! format!("{value}", value=4);      // => "4"
+//! format!("{} {}", 1, 2u);          // => "1 2"
+//! ```
+//!
+//! From these, you can see that the first argument is a format string. It is
+//! required by the compiler for this to be a string literal; it cannot be a
+//! variable passed in (in order to perform validity checking). The compiler
+//! will then parse the format string and determine if the list of arguments
+//! provided is suitable to pass to this format string.
+//!
+//! ### Positional parameters
+//!
+//! Each formatting argument is allowed to specify which value argument it's
+//! referencing, and if omitted it is assumed to be "the next argument". For
+//! example, the format string `{} {} {}` would take three parameters, and they
+//! would be formatted in the same order as they're given. The format string
+//! `{2} {1} {0}`, however, would format arguments in reverse order.
+//!
+//! Things can get a little tricky once you start intermingling the two types of
+//! positional specifiers. The "next argument" specifier can be thought of as an
+//! iterator over the argument. Each time a "next argument" specifier is seen,
+//! the iterator advances. This leads to behavior like this:
+//!
+//! ```rust
+//! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
+//! ```
+//!
+//! The internal iterator over the argument has not been advanced by the time
+//! the first `{}` is seen, so it prints the first argument. Then upon reaching
+//! the second `{}`, the iterator has advanced forward to the second argument.
+//! Essentially, parameters which explicitly name their argument do not affect
+//! parameters which do not name an argument in terms of positional specifiers.
+//!
+//! A format string is required to use all of its arguments, otherwise it is a
+//! compile-time error. You may refer to the same argument more than once in the
+//! format string, although it must always be referred to with the same type.
+//!
+//! ### Named parameters
+//!
+//! Rust itself does not have a Python-like equivalent of named parameters to a
+//! function, but the `format!` macro is a syntax extension which allows it to
+//! leverage named parameters. Named parameters are listed at the end of the
+//! argument list and have the syntax:
+//!
+//! ```text
+//! identifier '=' expression
+//! ```
+//!
+//! For example, the following `format!` expressions all use named argument:
+//!
+//! ```
+//! format!("{argument}", argument = "test");   // => "test"
+//! format!("{name} {}", 1, name = 2);        // => "2 1"
+//! format!("{a} {c} {b}", a="a", b='b', c=3);  // => "a 3 b"
+//! ```
+//!
+//! It is illegal to put positional parameters (those without names) after
+//! arguments which have names. Like with positional parameters, it is illegal
+//! to provide named parameters that are unused by the format string.
+//!
+//! ### Argument types
+//!
+//! Each argument's type is dictated by the format string. It is a requirement
+//! that every argument is only ever referred to by one type. For example, this
+//! is an invalid format string:
+//!
+//! ```text
+//! {0:x} {0:o}
+//! ```
+//!
+//! This is invalid because the first argument is both referred to as a
+//! hexadecimal as well as an
+//! octal.
+//!
+//! There are various parameters which do require a particular type, however.
+//! Namely if the syntax `{:.*}` is used, then the number of characters to print
+//! precedes the actual object being formatted, and the number of characters
+//! must have the type `uint`. Although a `uint` can be printed with `{}`, it is
+//! illegal to reference an argument as such. For example this is another
+//! invalid format string:
+//!
+//! ```text
+//! {:.*} {0}
+//! ```
+//!
+//! ### Formatting traits
+//!
+//! When requesting that an argument be formatted with a particular type, you
+//! are actually requesting that an argument ascribes to a particular trait.
+//! This allows multiple actual types to be formatted via `{:x}` (like `i8` as
+//! well as `int`).  The current mapping of types to traits is:
+//!
+//! * *nothing* ⇒ `Display`
+//! * `?` ⇒ `Debug`
+//! * `o` ⇒ `Octal`
+//! * `x` ⇒ `LowerHex`
+//! * `X` ⇒ `UpperHex`
+//! * `p` ⇒ `Pointer`
+//! * `b` ⇒ `Binary`
+//! * `e` ⇒ `LowerExp`
+//! * `E` ⇒ `UpperExp`
+//!
+//! What this means is that any type of argument which implements the
+//! `fmt::Binary` trait can then be formatted with `{:b}`. Implementations
+//! are provided for these traits for a number of primitive types by the
+//! standard library as well. If no format is specified (as in `{}` or `{:6}`),
+//! then the format trait used is the `Display` trait.
+//!
+//! When implementing a format trait for your own type, you will have to
+//! implement a method of the signature:
+//!
+//! ```rust
+//! # use std::fmt;
+//! # struct Foo; // our custom type
+//! # impl fmt::Display for Foo {
+//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+//! # write!(f, "testing, testing")
+//! # } }
+//! ```
+//!
+//! Your type will be passed as `self` by-reference, and then the function
+//! should emit output into the `f.buf` stream. It is up to each format trait
+//! implementation to correctly adhere to the requested formatting parameters.
+//! The values of these parameters will be listed in the fields of the
+//! `Formatter` struct. In order to help with this, the `Formatter` struct also
+//! provides some helper methods.
+//!
+//! Additionally, the return value of this function is `fmt::Result` which is a
+//! typedef to `Result<(), IoError>` (also known as `IoResult<()>`). Formatting
+//! implementations should ensure that they return errors from `write!`
+//! correctly (propagating errors upward).
+//!
+//! An example of implementing the formatting traits would look
+//! like:
+//!
+//! ```rust
+//! use std::fmt;
+//! use std::f64;
+//! use std::num::Float;
+//!
+//! #[derive(Debug)]
+//! struct Vector2D {
+//!     x: int,
+//!     y: int,
+//! }
+//!
+//! impl fmt::Display for Vector2D {
+//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+//!         // The `f` value implements the `Writer` trait, which is what the
+//!         // write! macro is expecting. Note that this formatting ignores the
+//!         // various flags provided to format strings.
+//!         write!(f, "({}, {})", self.x, self.y)
+//!     }
+//! }
+//!
+//! // Different traits allow different forms of output of a type. The meaning
+//! // of this format is to print the magnitude of a vector.
+//! impl fmt::Binary for Vector2D {
+//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+//!         let magnitude = (self.x * self.x + self.y * self.y) as f64;
+//!         let magnitude = magnitude.sqrt();
+//!
+//!         // Respect the formatting flags by using the helper method
+//!         // `pad_integral` on the Formatter object. See the method documentation
+//!         // for details, and the function `pad` can be used to pad strings.
+//!         let decimals = f.precision().unwrap_or(3);
+//!         let string = f64::to_str_exact(magnitude, decimals);
+//!         f.pad_integral(true, "", string.as_slice())
+//!     }
+//! }
+//!
+//! fn main() {
+//!     let myvector = Vector2D { x: 3, y: 4 };
+//!
+//!     println!("{}", myvector);       // => "(3, 4)"
+//!     println!("{:?}", myvector);     // => "Vector2D {x: 3, y:4}"
+//!     println!("{:10.3b}", myvector); // => "     5.000"
+//! }
+//! ```
+//!
+//! #### fmt::Display vs fmt::Debug
+//!
+//! These two formatting traits have distinct purposes:
+//!
+//! - `fmt::Display` implementations assert that the type can be faithfully
+//!   represented as a UTF-8 string at all times. It is **not** expected that
+//!   all types implement the `Display` trait.
+//! - `fmt::Debug` implementations should be implemented for **all** public types.
+//!   Output will typically represent the internal state as faithfully as possible.
+//!   The purpose of the `Debug` trait is to facilitate debugging Rust code. In
+//!   most cases, using `#[derive(Debug)]` is sufficient and recommended.
+//!
+//! Some examples of the output from both traits:
+//!
+//! ```
+//! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4");
+//! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
+//! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
+//! ```
+//!
+//! ### Related macros
+//!
+//! There are a number of related macros in the `format!` family. The ones that
+//! are currently implemented are:
+//!
+//! ```ignore
+//! format!      // described above
+//! write!       // first argument is a &mut old_io::Writer, the destination
+//! writeln!     // same as write but appends a newline
+//! print!       // the format string is printed to the standard output
+//! println!     // same as print but appends a newline
+//! format_args! // described below.
+//! ```
+//!
+//! #### `write!`
+//!
+//! This and `writeln` are two macros which are used to emit the format string
+//! to a specified stream. This is used to prevent intermediate allocations of
+//! format strings and instead directly write the output. Under the hood, this
+//! function is actually invoking the `write` function defined in this module.
+//! Example usage is:
+//!
+//! ```rust
+//! # #![allow(unused_must_use)]
+//! let mut w = Vec::new();
+//! write!(&mut w, "Hello {}!", "world");
+//! ```
+//!
+//! #### `print!`
+//!
+//! This and `println` emit their output to stdout. Similarly to the `write!`
+//! macro, the goal of these macros is to avoid intermediate allocations when
+//! printing output. Example usage is:
+//!
+//! ```rust
+//! print!("Hello {}!", "world");
+//! println!("I have a newline {}", "character at the end");
+//! ```
+//!
+//! #### `format_args!`
+//! This is a curious macro which is used to safely pass around
+//! an opaque object describing the format string. This object
+//! does not require any heap allocations to create, and it only
+//! references information on the stack. Under the hood, all of
+//! the related macros are implemented in terms of this. First
+//! off, some example usage is:
+//!
+//! ```
+//! use std::fmt;
+//! use std::old_io;
+//!
+//! fmt::format(format_args!("this returns {}", "String"));
+//!
+//! let mut some_writer = old_io::stdout();
+//! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
+//!
+//! fn my_fmt_fn(args: fmt::Arguments) {
+//!     write!(&mut old_io::stdout(), "{}", args);
+//! }
+//! my_fmt_fn(format_args!("or a {} too", "function"));
+//! ```
+//!
+//! The result of the `format_args!` macro is a value of type `fmt::Arguments`.
+//! This structure can then be passed to the `write` and `format` functions
+//! inside this module in order to process the format string.
+//! The goal of this macro is to even further prevent intermediate allocations
+//! when dealing formatting strings.
+//!
+//! For example, a logging library could use the standard formatting syntax, but
+//! it would internally pass around this structure until it has been determined
+//! where output should go to.
+//!
+//! ## Syntax
+//!
+//! The syntax for the formatting language used is drawn from other languages,
+//! so it should not be too alien. Arguments are formatted with python-like
+//! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
+//! `%`. The actual grammar for the formatting syntax is:
+//!
+//! ```text
+//! format_string := <text> [ format <text> ] *
+//! format := '{' [ argument ] [ ':' format_spec ] '}'
+//! argument := integer | identifier
+//!
+//! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
+//! fill := character
+//! align := '<' | '^' | '>'
+//! sign := '+' | '-'
+//! width := count
+//! precision := count | '*'
+//! type := identifier | ''
+//! count := parameter | integer
+//! parameter := integer '$'
+//! ```
+//!
+//! ## Formatting Parameters
+//!
+//! Each argument being formatted can be transformed by a number of formatting
+//! parameters (corresponding to `format_spec` in the syntax above). These
+//! parameters affect the string representation of what's being formatted. This
+//! syntax draws heavily from Python's, so it may seem a bit familiar.
+//!
+//! ### Fill/Alignment
+//!
+//! The fill character is provided normally in conjunction with the `width`
+//! parameter. This indicates that if the value being formatted is smaller than
+//! `width` some extra characters will be printed around it. The extra
+//! characters are specified by `fill`, and the alignment can be one of two
+//! options:
+//!
+//! * `<` - the argument is left-aligned in `width` columns
+//! * `^` - the argument is center-aligned in `width` columns
+//! * `>` - the argument is right-aligned in `width` columns
+//!
+//! ### Sign/#/0
+//!
+//! These can all be interpreted as flags for a particular formatter.
+//!
+//! * '+' - This is intended for numeric types and indicates that the sign
+//!         should always be printed. Positive signs are never printed by
+//!         default, and the negative sign is only printed by default for the
+//!         `Signed` trait. This flag indicates that the correct sign (+ or -)
+//!         should always be printed.
+//! * '-' - Currently not used
+//! * '#' - This flag is indicates that the "alternate" form of printing should
+//!         be used. By default, this only applies to the integer formatting
+//!         traits and performs like:
+//!     * `x` - precedes the argument with a "0x"
+//!     * `X` - precedes the argument with a "0x"
+//!     * `t` - precedes the argument with a "0b"
+//!     * `o` - precedes the argument with a "0o"
+//! * '0' - This is used to indicate for integer formats that the padding should
+//!         both be done with a `0` character as well as be sign-aware. A format
+//!         like `{:08d}` would yield `00000001` for the integer `1`, while the
+//!         same format would yield `-0000001` for the integer `-1`. Notice that
+//!         the negative version has one fewer zero than the positive version.
+//!
+//! ### Width
+//!
+//! This is a parameter for the "minimum width" that the format should take up.
+//! If the value's string does not fill up this many characters, then the
+//! padding specified by fill/alignment will be used to take up the required
+//! space.
+//!
+//! The default fill/alignment for non-numerics is a space and left-aligned. The
+//! defaults for numeric formatters is also a space but with right-alignment. If
+//! the '0' flag is specified for numerics, then the implicit fill character is
+//! '0'.
+//!
+//! The value for the width can also be provided as a `uint` in the list of
+//! parameters by using the `2$` syntax indicating that the second argument is a
+//! `uint` specifying the width.
+//!
+//! ### Precision
+//!
+//! For non-numeric types, this can be considered a "maximum width". If the
+//! resulting string is longer than this width, then it is truncated down to
+//! this many characters and only those are emitted.
+//!
+//! For integral types, this has no meaning currently.
+//!
+//! For floating-point types, this indicates how many digits after the decimal
+//! point should be printed.
+//!
+//! ## Escaping
+//!
+//! The literal characters `{` and `}` may be included in a string by preceding
+//! them with the same character. For example, the `{` character is escaped with
+//! `{{` and the `}` character is escaped with `}}`.
+
+#![unstable(feature = "std_misc")]
+
+pub use core::fmt::{Formatter, Result, Writer, rt};
+pub use core::fmt::{Show, String, Octal, Binary};
+pub use core::fmt::{Display, Debug};
+pub use core::fmt::{LowerHex, UpperHex, Pointer};
+pub use core::fmt::{LowerExp, UpperExp};
+pub use core::fmt::Error;
+pub use core::fmt::{ArgumentV1, Arguments, write, radix, Radix, RadixFmt};
+
+use string;
+
+/// The format function takes a precompiled format string and a list of
+/// arguments, to return the resulting formatted string.
+///
+/// # Arguments
+///
+///   * args - a structure of arguments generated via the `format_args!` macro.
+///
+/// # Example
+///
+/// ```rust
+/// use std::fmt;
+///
+/// let s = fmt::format(format_args!("Hello, {}!", "world"));
+/// assert_eq!(s, "Hello, world!".to_string());
+/// ```
+#[stable(feature = "rust1", since = "1.0.0")]
+pub fn format(args: Arguments) -> string::String {
+    let mut output = string::String::new();
+    let _ = write!(&mut output, "{}", args);
+    output
+}
+
+#[cfg(test)]
+mod tests {
+    use prelude::*;
+    use fmt;
+
+    #[test]
+    fn test_format() {
+        let s = fmt::format(format_args!("Hello, {}!", "world"));
+        assert_eq!(s.as_slice(), "Hello, world!");
+    }
+}
index f44141fe0f49370eccac5a83ed995b62ed3e416d..f220724c42e098f6ea1308777282da47bfea9ab4 100644 (file)
@@ -26,7 +26,6 @@
 #![feature(box_syntax)]
 #![feature(core)]
 #![feature(hash)]
-#![feature(int_uint)]
 #![feature(staged_api)]
 #![feature(unboxed_closures)]
 #![feature(unicode)]
@@ -34,6 +33,7 @@
 #![cfg_attr(test, feature(test))]
 #![cfg_attr(test, allow(deprecated))] // rand
 
+#![feature(no_std)]
 #![no_std]
 
 #[macro_use]
@@ -69,6 +69,7 @@
 mod btree;
 pub mod dlist;
 pub mod enum_set;
+pub mod fmt;
 pub mod ring_buf;
 pub mod slice;
 pub mod str;
@@ -108,15 +109,16 @@ pub fn fixme_14344_be_sure_to_link_to_collections() {}
 
 #[cfg(not(test))]
 mod std {
-    pub use core::fmt;      // necessary for panic!()
-    pub use core::option;   // necessary for panic!()
-    pub use core::clone;    // derive(Clone)
-    pub use core::cmp;      // derive(Eq, Ord, etc.)
-    pub use core::marker;   // derive(Copy)
-    pub use core::hash;     // derive(Hash)
+    // NOTE: remove after next snapshot
+    #[cfg(stage0)] pub use core::clone;    // derive(Clone)
+    #[cfg(stage0)] pub use core::cmp;      // derive(Eq, Ord, etc.)
+    #[cfg(stage0)] pub use core::marker;   // derive(Copy)
+    #[cfg(stage0)] pub use core::hash;     // derive(Hash)
+    #[cfg(stage0)] pub use core::iter;
+    #[cfg(stage0)] pub use core::fmt;      // necessary for panic!()
+    #[cfg(stage0)] pub use core::option;   // necessary for panic!()
+
     pub use core::ops;      // RangeFull
-    // for-loops
-    pub use core::iter;
 }
 
 #[cfg(test)]
index 15048998592a9dcf6a050d6db0306a06722b2642..79c86a846f1b90e96b0b969af1eb0bd9a884df21 100644 (file)
@@ -22,3 +22,19 @@ macro_rules! vec {
     );
     ($($x:expr,)*) => (vec![$($x),*])
 }
+
+/// Use the syntax described in `std::fmt` to create a value of type `String`.
+/// See `std::fmt` for more information.
+///
+/// # Example
+///
+/// ```
+/// format!("test");
+/// format!("hello {}", "world!");
+/// format!("x = {}, y = {y}", 10, y = 30);
+/// ```
+#[macro_export]
+#[stable(feature = "rust1", since = "1.0.0")]
+macro_rules! format {
+    ($($arg:tt)*) => ($crate::fmt::format(format_args!($($arg)*)))
+}
index 18021dea9f29ed5f118208d9b948a5a1431b4cac..76849e6ade85a23c5fcc7d1a74ae8ffca19294b0 100644 (file)
 use core::ptr;
 use core::raw::Slice as RawSlice;
 
-use std::hash::{Writer, Hash, Hasher};
-use std::cmp;
+use core::hash::{Writer, Hash, Hasher};
+use core::cmp;
 
 use alloc::heap;
 
-static INITIAL_CAPACITY: uint = 7u; // 2^3 - 1
-static MINIMUM_CAPACITY: uint = 1u; // 2 - 1
+static INITIAL_CAPACITY: usize = 7; // 2^3 - 1
+static MINIMUM_CAPACITY: usize = 1; // 2 - 1
 
 /// `RingBuf` is a circular buffer, which can be used as a double-ended queue efficiently.
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -44,9 +44,9 @@ pub struct RingBuf<T> {
     // If tail == head the buffer is empty. The length of the ringbuf
     // is defined as the distance between the two.
 
-    tail: uint,
-    head: uint,
-    cap: uint,
+    tail: usize,
+    head: usize,
+    cap: usize,
     ptr: *mut T
 }
 
@@ -59,7 +59,7 @@ unsafe impl<T: Sync> Sync for RingBuf<T> {}
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T: Clone> Clone for RingBuf<T> {
     fn clone(&self) -> RingBuf<T> {
-        self.iter().map(|t| t.clone()).collect()
+        self.iter().cloned().collect()
     }
 }
 
@@ -99,14 +99,14 @@ unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
 
     /// Moves an element out of the buffer
     #[inline]
-    unsafe fn buffer_read(&mut self, off: uint) -> T {
-        ptr::read(self.ptr.offset(off as int))
+    unsafe fn buffer_read(&mut self, off: usize) -> T {
+        ptr::read(self.ptr.offset(off as isize))
     }
 
     /// Writes an element into the buffer, moving it.
     #[inline]
-    unsafe fn buffer_write(&mut self, off: uint, t: T) {
-        ptr::write(self.ptr.offset(off as int), t);
+    unsafe fn buffer_write(&mut self, off: usize, t: T) {
+        ptr::write(self.ptr.offset(off as isize), t);
     }
 
     /// Returns true iff the buffer is at capacity
@@ -115,31 +115,31 @@ fn is_full(&self) -> bool { self.cap - self.len() == 1 }
 
     /// Returns the index in the underlying buffer for a given logical element index.
     #[inline]
-    fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
+    fn wrap_index(&self, idx: usize) -> usize { wrap_index(idx, self.cap) }
 
     /// Copies a contiguous block of memory len long from src to dst
     #[inline]
-    unsafe fn copy(&self, dst: uint, src: uint, len: uint) {
+    unsafe fn copy(&self, dst: usize, src: usize, len: usize) {
         debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
                       self.cap);
         debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
                       self.cap);
         ptr::copy_memory(
-            self.ptr.offset(dst as int),
-            self.ptr.offset(src as int),
+            self.ptr.offset(dst as isize),
+            self.ptr.offset(src as isize),
             len);
     }
 
     /// Copies a contiguous block of memory len long from src to dst
     #[inline]
-    unsafe fn copy_nonoverlapping(&self, dst: uint, src: uint, len: uint) {
+    unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) {
         debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
                       self.cap);
         debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
                       self.cap);
         ptr::copy_nonoverlapping_memory(
-            self.ptr.offset(dst as int),
-            self.ptr.offset(src as int),
+            self.ptr.offset(dst as isize),
+            self.ptr.offset(src as isize),
             len);
     }
 }
@@ -153,7 +153,7 @@ pub fn new() -> RingBuf<T> {
 
     /// Creates an empty `RingBuf` with space for at least `n` elements.
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(n: uint) -> RingBuf<T> {
+    pub fn with_capacity(n: usize) -> RingBuf<T> {
         // +1 since the ringbuffer always leaves one space empty
         let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
         assert!(cap > n, "capacity overflow");
@@ -192,10 +192,10 @@ pub fn with_capacity(n: uint) -> RingBuf<T> {
     /// assert_eq!(buf.get(1).unwrap(), &4);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get(&self, i: uint) -> Option<&T> {
+    pub fn get(&self, i: usize) -> Option<&T> {
         if i < self.len() {
             let idx = self.wrap_index(self.tail + i);
-            unsafe { Some(&*self.ptr.offset(idx as int)) }
+            unsafe { Some(&*self.ptr.offset(idx as isize)) }
         } else {
             None
         }
@@ -222,10 +222,10 @@ pub fn get(&self, i: uint) -> Option<&T> {
     /// assert_eq!(buf[1], 7);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
+    pub fn get_mut(&mut self, i: usize) -> Option<&mut T> {
         if i < self.len() {
             let idx = self.wrap_index(self.tail + i);
-            unsafe { Some(&mut *self.ptr.offset(idx as int)) }
+            unsafe { Some(&mut *self.ptr.offset(idx as isize)) }
         } else {
             None
         }
@@ -251,13 +251,13 @@ pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
     /// assert_eq!(buf[2], 3);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn swap(&mut self, i: uint, j: uint) {
+    pub fn swap(&mut self, i: usize, j: usize) {
         assert!(i < self.len());
         assert!(j < self.len());
         let ri = self.wrap_index(self.tail + i);
         let rj = self.wrap_index(self.tail + j);
         unsafe {
-            ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
+            ptr::swap(self.ptr.offset(ri as isize), self.ptr.offset(rj as isize))
         }
     }
 
@@ -274,7 +274,7 @@ pub fn swap(&mut self, i: uint, j: uint) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint { self.cap - 1 }
+    pub fn capacity(&self) -> usize { self.cap - 1 }
 
     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
     /// given `RingBuf`. Does nothing if the capacity is already sufficient.
@@ -285,7 +285,7 @@ pub fn capacity(&self) -> uint { self.cap - 1 }
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -297,7 +297,7 @@ pub fn capacity(&self) -> uint { self.cap - 1 }
     /// assert!(buf.capacity() >= 11);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_exact(&mut self, additional: uint) {
+    pub fn reserve_exact(&mut self, additional: usize) {
         self.reserve(additional);
     }
 
@@ -306,7 +306,7 @@ pub fn reserve_exact(&mut self, additional: uint) {
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -318,7 +318,7 @@ pub fn reserve_exact(&mut self, additional: uint) {
     /// assert!(buf.capacity() >= 11);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve(&mut self, additional: uint) {
+    pub fn reserve(&mut self, additional: usize) {
         let new_len = self.len() + additional;
         assert!(new_len + 1 > self.len(), "capacity overflow");
         if new_len > self.capacity() {
@@ -388,7 +388,7 @@ pub fn reserve(&mut self, additional: uint) {
     /// use std::collections::RingBuf;
     ///
     /// let mut buf = RingBuf::with_capacity(15);
-    /// buf.extend(0u..4);
+    /// buf.extend(0..4);
     /// assert_eq!(buf.capacity(), 15);
     /// buf.shrink_to_fit();
     /// assert!(buf.capacity() >= 4);
@@ -482,7 +482,7 @@ pub fn shrink_to_fit(&mut self) {
     /// ```
     #[unstable(feature = "collections",
                reason = "matches collection reform specification; waiting on panic semantics")]
-    pub fn truncate(&mut self, len: uint) {
+    pub fn truncate(&mut self, len: usize) {
         for _ in len..self.len() {
             self.pop_back();
         }
@@ -529,13 +529,13 @@ pub fn iter(&self) -> Iter<T> {
     /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[], b);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
+    pub fn iter_mut(&mut self) -> IterMut<T> {
         IterMut {
             tail: self.tail,
             head: self.head,
             cap: self.cap,
             ptr: self.ptr,
-            marker: marker::ContravariantLifetime::<'a>,
+            marker: marker::ContravariantLifetime,
         }
     }
 
@@ -552,7 +552,7 @@ pub fn into_iter(self) -> IntoIter<T> {
     #[inline]
     #[unstable(feature = "collections",
                reason = "matches collection reform specification, waiting for dust to settle")]
-    pub fn as_slices<'a>(&'a self) -> (&'a [T], &'a [T]) {
+    pub fn as_slices(&self) -> (&[T], &[T]) {
         unsafe {
             let contiguous = self.is_contiguous();
             let buf = self.buffer_as_slice();
@@ -572,7 +572,7 @@ pub fn as_slices<'a>(&'a self) -> (&'a [T], &'a [T]) {
     #[inline]
     #[unstable(feature = "collections",
                reason = "matches collection reform specification, waiting for dust to settle")]
-    pub fn as_mut_slices<'a>(&'a mut self) -> (&'a mut [T], &'a mut [T]) {
+    pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
         unsafe {
             let contiguous = self.is_contiguous();
             let head = self.head;
@@ -604,7 +604,7 @@ pub fn as_mut_slices<'a>(&'a mut self) -> (&'a mut [T], &'a mut [T]) {
     /// assert_eq!(v.len(), 1);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
+    pub fn len(&self) -> usize { count(self.tail, self.head, self.cap) }
 
     /// Returns true if the buffer contains no elements
     ///
@@ -878,7 +878,7 @@ fn is_contiguous(&self) -> bool {
     /// ```
     #[unstable(feature = "collections",
                reason = "the naming of this function may be altered")]
-    pub fn swap_back_remove(&mut self, index: uint) -> Option<T> {
+    pub fn swap_back_remove(&mut self, index: usize) -> Option<T> {
         let length = self.len();
         if length > 0 && index < length - 1 {
             self.swap(index, length - 1);
@@ -911,7 +911,7 @@ pub fn swap_back_remove(&mut self, index: uint) -> Option<T> {
     /// ```
     #[unstable(feature = "collections",
                reason = "the naming of this function may be altered")]
-    pub fn swap_front_remove(&mut self, index: uint) -> Option<T> {
+    pub fn swap_front_remove(&mut self, index: usize) -> Option<T> {
         let length = self.len();
         if length > 0 && index < length && index != 0 {
             self.swap(index, 0);
@@ -939,7 +939,7 @@ pub fn swap_front_remove(&mut self, index: uint) -> Option<T> {
     /// buf.insert(1,11);
     /// assert_eq!(Some(&11), buf.get(1));
     /// ```
-    pub fn insert(&mut self, i: uint, t: T) {
+    pub fn insert(&mut self, i: usize, t: T) {
         assert!(i <= self.len(), "index out of bounds");
         if self.is_full() {
             self.reserve(1);
@@ -1144,7 +1144,7 @@ pub fn insert(&mut self, i: uint, t: T) {
     /// assert_eq!(Some(&15), buf.get(2));
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn remove(&mut self, i: uint) -> Option<T> {
+    pub fn remove(&mut self, i: usize) -> Option<T> {
         if self.is_empty() || self.len() <= i {
             return None;
         }
@@ -1312,7 +1312,7 @@ impl<T: Clone> RingBuf<T> {
     /// ```
     #[unstable(feature = "collections",
                reason = "matches collection reform specification; waiting on panic semantics")]
-    pub fn resize(&mut self, new_len: uint, value: T) {
+    pub fn resize(&mut self, new_len: usize, value: T) {
         let len = self.len();
 
         if new_len > len {
@@ -1325,14 +1325,14 @@ pub fn resize(&mut self, new_len: uint, value: T) {
 
 /// Returns the index in the underlying buffer for a given logical element index.
 #[inline]
-fn wrap_index(index: uint, size: uint) -> uint {
+fn wrap_index(index: usize, size: usize) -> usize {
     // size is always a power of 2
     index & (size - 1)
 }
 
 /// Calculate the number of elements left to be read in the buffer
 #[inline]
-fn count(tail: uint, head: uint, size: uint) -> uint {
+fn count(tail: usize, head: usize, size: usize) -> usize {
     // size is always a power of 2
     (head - tail) & (size - 1)
 }
@@ -1341,8 +1341,8 @@ fn count(tail: uint, head: uint, size: uint) -> uint {
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Iter<'a, T:'a> {
     ring: &'a [T],
-    tail: uint,
-    head: uint
+    tail: usize,
+    head: usize
 }
 
 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
@@ -1371,7 +1371,7 @@ fn next(&mut self) -> Option<&'a T> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         let len = count(self.tail, self.head, self.ring.len());
         (len, Some(len))
     }
@@ -1395,13 +1395,13 @@ impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
     #[inline]
-    fn indexable(&self) -> uint {
+    fn indexable(&self) -> usize {
         let (len, _) = self.size_hint();
         len
     }
 
     #[inline]
-    fn idx(&mut self, j: uint) -> Option<&'a T> {
+    fn idx(&mut self, j: usize) -> Option<&'a T> {
         if j >= self.indexable() {
             None
         } else {
@@ -1418,9 +1418,9 @@ fn idx(&mut self, j: uint) -> Option<&'a T> {
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct IterMut<'a, T:'a> {
     ptr: *mut T,
-    tail: uint,
-    head: uint,
-    cap: uint,
+    tail: usize,
+    head: usize,
+    cap: usize,
     marker: marker::ContravariantLifetime<'a>,
 }
 
@@ -1437,12 +1437,12 @@ fn next(&mut self) -> Option<&'a mut T> {
         self.tail = wrap_index(self.tail + 1, self.cap);
 
         unsafe {
-            Some(&mut *self.ptr.offset(tail as int))
+            Some(&mut *self.ptr.offset(tail as isize))
         }
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         let len = count(self.tail, self.head, self.cap);
         (len, Some(len))
     }
@@ -1458,7 +1458,7 @@ fn next_back(&mut self) -> Option<&'a mut T> {
         self.head = wrap_index(self.head - 1, self.cap);
 
         unsafe {
-            Some(&mut *self.ptr.offset(self.head as int))
+            Some(&mut *self.ptr.offset(self.head as isize))
         }
     }
 }
@@ -1482,7 +1482,7 @@ fn next(&mut self) -> Option<T> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         let len = self.inner.len();
         (len, Some(len))
     }
@@ -1526,7 +1526,7 @@ fn next(&mut self) -> Option<T> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         let len = self.inner.len();
         (len, Some(len))
     }
@@ -1580,21 +1580,19 @@ fn hash(&self, state: &mut S) {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<A> Index<uint> for RingBuf<A> {
+impl<A> Index<usize> for RingBuf<A> {
     type Output = A;
 
     #[inline]
-    fn index<'a>(&'a self, i: &uint) -> &'a A {
+    fn index(&self, i: &usize) -> &A {
         self.get(*i).expect("Out of bounds access")
     }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<A> IndexMut<uint> for RingBuf<A> {
-    type Output = A;
-
+impl<A> IndexMut<usize> for RingBuf<A> {
     #[inline]
-    fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
+    fn index_mut(&mut self, i: &usize) -> &mut A {
         self.get_mut(*i).expect("Out of bounds access")
     }
 }
@@ -1673,13 +1671,13 @@ mod tests {
     #[allow(deprecated)]
     fn test_simple() {
         let mut d = RingBuf::new();
-        assert_eq!(d.len(), 0u);
+        assert_eq!(d.len(), 0);
         d.push_front(17);
         d.push_front(42);
         d.push_back(137);
-        assert_eq!(d.len(), 3u);
+        assert_eq!(d.len(), 3);
         d.push_back(137);
-        assert_eq!(d.len(), 4u);
+        assert_eq!(d.len(), 4);
         assert_eq!(*d.front().unwrap(), 42);
         assert_eq!(*d.back().unwrap(), 137);
         let mut i = d.pop_front();
@@ -1690,15 +1688,15 @@ fn test_simple() {
         assert_eq!(i, Some(137));
         i = d.pop_back();
         assert_eq!(i, Some(17));
-        assert_eq!(d.len(), 0u);
+        assert_eq!(d.len(), 0);
         d.push_back(3);
-        assert_eq!(d.len(), 1u);
+        assert_eq!(d.len(), 1);
         d.push_front(2);
-        assert_eq!(d.len(), 2u);
+        assert_eq!(d.len(), 2);
         d.push_back(4);
-        assert_eq!(d.len(), 3u);
+        assert_eq!(d.len(), 3);
         d.push_front(1);
-        assert_eq!(d.len(), 4u);
+        assert_eq!(d.len(), 4);
         debug!("{}", d[0]);
         debug!("{}", d[1]);
         debug!("{}", d[2]);
@@ -1743,21 +1741,21 @@ fn test_parameterized<T:Clone + PartialEq + Debug>(a: T, b: T, c: T, d: T) {
     #[test]
     fn test_push_front_grow() {
         let mut deq = RingBuf::new();
-        for i in 0u..66 {
+        for i in 0..66 {
             deq.push_front(i);
         }
         assert_eq!(deq.len(), 66);
 
-        for i in 0u..66 {
+        for i in 0..66 {
             assert_eq!(deq[i], 65 - i);
         }
 
         let mut deq = RingBuf::new();
-        for i in 0u..66 {
+        for i in 0..66 {
             deq.push_back(i);
         }
 
-        for i in 0u..66 {
+        for i in 0..66 {
             assert_eq!(deq[i], i);
         }
     }
@@ -1765,7 +1763,7 @@ fn test_push_front_grow() {
     #[test]
     fn test_index() {
         let mut deq = RingBuf::new();
-        for i in 1u..4 {
+        for i in 1..4 {
             deq.push_front(i);
         }
         assert_eq!(deq[1], 2);
@@ -1775,7 +1773,7 @@ fn test_index() {
     #[should_fail]
     fn test_index_out_of_bounds() {
         let mut deq = RingBuf::new();
-        for i in 1u..4 {
+        for i in 1..4 {
             deq.push_front(i);
         }
         deq[3];
@@ -1784,7 +1782,7 @@ fn test_index_out_of_bounds() {
     #[bench]
     fn bench_new(b: &mut test::Bencher) {
         b.iter(|| {
-            let ring: RingBuf<u64> = RingBuf::new();
+            let ring: RingBuf<i32> = RingBuf::new();
             test::black_box(ring);
         })
     }
@@ -1815,7 +1813,7 @@ fn bench_push_front_100(b: &mut test::Bencher) {
 
     #[bench]
     fn bench_pop_back_100(b: &mut test::Bencher) {
-        let mut deq: RingBuf<i32> = RingBuf::with_capacity(101);
+        let mut deq= RingBuf::<i32>::with_capacity(101);
 
         b.iter(|| {
             deq.head = 100;
@@ -1828,7 +1826,7 @@ fn bench_pop_back_100(b: &mut test::Bencher) {
 
     #[bench]
     fn bench_pop_front_100(b: &mut test::Bencher) {
-        let mut deq: RingBuf<i32> = RingBuf::with_capacity(101);
+        let mut deq = RingBuf::<i32>::with_capacity(101);
 
         b.iter(|| {
             deq.head = 100;
@@ -1852,7 +1850,7 @@ fn bench_grow_1025(b: &mut test::Bencher) {
 
     #[bench]
     fn bench_iter_1000(b: &mut test::Bencher) {
-        let ring: RingBuf<i32> = (0..1000).collect();
+        let ring: RingBuf<_> = (0..1000).collect();
 
         b.iter(|| {
             let mut sum = 0;
@@ -1865,7 +1863,7 @@ fn bench_iter_1000(b: &mut test::Bencher) {
 
     #[bench]
     fn bench_mut_iter_1000(b: &mut test::Bencher) {
-        let mut ring: RingBuf<i32> = (0..1000).collect();
+        let mut ring: RingBuf<_> = (0..1000).collect();
 
         b.iter(|| {
             let mut sum = 0;
@@ -1978,11 +1976,7 @@ fn test_with_capacity_non_power_two() {
     #[test]
     fn test_reserve_exact() {
         let mut d = RingBuf::new();
-        d.push_back(0u64);
-        d.reserve_exact(50);
-        assert!(d.capacity() >= 51);
-        let mut d = RingBuf::new();
-        d.push_back(0u32);
+        d.push_back(0);
         d.reserve_exact(50);
         assert!(d.capacity() >= 51);
     }
@@ -1990,21 +1984,17 @@ fn test_reserve_exact() {
     #[test]
     fn test_reserve() {
         let mut d = RingBuf::new();
-        d.push_back(0u64);
-        d.reserve(50);
-        assert!(d.capacity() >= 51);
-        let mut d = RingBuf::new();
-        d.push_back(0u32);
+        d.push_back(0);
         d.reserve(50);
         assert!(d.capacity() >= 51);
     }
 
     #[test]
     fn test_swap() {
-        let mut d: RingBuf<i32> = (0..5).collect();
+        let mut d: RingBuf<_> = (0..5).collect();
         d.pop_front();
         d.swap(0, 3);
-        assert_eq!(d.iter().map(|&x|x).collect::<Vec<i32>>(), vec!(4, 2, 3, 1));
+        assert_eq!(d.iter().cloned().collect::<Vec<_>>(), vec!(4, 2, 3, 1));
     }
 
     #[test]
@@ -2018,7 +2008,7 @@ fn test_iter() {
         }
         {
             let b: &[_] = &[&0,&1,&2,&3,&4];
-            assert_eq!(d.iter().collect::<Vec<&i32>>(), b);
+            assert_eq!(d.iter().collect::<Vec<_>>(), b);
         }
 
         for i in 6..9 {
@@ -2026,7 +2016,7 @@ fn test_iter() {
         }
         {
             let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
-            assert_eq!(d.iter().collect::<Vec<&i32>>(), b);
+            assert_eq!(d.iter().collect::<Vec<_>>(), b);
         }
 
         let mut it = d.iter();
@@ -2049,14 +2039,14 @@ fn test_rev_iter() {
         }
         {
             let b: &[_] = &[&4,&3,&2,&1,&0];
-            assert_eq!(d.iter().rev().collect::<Vec<&i32>>(), b);
+            assert_eq!(d.iter().rev().collect::<Vec<_>>(), b);
         }
 
         for i in 6..9 {
             d.push_front(i);
         }
         let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
-        assert_eq!(d.iter().rev().collect::<Vec<&i32>>(), b);
+        assert_eq!(d.iter().rev().collect::<Vec<_>>(), b);
     }
 
     #[test]
@@ -2070,8 +2060,8 @@ fn test_mut_rev_iter_wrap() {
         assert_eq!(d.pop_front(), Some(1));
         d.push_back(4);
 
-        assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<i32>>(),
-                   vec!(4, 3, 2));
+        assert_eq!(d.iter_mut().rev().cloned().collect::<Vec<_>>(),
+                   vec![4, 3, 2]);
     }
 
     #[test]
@@ -2079,7 +2069,7 @@ fn test_mut_iter() {
         let mut d = RingBuf::new();
         assert!(d.iter_mut().next().is_none());
 
-        for i in 0u..3 {
+        for i in 0..3 {
             d.push_front(i);
         }
 
@@ -2102,7 +2092,7 @@ fn test_mut_rev_iter() {
         let mut d = RingBuf::new();
         assert!(d.iter_mut().rev().next().is_none());
 
-        for i in 0u..3 {
+        for i in 0..3 {
             d.push_front(i);
         }
 
@@ -2141,7 +2131,7 @@ fn test_into_iter() {
             }
 
             let b = vec![0,1,2,3,4];
-            assert_eq!(d.into_iter().collect::<Vec<i32>>(), b);
+            assert_eq!(d.into_iter().collect::<Vec<_>>(), b);
         }
 
         // wrapped iter
@@ -2155,7 +2145,7 @@ fn test_into_iter() {
             }
 
             let b = vec![8,7,6,0,1,2,3,4];
-            assert_eq!(d.into_iter().collect::<Vec<i32>>(), b);
+            assert_eq!(d.into_iter().collect::<Vec<_>>(), b);
         }
 
         // partially used
@@ -2224,7 +2214,7 @@ fn test_drain() {
 
         // partially used
         {
-            let mut d: RingBuf<i32> = RingBuf::new();
+            let mut d: RingBuf<_> = RingBuf::new();
             for i in 0..5 {
                 d.push_back(i);
             }
@@ -2250,12 +2240,12 @@ fn test_drain() {
     fn test_from_iter() {
         use core::iter;
         let v = vec!(1,2,3,4,5,6,7);
-        let deq: RingBuf<i32> = v.iter().map(|&x| x).collect();
-        let u: Vec<i32> = deq.iter().map(|&x| x).collect();
+        let deq: RingBuf<_> = v.iter().cloned().collect();
+        let u: Vec<_> = deq.iter().cloned().collect();
         assert_eq!(u, v);
 
-        let seq = iter::count(0u, 2).take(256);
-        let deq: RingBuf<uint> = seq.collect();
+        let seq = iter::count(0, 2).take(256);
+        let deq: RingBuf<_> = seq.collect();
         for (i, &x) in deq.iter().enumerate() {
             assert_eq!(2*i, x);
         }
@@ -2269,14 +2259,14 @@ fn test_clone() {
         d.push_front(42);
         d.push_back(137);
         d.push_back(137);
-        assert_eq!(d.len(), 4u);
+        assert_eq!(d.len(), 4);
         let mut e = d.clone();
-        assert_eq!(e.len(), 4u);
+        assert_eq!(e.len(), 4);
         while !d.is_empty() {
             assert_eq!(d.pop_back(), e.pop_back());
         }
-        assert_eq!(d.len(), 0u);
-        assert_eq!(e.len(), 0u);
+        assert_eq!(d.len(), 0);
+        assert_eq!(e.len(), 0);
     }
 
     #[test]
@@ -2333,18 +2323,18 @@ fn test_ord() {
 
     #[test]
     fn test_show() {
-        let ringbuf: RingBuf<i32> = (0..10).collect();
+        let ringbuf: RingBuf<_> = (0..10).collect();
         assert_eq!(format!("{:?}", ringbuf), "RingBuf [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
 
-        let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
-                                                                        .map(|&s| s)
+        let ringbuf: RingBuf<_> = vec!["just", "one", "test", "more"].iter()
+                                                                        .cloned()
                                                                         .collect();
         assert_eq!(format!("{:?}", ringbuf), "RingBuf [\"just\", \"one\", \"test\", \"more\"]");
     }
 
     #[test]
     fn test_drop() {
-        static mut drops: uint = 0;
+        static mut drops: i32 = 0;
         struct Elem;
         impl Drop for Elem {
             fn drop(&mut self) {
@@ -2364,7 +2354,7 @@ fn drop(&mut self) {
 
     #[test]
     fn test_drop_with_pop() {
-        static mut drops: uint = 0;
+        static mut drops: i32 = 0;
         struct Elem;
         impl Drop for Elem {
             fn drop(&mut self) {
@@ -2388,7 +2378,7 @@ fn drop(&mut self) {
 
     #[test]
     fn test_drop_clear() {
-        static mut drops: uint = 0;
+        static mut drops: i32 = 0;
         struct Elem;
         impl Drop for Elem {
             fn drop(&mut self) {
index 4b4ea3e4c3ca539729dc22c657aabc7be7221a67..679754be7490ee35edc70196650968529b6662aa 100644 (file)
@@ -26,7 +26,7 @@
 //! block of memory that a mutable slice points to:
 //!
 //! ```rust
-//! let x: &mut[int] = &mut [1, 2, 3];
+//! let x: &mut[i32] = &mut [1, 2, 3];
 //! x[1] = 7;
 //! assert_eq!(x[0], 1);
 //! assert_eq!(x[1], 7);
 pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split};
 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
 pub use core::slice::{bytes, mut_ref_slice, ref_slice};
+pub use core::slice::{from_raw_parts, from_raw_parts_mut};
 pub use core::slice::{from_raw_buf, from_raw_mut_buf};
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -168,25 +169,25 @@ pub trait SliceExt {
     /// ```
     #[unstable(feature = "collections",
                reason = "uncertain about this API approach")]
-    fn move_from(&mut self, src: Vec<Self::Item>, start: uint, end: uint) -> uint;
+    fn move_from(&mut self, src: Vec<Self::Item>, start: usize, end: usize) -> usize;
 
     /// Deprecated: use `&s[start .. end]` notation instead.
     #[unstable(feature = "collections",
                reason = "will be replaced by slice syntax")]
     #[deprecated(since = "1.0.0", reason = "use &s[start .. end] instead")]
-    fn slice(&self, start: uint, end: uint) -> &[Self::Item];
+    fn slice(&self, start: usize, end: usize) -> &[Self::Item];
 
     /// Deprecated: use `&s[start..]` notation instead.
     #[unstable(feature = "collections",
                reason = "will be replaced by slice syntax")]
     #[deprecated(since = "1.0.0", reason = "use &s[start..] instead")]
-    fn slice_from(&self, start: uint) -> &[Self::Item];
+    fn slice_from(&self, start: usize) -> &[Self::Item];
 
     /// Deprecated: use `&s[..end]` notation instead.
     #[unstable(feature = "collections",
                reason = "will be replaced by slice syntax")]
     #[deprecated(since = "1.0.0", reason = "use &s[..end] instead")]
-    fn slice_to(&self, end: uint) -> &[Self::Item];
+    fn slice_to(&self, end: usize) -> &[Self::Item];
 
     /// Divides one slice into two at an index.
     ///
@@ -205,7 +206,7 @@ pub trait SliceExt {
     /// assert_eq!([30, 20, 50], v2);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn split_at(&self, mid: uint) -> (&[Self::Item], &[Self::Item]);
+    fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
 
     /// Returns an iterator over the slice.
     #[stable(feature = "rust1", since = "1.0.0")]
@@ -245,7 +246,7 @@ fn split<F>(&self, pred: F) -> Split<Self::Item, F>
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn splitn<F>(&self, n: uint, pred: F) -> SplitN<Self::Item, F>
+    fn splitn<F>(&self, n: usize, pred: F) -> SplitN<Self::Item, F>
                  where F: FnMut(&Self::Item) -> bool;
 
     /// Returns an iterator over subslices separated by elements that match
@@ -265,7 +266,7 @@ fn splitn<F>(&self, n: uint, pred: F) -> SplitN<Self::Item, F>
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<Self::Item, F>
+    fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<Self::Item, F>
                   where F: FnMut(&Self::Item) -> bool;
 
     /// Returns an iterator over all contiguous windows of length
@@ -288,7 +289,7 @@ fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<Self::Item, F>
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn windows(&self, size: uint) -> Windows<Self::Item>;
+    fn windows(&self, size: usize) -> Windows<Self::Item>;
 
     /// Returns an iterator over `size` elements of the slice at a
     /// time. The chunks do not overlap. If `size` does not divide the
@@ -311,7 +312,7 @@ fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<Self::Item, F>
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn chunks(&self, size: uint) -> Chunks<Self::Item>;
+    fn chunks(&self, size: usize) -> Chunks<Self::Item>;
 
     /// Returns the element of a slice at the given index, or `None` if the
     /// index is out of bounds.
@@ -324,7 +325,7 @@ fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<Self::Item, F>
     /// assert_eq!(None, v.get(3));
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn get(&self, index: uint) -> Option<&Self::Item>;
+    fn get(&self, index: usize) -> Option<&Self::Item>;
 
     /// Returns the first element of a slice, or `None` if it is empty.
     ///
@@ -365,7 +366,7 @@ fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<Self::Item, F>
     /// Returns a pointer to the element at the given index, without doing
     /// bounds checking.
     #[stable(feature = "rust1", since = "1.0.0")]
-    unsafe fn get_unchecked(&self, index: uint) -> &Self::Item;
+    unsafe fn get_unchecked(&self, index: usize) -> &Self::Item;
 
     /// Returns an unsafe pointer to the slice's buffer
     ///
@@ -410,7 +411,7 @@ fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<Self::Item, F>
     /// assert!(match r { Ok(1...4) => true, _ => false, });
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn binary_search_by<F>(&self, f: F) -> Result<uint, uint> where
+    fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where
         F: FnMut(&Self::Item) -> Ordering;
 
     /// Return the number of elements in the slice
@@ -422,7 +423,7 @@ fn binary_search_by<F>(&self, f: F) -> Result<uint, uint> where
     /// assert_eq!(a.len(), 3);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn len(&self) -> uint;
+    fn len(&self) -> usize;
 
     /// Returns true if the slice has a length of 0
     ///
@@ -438,7 +439,7 @@ fn is_empty(&self) -> bool { self.len() == 0 }
     /// Returns a mutable reference to the element at the given index,
     /// or `None` if the index is out of bounds
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn get_mut(&mut self, index: uint) -> Option<&mut Self::Item>;
+    fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>;
 
     /// Work with `self` as a mut slice.
     /// Primarily intended for getting a &mut [T] from a [T; N].
@@ -449,19 +450,19 @@ fn is_empty(&self) -> bool { self.len() == 0 }
     #[unstable(feature = "collections",
                reason = "will be replaced by slice syntax")]
     #[deprecated(since = "1.0.0", reason = "use &mut s[start .. end] instead")]
-    fn slice_mut(&mut self, start: uint, end: uint) -> &mut [Self::Item];
+    fn slice_mut(&mut self, start: usize, end: usize) -> &mut [Self::Item];
 
     /// Deprecated: use `&mut s[start ..]` instead.
     #[unstable(feature = "collections",
                reason = "will be replaced by slice syntax")]
     #[deprecated(since = "1.0.0", reason = "use &mut s[start ..] instead")]
-    fn slice_from_mut(&mut self, start: uint) -> &mut [Self::Item];
+    fn slice_from_mut(&mut self, start: usize) -> &mut [Self::Item];
 
     /// Deprecated: use `&mut s[.. end]` instead.
     #[unstable(feature = "collections",
                reason = "will be replaced by slice syntax")]
     #[deprecated(since = "1.0.0", reason = "use &mut s[.. end] instead")]
-    fn slice_to_mut(&mut self, end: uint) -> &mut [Self::Item];
+    fn slice_to_mut(&mut self, end: usize) -> &mut [Self::Item];
 
     /// Returns an iterator that allows modifying each value
     #[stable(feature = "rust1", since = "1.0.0")]
@@ -495,7 +496,7 @@ fn split_mut<F>(&mut self, pred: F) -> SplitMut<Self::Item, F>
     /// `pred`, limited to splitting at most `n` times.  The matched element is
     /// not contained in the subslices.
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn splitn_mut<F>(&mut self, n: uint, pred: F) -> SplitNMut<Self::Item, F>
+    fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<Self::Item, F>
                      where F: FnMut(&Self::Item) -> bool;
 
     /// Returns an iterator over subslices separated by elements that match
@@ -503,7 +504,7 @@ fn splitn_mut<F>(&mut self, n: uint, pred: F) -> SplitNMut<Self::Item, F>
     /// the slice and works backwards.  The matched element is not contained in
     /// the subslices.
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<Self::Item, F>
+    fn rsplitn_mut<F>(&mut self,  n: usize, pred: F) -> RSplitNMut<Self::Item, F>
                       where F: FnMut(&Self::Item) -> bool;
 
     /// Returns an iterator over `chunk_size` elements of the slice at a time.
@@ -515,7 +516,7 @@ fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<Self::Item, F>
     ///
     /// Panics if `chunk_size` is 0.
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut<Self::Item>;
+    fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
 
     /// Swaps two elements in a slice.
     ///
@@ -536,7 +537,7 @@ fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<Self::Item, F>
     /// assert!(v == ["a", "d", "c", "b"]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn swap(&mut self, a: uint, b: uint);
+    fn swap(&mut self, a: usize, b: usize);
 
     /// Divides one `&mut` into two at an index.
     ///
@@ -573,7 +574,7 @@ fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<Self::Item, F>
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn split_at_mut(&mut self, mid: uint) -> (&mut [Self::Item], &mut [Self::Item]);
+    fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
 
     /// Reverse the order of elements in a slice, in place.
     ///
@@ -589,7 +590,7 @@ fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<Self::Item, F>
 
     /// Returns an unsafe mutable pointer to the element in index
     #[stable(feature = "rust1", since = "1.0.0")]
-    unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut Self::Item;
+    unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut Self::Item;
 
     /// Return an unsafe mutable pointer to the slice's buffer.
     ///
@@ -651,7 +652,7 @@ fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<Self::Item, F>
     /// assert!(dst == [3, 4, 5]);
     /// ```
     #[unstable(feature = "collections")]
-    fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone;
+    fn clone_from_slice(&mut self, &[Self::Item]) -> usize where Self::Item: Clone;
 
     /// Sorts the slice, in place.
     ///
@@ -692,12 +693,12 @@ fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<Self::Item, F>
     /// assert!(match r { Ok(1...4) => true, _ => false, });
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn binary_search(&self, x: &Self::Item) -> Result<uint, uint> where Self::Item: Ord;
+    fn binary_search(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord;
 
     /// Deprecated: use `binary_search` instead.
     #[unstable(feature = "collections")]
     #[deprecated(since = "1.0.0", reason = "use binary_search instead")]
-    fn binary_search_elem(&self, x: &Self::Item) -> Result<uint, uint> where Self::Item: Ord {
+    fn binary_search_elem(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord {
         self.binary_search(x)
     }
 
@@ -743,11 +744,11 @@ fn binary_search_elem(&self, x: &Self::Item) -> Result<uint, uint> where Self::I
 
     /// Find the first index containing a matching value.
     #[unstable(feature = "collections")]
-    fn position_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
+    fn position_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
 
     /// Find the last index containing a matching value.
     #[unstable(feature = "collections")]
-    fn rposition_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
+    fn rposition_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
 
     /// Returns true if the slice contains an element with the given value.
     ///
@@ -804,7 +805,7 @@ fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
     }
 
     #[inline]
-    fn move_from(&mut self, mut src: Vec<T>, start: uint, end: uint) -> uint {
+    fn move_from(&mut self, mut src: Vec<T>, start: usize, end: usize) -> usize {
         for (a, b) in self.iter_mut().zip(src[start .. end].iter_mut()) {
             mem::swap(a, b);
         }
@@ -812,27 +813,27 @@ fn move_from(&mut self, mut src: Vec<T>, start: uint, end: uint) -> uint {
     }
 
     #[inline]
-    fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
+    fn slice(&self, start: usize, end: usize) -> &[T] {
         &self[start .. end]
     }
 
     #[inline]
-    fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
+    fn slice_from(&self, start: usize) -> &[T] {
         &self[start ..]
     }
 
     #[inline]
-    fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
+    fn slice_to(&self, end: usize) -> &[T] {
         &self[.. end]
     }
 
     #[inline]
-    fn split_at<'a>(&'a self, mid: uint) -> (&'a [T], &'a [T]) {
+    fn split_at(&self, mid: usize) -> (&[T], &[T]) {
         core_slice::SliceExt::split_at(self, mid)
     }
 
     #[inline]
-    fn iter<'a>(&'a self) -> Iter<'a, T> {
+    fn iter(&self) -> Iter<T> {
         core_slice::SliceExt::iter(self)
     }
 
@@ -843,54 +844,54 @@ fn split<F>(&self, pred: F) -> Split<T, F>
     }
 
     #[inline]
-    fn splitn<F>(&self, n: uint, pred: F) -> SplitN<T, F>
+    fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
                  where F: FnMut(&T) -> bool {
         core_slice::SliceExt::splitn(self, n, pred)
     }
 
     #[inline]
-    fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<T, F>
+    fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
                   where F: FnMut(&T) -> bool {
         core_slice::SliceExt::rsplitn(self, n, pred)
     }
 
     #[inline]
-    fn windows<'a>(&'a self, size: uint) -> Windows<'a, T> {
+    fn windows(&self, size: usize) -> Windows<T> {
         core_slice::SliceExt::windows(self, size)
     }
 
     #[inline]
-    fn chunks<'a>(&'a self, size: uint) -> Chunks<'a, T> {
+    fn chunks(&self, size: usize) -> Chunks<T> {
         core_slice::SliceExt::chunks(self, size)
     }
 
     #[inline]
-    fn get<'a>(&'a self, index: uint) -> Option<&'a T> {
+    fn get(&self, index: usize) -> Option<&T> {
         core_slice::SliceExt::get(self, index)
     }
 
     #[inline]
-    fn first<'a>(&'a self) -> Option<&'a T> {
+    fn first(&self) -> Option<&T> {
         core_slice::SliceExt::first(self)
     }
 
     #[inline]
-    fn tail<'a>(&'a self) -> &'a [T] {
+    fn tail(&self) -> &[T] {
         core_slice::SliceExt::tail(self)
     }
 
     #[inline]
-    fn init<'a>(&'a self) -> &'a [T] {
+    fn init(&self) -> &[T] {
         core_slice::SliceExt::init(self)
     }
 
     #[inline]
-    fn last<'a>(&'a self) -> Option<&'a T> {
+    fn last(&self) -> Option<&T> {
         core_slice::SliceExt::last(self)
     }
 
     #[inline]
-    unsafe fn get_unchecked<'a>(&'a self, index: uint) -> &'a T {
+    unsafe fn get_unchecked(&self, index: usize) -> &T {
         core_slice::SliceExt::get_unchecked(self, index)
     }
 
@@ -900,13 +901,13 @@ fn as_ptr(&self) -> *const T {
     }
 
     #[inline]
-    fn binary_search_by<F>(&self, f: F) -> Result<uint, uint>
+    fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
                         where F: FnMut(&T) -> Ordering {
         core_slice::SliceExt::binary_search_by(self, f)
     }
 
     #[inline]
-    fn len(&self) -> uint {
+    fn len(&self) -> usize {
         core_slice::SliceExt::len(self)
     }
 
@@ -916,52 +917,52 @@ fn is_empty(&self) -> bool {
     }
 
     #[inline]
-    fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T> {
+    fn get_mut(&mut self, index: usize) -> Option<&mut T> {
         core_slice::SliceExt::get_mut(self, index)
     }
 
     #[inline]
-    fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
+    fn as_mut_slice(&mut self) -> &mut [T] {
         core_slice::SliceExt::as_mut_slice(self)
     }
 
     #[inline]
-    fn slice_mut<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [T] {
+    fn slice_mut(&mut self, start: usize, end: usize) -> &mut [T] {
         &mut self[start .. end]
     }
 
     #[inline]
-    fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [T] {
+    fn slice_from_mut(&mut self, start: usize) -> &mut [T] {
         &mut self[start ..]
     }
 
     #[inline]
-    fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [T] {
+    fn slice_to_mut(&mut self, end: usize) -> &mut [T] {
         &mut self[.. end]
     }
 
     #[inline]
-    fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
+    fn iter_mut(&mut self) -> IterMut<T> {
         core_slice::SliceExt::iter_mut(self)
     }
 
     #[inline]
-    fn first_mut<'a>(&'a mut self) -> Option<&'a mut T> {
+    fn first_mut(&mut self) -> Option<&mut T> {
         core_slice::SliceExt::first_mut(self)
     }
 
     #[inline]
-    fn tail_mut<'a>(&'a mut self) -> &'a mut [T] {
+    fn tail_mut(&mut self) -> &mut [T] {
         core_slice::SliceExt::tail_mut(self)
     }
 
     #[inline]
-    fn init_mut<'a>(&'a mut self) -> &'a mut [T] {
+    fn init_mut(&mut self) -> &mut [T] {
         core_slice::SliceExt::init_mut(self)
     }
 
     #[inline]
-    fn last_mut<'a>(&'a mut self) -> Option<&'a mut T> {
+    fn last_mut(&mut self) -> Option<&mut T> {
         core_slice::SliceExt::last_mut(self)
     }
 
@@ -972,29 +973,29 @@ fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
     }
 
     #[inline]
-    fn splitn_mut<F>(&mut self, n: uint, pred: F) -> SplitNMut<T, F>
+    fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
                      where F: FnMut(&T) -> bool {
         core_slice::SliceExt::splitn_mut(self, n, pred)
     }
 
     #[inline]
-    fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<T, F>
+    fn rsplitn_mut<F>(&mut self,  n: usize, pred: F) -> RSplitNMut<T, F>
                       where F: FnMut(&T) -> bool {
         core_slice::SliceExt::rsplitn_mut(self, n, pred)
     }
 
     #[inline]
-    fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> ChunksMut<'a, T> {
+    fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
         core_slice::SliceExt::chunks_mut(self, chunk_size)
     }
 
     #[inline]
-    fn swap(&mut self, a: uint, b: uint) {
+    fn swap(&mut self, a: usize, b: usize) {
         core_slice::SliceExt::swap(self, a, b)
     }
 
     #[inline]
-    fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
+    fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
         core_slice::SliceExt::split_at_mut(self, mid)
     }
 
@@ -1004,7 +1005,7 @@ fn reverse(&mut self) {
     }
 
     #[inline]
-    unsafe fn get_unchecked_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
+    unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
         core_slice::SliceExt::get_unchecked_mut(self, index)
     }
 
@@ -1029,7 +1030,7 @@ fn permutations(&self) -> Permutations<T> where T: Clone {
         }
     }
 
-    fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone {
+    fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
         core_slice::SliceExt::clone_from_slice(self, src)
     }
 
@@ -1038,7 +1039,7 @@ fn sort(&mut self) where T: Ord {
         self.sort_by(|a, b| a.cmp(b))
     }
 
-    fn binary_search(&self, x: &T) -> Result<uint, uint> where T: Ord {
+    fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
         core_slice::SliceExt::binary_search(self, x)
     }
 
@@ -1050,11 +1051,11 @@ fn prev_permutation(&mut self) -> bool where T: Ord {
         core_slice::SliceExt::prev_permutation(self)
     }
 
-    fn position_elem(&self, t: &T) -> Option<uint> where T: PartialEq {
+    fn position_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
         core_slice::SliceExt::position_elem(self, t)
     }
 
-    fn rposition_elem(&self, t: &T) -> Option<uint> where T: PartialEq {
+    fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
         core_slice::SliceExt::rposition_elem(self, t)
     }
 
@@ -1116,7 +1117,7 @@ pub trait SliceConcatExt<T: ?Sized, U> {
 
 impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] {
     fn concat(&self) -> Vec<T> {
-        let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
+        let size = self.iter().fold(0, |acc, v| acc + v.as_slice().len());
         let mut result = Vec::with_capacity(size);
         for v in self {
             result.push_all(v.as_slice())
@@ -1125,7 +1126,7 @@ fn concat(&self) -> Vec<T> {
     }
 
     fn connect(&self, sep: &T) -> Vec<T> {
-        let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
+        let size = self.iter().fold(0, |acc, v| acc + v.as_slice().len());
         let mut result = Vec::with_capacity(size + self.len());
         let mut first = true;
         for v in self {
@@ -1153,13 +1154,13 @@ pub struct ElementSwaps {
     /// If `true`, emit the last swap that returns the sequence to initial
     /// state.
     emit_reset: bool,
-    swaps_made : uint,
+    swaps_made : usize,
 }
 
 impl ElementSwaps {
     /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
     #[unstable(feature = "collections")]
-    pub fn new(length: uint) -> ElementSwaps {
+    pub fn new(length: usize) -> ElementSwaps {
         // Initialize `sdir` with a direction that position should move in
         // (all negative at the beginning) and the `size` of the
         // element (equal to the original index).
@@ -1200,17 +1201,17 @@ enum Direction { Pos, Neg }
 /// An `Index` and `Direction` together.
 #[derive(Copy, Clone)]
 struct SizeDirection {
-    size: uint,
+    size: usize,
     dir: Direction,
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Iterator for ElementSwaps {
-    type Item = (uint, uint);
+    type Item = (usize, usize);
 
     #[inline]
-    fn next(&mut self) -> Option<(uint, uint)> {
-        fn new_pos(i: uint, s: Direction) -> uint {
+    fn next(&mut self) -> Option<(usize, usize)> {
+        fn new_pos(i: usize, s: Direction) -> usize {
             i + match s { Pos => 1, Neg => -1 }
         }
 
@@ -1252,7 +1253,7 @@ fn new_pos(i: uint, s: Direction) -> uint {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         // For a vector of size n, there are exactly n! permutations.
         let n = (2..self.sdir.len() + 1).product();
         (n - self.swaps_made, Some(n - self.swaps_made))
@@ -1291,7 +1292,7 @@ fn next(&mut self) -> Option<Vec<T>> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         self.swaps.size_hint()
     }
 }
@@ -1301,7 +1302,7 @@ fn size_hint(&self) -> (uint, Option<uint>) {
 ////////////////////////////////////////////////////////////////////////////////
 
 fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
-    let len = v.len() as int;
+    let len = v.len() as isize;
     let buf_v = v.as_mut_ptr();
 
     // 1 <= i < len;
@@ -1332,7 +1333,7 @@ fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> O
                 let tmp = ptr::read(read_ptr);
                 ptr::copy_memory(buf_v.offset(j + 1),
                                  &*buf_v.offset(j),
-                                 (i - j) as uint);
+                                 (i - j) as usize);
                 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
                                                 &tmp,
                                                 1);
@@ -1344,8 +1345,8 @@ fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> O
 
 fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
     // warning: this wildly uses unsafe.
-    static BASE_INSERTION: uint = 32;
-    static LARGE_INSERTION: uint = 16;
+    static BASE_INSERTION: usize = 32;
+    static LARGE_INSERTION: usize = 16;
 
     // FIXME #12092: smaller insertion runs seems to make sorting
     // vectors of large elements a little faster on some platforms,
@@ -1371,7 +1372,7 @@ fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order
     let mut working_space = Vec::with_capacity(2 * len);
     // these both are buffers of length `len`.
     let mut buf_dat = working_space.as_mut_ptr();
-    let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
+    let mut buf_tmp = unsafe {buf_dat.offset(len as isize)};
 
     // length `len`.
     let buf_v = v.as_ptr();
@@ -1387,17 +1388,17 @@ fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order
         // start <= i < len;
         for i in start..cmp::min(start + insertion, len) {
             // j satisfies: start <= j <= i;
-            let mut j = i as int;
+            let mut j = i as isize;
             unsafe {
                 // `i` is in bounds.
-                let read_ptr = buf_v.offset(i as int);
+                let read_ptr = buf_v.offset(i as isize);
 
                 // find where to insert, we need to do strict <,
                 // rather than <=, to maintain stability.
 
                 // start <= j - 1 < len, so .offset(j - 1) is in
                 // bounds.
-                while j > start as int &&
+                while j > start as isize &&
                         compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
                     j -= 1;
                 }
@@ -1410,7 +1411,7 @@ fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order
                 // `.offset(j)` is always in bounds.
                 ptr::copy_memory(buf_dat.offset(j + 1),
                                  &*buf_dat.offset(j),
-                                 i - j as uint);
+                                 i - j as usize);
                 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
             }
         }
@@ -1431,24 +1432,24 @@ fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order
                 // the end of the first run & start of the
                 // second. Offset of `len` is defined, since this is
                 // precisely one byte past the end of the object.
-                let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
+                let right_start = buf_dat.offset(cmp::min(start + width, len) as isize);
                 // end of the second. Similar reasoning to the above re safety.
                 let right_end_idx = cmp::min(start + 2 * width, len);
-                let right_end = buf_dat.offset(right_end_idx as int);
+                let right_end = buf_dat.offset(right_end_idx as isize);
 
                 // the pointers to the elements under consideration
                 // from the two runs.
 
                 // both of these are in bounds.
-                let mut left = buf_dat.offset(start as int);
+                let mut left = buf_dat.offset(start as isize);
                 let mut right = right_start;
 
                 // where we're putting the results, it is a run of
                 // length `2*width`, so we step it once for each step
                 // of either `left` or `right`.  `buf_tmp` has length
                 // `len`, so these are in bounds.
-                let mut out = buf_tmp.offset(start as int);
-                let out_end = buf_tmp.offset(right_end_idx as int);
+                let mut out = buf_tmp.offset(start as isize);
+                let out_end = buf_tmp.offset(right_end_idx as isize);
 
                 while out < out_end {
                     // Either the left or the right run are exhausted,
@@ -1458,11 +1459,11 @@ fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order
                     // case).
                     if left == right_start {
                         // the number remaining in this run.
-                        let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
+                        let elems = (right_end as usize - right as usize) / mem::size_of::<T>();
                         ptr::copy_nonoverlapping_memory(out, &*right, elems);
                         break;
                     } else if right == right_end {
-                        let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
+                        let elems = (right_start as usize - left as usize) / mem::size_of::<T>();
                         ptr::copy_nonoverlapping_memory(out, &*left, elems);
                         break;
                     }
@@ -1506,7 +1507,7 @@ unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
 #[cfg(test)]
 mod tests {
     use core::cmp::Ordering::{Greater, Less, Equal};
-    use core::prelude::{Some, None, range, Clone};
+    use core::prelude::{Some, None, Clone};
     use core::prelude::{Iterator, IteratorExt};
     use core::prelude::{AsSlice};
     use core::prelude::Ord;
@@ -1519,62 +1520,62 @@ mod tests {
     use vec::Vec;
     use super::{ElementSwaps, SliceConcatExt, SliceExt};
 
-    fn square(n: uint) -> uint { n * n }
+    fn square(n: usize) -> usize { n * n }
 
-    fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
+    fn is_odd(n: &usize) -> bool { *n % 2 == 1 }
 
     #[test]
     fn test_from_fn() {
         // Test on-stack from_fn.
-        let mut v = (0u..3).map(square).collect::<Vec<_>>();
+        let mut v: Vec<_> = (0..3).map(square).collect();
         {
-            let v = v.as_slice();
-            assert_eq!(v.len(), 3u);
-            assert_eq!(v[0], 0u);
-            assert_eq!(v[1], 1u);
-            assert_eq!(v[2], 4u);
+            let v = v;
+            assert_eq!(v.len(), 3);
+            assert_eq!(v[0], 0);
+            assert_eq!(v[1], 1);
+            assert_eq!(v[2], 4);
         }
 
         // Test on-heap from_fn.
-        v = (0u..5).map(square).collect::<Vec<_>>();
+        v = (0..5).map(square).collect();
         {
-            let v = v.as_slice();
-            assert_eq!(v.len(), 5u);
-            assert_eq!(v[0], 0u);
-            assert_eq!(v[1], 1u);
-            assert_eq!(v[2], 4u);
-            assert_eq!(v[3], 9u);
-            assert_eq!(v[4], 16u);
+            let v = v;
+            assert_eq!(v.len(), 5);
+            assert_eq!(v[0], 0);
+            assert_eq!(v[1], 1);
+            assert_eq!(v[2], 4);
+            assert_eq!(v[3], 9);
+            assert_eq!(v[4], 16);
         }
     }
 
     #[test]
     fn test_from_elem() {
         // Test on-stack from_elem.
-        let mut v = vec![10u, 10u];
+        let mut v = vec![10, 10];
         {
-            let v = v.as_slice();
-            assert_eq!(v.len(), 2u);
-            assert_eq!(v[0], 10u);
-            assert_eq!(v[1], 10u);
+            let v = v;
+            assert_eq!(v.len(), 2);
+            assert_eq!(v[0], 10);
+            assert_eq!(v[1], 10);
         }
 
         // Test on-heap from_elem.
-        v = vec![20u, 20u, 20u, 20u, 20u, 20u];
+        v = vec![20; 6];
         {
             let v = v.as_slice();
-            assert_eq!(v[0], 20u);
-            assert_eq!(v[1], 20u);
-            assert_eq!(v[2], 20u);
-            assert_eq!(v[3], 20u);
-            assert_eq!(v[4], 20u);
-            assert_eq!(v[5], 20u);
+            assert_eq!(v[0], 20);
+            assert_eq!(v[1], 20);
+            assert_eq!(v[2], 20);
+            assert_eq!(v[3], 20);
+            assert_eq!(v[4], 20);
+            assert_eq!(v[5], 20);
         }
     }
 
     #[test]
     fn test_is_empty() {
-        let xs: [int; 0] = [];
+        let xs: [i32; 0] = [];
         assert!(xs.is_empty());
         assert!(![0].is_empty());
     }
@@ -1624,68 +1625,68 @@ fn test_first_mut() {
     #[test]
     fn test_tail() {
         let mut a = vec![11];
-        let b: &[int] = &[];
+        let b: &[i32] = &[];
         assert_eq!(a.tail(), b);
         a = vec![11, 12];
-        let b: &[int] = &[12];
+        let b: &[i32] = &[12];
         assert_eq!(a.tail(), b);
     }
 
     #[test]
     fn test_tail_mut() {
         let mut a = vec![11];
-        let b: &mut [int] = &mut [];
+        let b: &mut [i32] = &mut [];
         assert!(a.tail_mut() == b);
         a = vec![11, 12];
-        let b: &mut [int] = &mut [12];
+        let b: &mut [_] = &mut [12];
         assert!(a.tail_mut() == b);
     }
 
     #[test]
     #[should_fail]
     fn test_tail_empty() {
-        let a: Vec<int> = vec![];
+        let a = Vec::<i32>::new();
         a.tail();
     }
 
     #[test]
     #[should_fail]
     fn test_tail_mut_empty() {
-        let mut a: Vec<int> = vec![];
+        let mut a = Vec::<i32>::new();
         a.tail_mut();
     }
 
     #[test]
     fn test_init() {
         let mut a = vec![11];
-        let b: &[int] = &[];
+        let b: &[i32] = &[];
         assert_eq!(a.init(), b);
         a = vec![11, 12];
-        let b: &[int] = &[11];
+        let b: &[_] = &[11];
         assert_eq!(a.init(), b);
     }
 
     #[test]
     fn test_init_mut() {
         let mut a = vec![11];
-        let b: &mut [int] = &mut [];
+        let b: &mut [i32] = &mut [];
         assert!(a.init_mut() == b);
         a = vec![11, 12];
-        let b: &mut [int] = &mut [11];
+        let b: &mut [_] = &mut [11];
         assert!(a.init_mut() == b);
     }
 
     #[test]
     #[should_fail]
     fn test_init_empty() {
-        let a: Vec<int> = vec![];
+        let a = Vec::<i32>::new();
         a.init();
     }
 
     #[test]
     #[should_fail]
     fn test_init_mut_empty() {
-        let mut a: Vec<int> = vec![];
+        let mut a = Vec::<i32>::new();
         a.init_mut();
     }
 
@@ -1713,26 +1714,26 @@ fn test_last_mut() {
     fn test_slice() {
         // Test fixed length vector.
         let vec_fixed = [1, 2, 3, 4];
-        let v_a = vec_fixed[1u..vec_fixed.len()].to_vec();
-        assert_eq!(v_a.len(), 3u);
-        let v_a = v_a.as_slice();
+        let v_a = vec_fixed[1..vec_fixed.len()].to_vec();
+        assert_eq!(v_a.len(), 3);
+
         assert_eq!(v_a[0], 2);
         assert_eq!(v_a[1], 3);
         assert_eq!(v_a[2], 4);
 
         // Test on stack.
         let vec_stack: &[_] = &[1, 2, 3];
-        let v_b = vec_stack[1u..3u].to_vec();
-        assert_eq!(v_b.len(), 2u);
-        let v_b = v_b.as_slice();
+        let v_b = vec_stack[1..3].to_vec();
+        assert_eq!(v_b.len(), 2);
+
         assert_eq!(v_b[0], 2);
         assert_eq!(v_b[1], 3);
 
         // Test `Box<[T]>`
         let vec_unique = vec![1, 2, 3, 4, 5, 6];
-        let v_d = vec_unique[1u..6u].to_vec();
-        assert_eq!(v_d.len(), 5u);
-        let v_d = v_d.as_slice();
+        let v_d = vec_unique[1..6].to_vec();
+        assert_eq!(v_d.len(), 5);
+
         assert_eq!(v_d[0], 2);
         assert_eq!(v_d[1], 3);
         assert_eq!(v_d[2], 4);
@@ -1742,21 +1743,21 @@ fn test_slice() {
 
     #[test]
     fn test_slice_from() {
-        let vec: &[int] = &[1, 2, 3, 4];
+        let vec: &[_] = &[1, 2, 3, 4];
         assert_eq!(&vec[], vec);
-        let b: &[int] = &[3, 4];
+        let b: &[_] = &[3, 4];
         assert_eq!(&vec[2..], b);
-        let b: &[int] = &[];
+        let b: &[_] = &[];
         assert_eq!(&vec[4..], b);
     }
 
     #[test]
     fn test_slice_to() {
-        let vec: &[int] = &[1, 2, 3, 4];
+        let vec: &[_] = &[1, 2, 3, 4];
         assert_eq!(&vec[..4], vec);
-        let b: &[int] = &[1, 2];
+        let b: &[_] = &[1, 2];
         assert_eq!(&vec[..2], b);
-        let b: &[int] = &[];
+        let b: &[_] = &[];
         assert_eq!(&vec[..0], b);
     }
 
@@ -1812,21 +1813,21 @@ fn test_push() {
         // Test on-stack push().
         let mut v = vec![];
         v.push(1);
-        assert_eq!(v.len(), 1u);
-        assert_eq!(v.as_slice()[0], 1);
+        assert_eq!(v.len(), 1);
+        assert_eq!(v[0], 1);
 
         // Test on-heap push().
         v.push(2);
-        assert_eq!(v.len(), 2u);
-        assert_eq!(v.as_slice()[0], 1);
-        assert_eq!(v.as_slice()[1], 2);
+        assert_eq!(v.len(), 2);
+        assert_eq!(v[0], 1);
+        assert_eq!(v[1], 2);
     }
 
     #[test]
     fn test_truncate() {
         let mut v = vec![box 6,box 5,box 4];
         v.truncate(1);
-        let v = v.as_slice();
+        let v = v;
         assert_eq!(v.len(), 1);
         assert_eq!(*(v[0]), 6);
         // If the unsafe block didn't drop things properly, we blow up here.
@@ -1842,19 +1843,19 @@ fn test_clear() {
 
     #[test]
     fn test_dedup() {
-        fn case(a: Vec<uint>, b: Vec<uint>) {
+        fn case(a: Vec<i32>, b: Vec<i32>) {
             let mut v = a;
             v.dedup();
             assert_eq!(v, b);
         }
         case(vec![], vec![]);
-        case(vec![1u], vec![1]);
-        case(vec![1u,1], vec![1]);
-        case(vec![1u,2,3], vec![1,2,3]);
-        case(vec![1u,1,2,3], vec![1,2,3]);
-        case(vec![1u,2,2,3], vec![1,2,3]);
-        case(vec![1u,2,3,3], vec![1,2,3]);
-        case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
+        case(vec![1], vec![1]);
+        case(vec![1,1], vec![1]);
+        case(vec![1,2,3], vec![1,2,3]);
+        case(vec![1,1,2,3], vec![1,2,3]);
+        case(vec![1,2,2,3], vec![1,2,3]);
+        case(vec![1,2,3,3], vec![1,2,3]);
+        case(vec![1,1,2,2,2,3,3], vec![1,2,3]);
     }
 
     #[test]
@@ -1887,9 +1888,9 @@ fn test_dedup_shared() {
 
     #[test]
     fn test_retain() {
-        let mut v = vec![1u, 2, 3, 4, 5];
+        let mut v = vec![1, 2, 3, 4, 5];
         v.retain(is_odd);
-        assert_eq!(v, vec![1u, 3, 5]);
+        assert_eq!(v, vec![1, 3, 5]);
     }
 
     #[test]
@@ -1912,7 +1913,7 @@ fn test_element_swaps() {
     #[test]
     fn test_permutations() {
         {
-            let v: [int; 0] = [];
+            let v: [i32; 0] = [];
             let mut it = v.permutations();
             let (min_size, max_opt) = it.size_hint();
             assert_eq!(min_size, 1);
@@ -1964,56 +1965,56 @@ fn test_permutations() {
 
     #[test]
     fn test_lexicographic_permutations() {
-        let v : &mut[int] = &mut[1, 2, 3, 4, 5];
+        let v : &mut[_] = &mut[1, 2, 3, 4, 5];
         assert!(v.prev_permutation() == false);
         assert!(v.next_permutation());
-        let b: &mut[int] = &mut[1, 2, 3, 5, 4];
+        let b: &mut[_] = &mut[1, 2, 3, 5, 4];
         assert!(v == b);
         assert!(v.prev_permutation());
-        let b: &mut[int] = &mut[1, 2, 3, 4, 5];
+        let b: &mut[_] = &mut[1, 2, 3, 4, 5];
         assert!(v == b);
         assert!(v.next_permutation());
         assert!(v.next_permutation());
-        let b: &mut[int] = &mut[1, 2, 4, 3, 5];
+        let b: &mut[_] = &mut[1, 2, 4, 3, 5];
         assert!(v == b);
         assert!(v.next_permutation());
-        let b: &mut[int] = &mut[1, 2, 4, 5, 3];
+        let b: &mut[_] = &mut[1, 2, 4, 5, 3];
         assert!(v == b);
 
-        let v : &mut[int] = &mut[1, 0, 0, 0];
+        let v : &mut[_] = &mut[1, 0, 0, 0];
         assert!(v.next_permutation() == false);
         assert!(v.prev_permutation());
-        let b: &mut[int] = &mut[0, 1, 0, 0];
+        let b: &mut[_] = &mut[0, 1, 0, 0];
         assert!(v == b);
         assert!(v.prev_permutation());
-        let b: &mut[int] = &mut[0, 0, 1, 0];
+        let b: &mut[_] = &mut[0, 0, 1, 0];
         assert!(v == b);
         assert!(v.prev_permutation());
-        let b: &mut[int] = &mut[0, 0, 0, 1];
+        let b: &mut[_] = &mut[0, 0, 0, 1];
         assert!(v == b);
         assert!(v.prev_permutation() == false);
     }
 
     #[test]
     fn test_lexicographic_permutations_empty_and_short() {
-        let empty : &mut[int] = &mut[];
+        let empty : &mut[i32] = &mut[];
         assert!(empty.next_permutation() == false);
-        let b: &mut[int] = &mut[];
+        let b: &mut[i32] = &mut[];
         assert!(empty == b);
         assert!(empty.prev_permutation() == false);
         assert!(empty == b);
 
-        let one_elem : &mut[int] = &mut[4];
+        let one_elem : &mut[_] = &mut[4];
         assert!(one_elem.prev_permutation() == false);
-        let b: &mut[int] = &mut[4];
+        let b: &mut[_] = &mut[4];
         assert!(one_elem == b);
         assert!(one_elem.next_permutation() == false);
         assert!(one_elem == b);
 
-        let two_elem : &mut[int] = &mut[1, 2];
+        let two_elem : &mut[_] = &mut[1, 2];
         assert!(two_elem.prev_permutation() == false);
-        let b : &mut[int] = &mut[1, 2];
-        let c : &mut[int] = &mut[2, 1];
+        let b : &mut[_] = &mut[1, 2];
+        let c : &mut[_] = &mut[2, 1];
         assert!(two_elem == b);
         assert!(two_elem.next_permutation());
         assert!(two_elem == c);
@@ -2030,9 +2031,9 @@ fn test_position_elem() {
         assert!([].position_elem(&1).is_none());
 
         let v1 = vec![1, 2, 3, 3, 2, 5];
-        assert_eq!(v1.position_elem(&1), Some(0u));
-        assert_eq!(v1.position_elem(&2), Some(1u));
-        assert_eq!(v1.position_elem(&5), Some(5u));
+        assert_eq!(v1.position_elem(&1), Some(0));
+        assert_eq!(v1.position_elem(&2), Some(1));
+        assert_eq!(v1.position_elem(&5), Some(5));
         assert!(v1.position_elem(&4).is_none());
     }
 
@@ -2083,24 +2084,23 @@ fn test_binary_search() {
 
     #[test]
     fn test_reverse() {
-        let mut v: Vec<int> = vec![10, 20];
+        let mut v = vec![10, 20];
         assert_eq!(v[0], 10);
         assert_eq!(v[1], 20);
         v.reverse();
         assert_eq!(v[0], 20);
         assert_eq!(v[1], 10);
 
-        let mut v3: Vec<int> = vec![];
+        let mut v3 = Vec::<i32>::new();
         v3.reverse();
         assert!(v3.is_empty());
     }
 
     #[test]
     fn test_sort() {
-        for len in 4u..25 {
+        for len in 4..25 {
             for _ in 0..100 {
-                let mut v = thread_rng().gen_iter::<uint>().take(len)
-                                      .collect::<Vec<uint>>();
+                let mut v: Vec<_> = thread_rng().gen_iter::<i32>().take(len).collect();
                 let mut v1 = v.clone();
 
                 v.sort();
@@ -2115,10 +2115,10 @@ fn test_sort() {
         }
 
         // shouldn't panic
-        let mut v: [uint; 0] = [];
+        let mut v: [i32; 0] = [];
         v.sort();
 
-        let mut v = [0xDEADBEEFu];
+        let mut v = [0xDEADBEEFu64];
         v.sort();
         assert!(v == [0xDEADBEEF]);
     }
@@ -2126,7 +2126,7 @@ fn test_sort() {
     #[test]
     fn test_sort_stability() {
         for len in 4..25 {
-            for _ in 0u..10 {
+            for _ in 0..10 {
                 let mut counts = [0; 10];
 
                 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
@@ -2134,11 +2134,11 @@ fn test_sort_stability() {
                 // the second item represents which occurrence of that
                 // number this element is, i.e. the second elements
                 // will occur in sorted order.
-                let mut v = (0..len).map(|_| {
-                        let n = thread_rng().gen::<uint>() % 10;
+                let mut v: Vec<_> = (0..len).map(|_| {
+                        let n = thread_rng().gen::<usize>() % 10;
                         counts[n] += 1;
                         (n, counts[n])
-                    }).collect::<Vec<(uint, int)>>();
+                    }).collect();
 
                 // only sort on the first element, so an unstable sort
                 // may mix up the counts.
@@ -2156,28 +2156,28 @@ fn test_sort_stability() {
 
     #[test]
     fn test_concat() {
-        let v: [Vec<int>; 0] = [];
-        let c: Vec<int> = v.concat();
+        let v: [Vec<i32>; 0] = [];
+        let c = v.concat();
         assert_eq!(c, []);
-        let d: Vec<int> = [vec![1], vec![2,3]].concat();
+        let d = [vec![1], vec![2,3]].concat();
         assert_eq!(d, vec![1, 2, 3]);
 
-        let v: [&[int]; 2] = [&[1], &[2, 3]];
+        let v: &[&[_]] = &[&[1], &[2, 3]];
         assert_eq!(v.connect(&0), vec![1, 0, 2, 3]);
-        let v: [&[int]; 3] = [&[1], &[2], &[3]];
+        let v: &[&[_]] = &[&[1], &[2], &[3]];
         assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]);
     }
 
     #[test]
     fn test_connect() {
-        let v: [Vec<int>; 0] = [];
+        let v: [Vec<i32>; 0] = [];
         assert_eq!(v.connect(&0), vec![]);
         assert_eq!([vec![1], vec![2, 3]].connect(&0), vec![1, 0, 2, 3]);
         assert_eq!([vec![1], vec![2], vec![3]].connect(&0), vec![1, 0, 2, 0, 3]);
 
-        let v: [&[int]; 2] = [&[1], &[2, 3]];
+        let v: [&[_]; 2] = [&[1], &[2, 3]];
         assert_eq!(v.connect(&0), vec![1, 0, 2, 3]);
-        let v: [&[int]; 3] = [&[1], &[2], &[3]];
+        let v: [&[_]; 3] = [&[1], &[2], &[3]];
         assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]);
     }
 
@@ -2209,13 +2209,13 @@ fn test_insert_oob() {
 
     #[test]
     fn test_remove() {
-        let mut a = vec![1,2,3,4];
+        let mut a = vec![1, 2, 3, 4];
 
         assert_eq!(a.remove(2), 3);
-        assert_eq!(a, vec![1,2,4]);
+        assert_eq!(a, vec![1, 2, 4]);
 
         assert_eq!(a.remove(2), 4);
-        assert_eq!(a, vec![1,2]);
+        assert_eq!(a, vec![1, 2]);
 
         assert_eq!(a.remove(0), 1);
         assert_eq!(a, vec![2]);
@@ -2234,19 +2234,16 @@ fn test_remove_fail() {
 
     #[test]
     fn test_capacity() {
-        let mut v = vec![0u64];
-        v.reserve_exact(10u);
-        assert!(v.capacity() >= 11u);
-        let mut v = vec![0u32];
-        v.reserve_exact(10u);
-        assert!(v.capacity() >= 11u);
+        let mut v = vec![0];
+        v.reserve_exact(10);
+        assert!(v.capacity() >= 11);
     }
 
     #[test]
     fn test_slice_2() {
         let v = vec![1, 2, 3, 4, 5];
-        let v = v.slice(1u, 3u);
-        assert_eq!(v.len(), 2u);
+        let v = v.slice(1, 3);
+        assert_eq!(v.len(), 2);
         assert_eq!(v[0], 2);
         assert_eq!(v[1], 3);
     }
@@ -2256,7 +2253,7 @@ fn test_slice_2() {
     fn test_permute_fail() {
         let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
                  (box 0, Rc::new(0)), (box 0, Rc::new(0))];
-        let mut i = 0u;
+        let mut i = 0;
         for _ in v.permutations() {
             if i == 2 {
                 panic!()
@@ -2267,15 +2264,15 @@ fn test_permute_fail() {
 
     #[test]
     fn test_total_ord() {
-        let c: &[int] = &[1, 2, 3];
+        let c = &[1, 2, 3];
         [1, 2, 3, 4][].cmp(c) == Greater;
-        let c: &[int] = &[1, 2, 3, 4];
+        let c = &[1, 2, 3, 4];
         [1, 2, 3][].cmp(c) == Less;
-        let c: &[int] = &[1, 2, 3, 6];
+        let c = &[1, 2, 3, 6];
         [1, 2, 3, 4][].cmp(c) == Equal;
-        let c: &[int] = &[1, 2, 3, 4, 5, 6];
+        let c = &[1, 2, 3, 4, 5, 6];
         [1, 2, 3, 4, 5, 5, 5, 5][].cmp(c) == Less;
-        let c: &[int] = &[1, 2, 3, 4];
+        let c = &[1, 2, 3, 4];
         [2, 2][].cmp(c) == Greater;
     }
 
@@ -2377,7 +2374,7 @@ fn test_rev_iterator() {
 
     #[test]
     fn test_mut_rev_iterator() {
-        let mut xs = [1u, 2, 3, 4, 5];
+        let mut xs = [1, 2, 3, 4, 5];
         for (i,x) in xs.iter_mut().rev().enumerate() {
             *x += i;
         }
@@ -2386,77 +2383,77 @@ fn test_mut_rev_iterator() {
 
     #[test]
     fn test_move_iterator() {
-        let xs = vec![1u,2,3,4,5];
-        assert_eq!(xs.into_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
+        let xs = vec![1,2,3,4,5];
+        assert_eq!(xs.into_iter().fold(0, |a: usize, b: usize| 10*a + b), 12345);
     }
 
     #[test]
     fn test_move_rev_iterator() {
-        let xs = vec![1u,2,3,4,5];
-        assert_eq!(xs.into_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
+        let xs = vec![1,2,3,4,5];
+        assert_eq!(xs.into_iter().rev().fold(0, |a: usize, b: usize| 10*a + b), 54321);
     }
 
     #[test]
     fn test_splitator() {
         let xs = &[1,2,3,4,5];
 
-        let splits: &[&[int]] = &[&[1], &[3], &[5]];
-        assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[1], &[3], &[5]];
+        assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[], &[2,3,4,5]];
-        assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[], &[2,3,4,5]];
+        assert_eq!(xs.split(|x| *x == 1).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[1,2,3,4], &[]];
-        assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[1,2,3,4], &[]];
+        assert_eq!(xs.split(|x| *x == 5).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[1,2,3,4,5]];
-        assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[1,2,3,4,5]];
+        assert_eq!(xs.split(|x| *x == 10).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[], &[], &[], &[], &[], &[]];
-        assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[], &[], &[], &[], &[], &[]];
+        assert_eq!(xs.split(|_| true).collect::<Vec<&[i32]>>(),
                    splits);
 
-        let xs: &[int] = &[];
-        let splits: &[&[int]] = &[&[]];
-        assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>(), splits);
+        let xs: &[i32] = &[];
+        let splits: &[&[i32]] = &[&[]];
+        assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[i32]>>(), splits);
     }
 
     #[test]
     fn test_splitnator() {
         let xs = &[1,2,3,4,5];
 
-        let splits: &[&[int]] = &[&[1,2,3,4,5]];
-        assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[1,2,3,4,5]];
+        assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[1], &[3,4,5]];
-        assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[1], &[3,4,5]];
+        assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[], &[], &[], &[4,5]];
-        assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[], &[], &[], &[4,5]];
+        assert_eq!(xs.splitn(3, |_| true).collect::<Vec<_>>(),
                    splits);
 
-        let xs: &[int] = &[];
-        let splits: &[&[int]] = &[&[]];
-        assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>(), splits);
+        let xs: &[i32] = &[];
+        let splits: &[&[i32]] = &[&[]];
+        assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<_>>(), splits);
     }
 
     #[test]
     fn test_splitnator_mut() {
         let xs = &mut [1,2,3,4,5];
 
-        let splits: &[&mut [int]] = &[&mut [1,2,3,4,5]];
-        assert_eq!(xs.splitn_mut(0, |x| *x % 2 == 0).collect::<Vec<&mut [int]>>(),
+        let splits: &[&mut[_]] = &[&mut [1,2,3,4,5]];
+        assert_eq!(xs.splitn_mut(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&mut [int]] = &[&mut [1], &mut [3,4,5]];
-        assert_eq!(xs.splitn_mut(1, |x| *x % 2 == 0).collect::<Vec<&mut [int]>>(),
+        let splits: &[&mut[_]] = &[&mut [1], &mut [3,4,5]];
+        assert_eq!(xs.splitn_mut(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&mut [int]] = &[&mut [], &mut [], &mut [], &mut [4,5]];
-        assert_eq!(xs.splitn_mut(3, |_| true).collect::<Vec<&mut [int]>>(),
+        let splits: &[&mut[_]] = &[&mut [], &mut [], &mut [], &mut [4,5]];
+        assert_eq!(xs.splitn_mut(3, |_| true).collect::<Vec<_>>(),
                    splits);
 
-        let xs: &mut [int] = &mut [];
-        let splits: &[&mut [int]] = &[&mut []];
-        assert_eq!(xs.splitn_mut(1, |x| *x == 5).collect::<Vec<&mut [int]>>(),
+        let xs: &mut [i32] = &mut [];
+        let splits: &[&mut[i32]] = &[&mut []];
+        assert_eq!(xs.splitn_mut(1, |x| *x == 5).collect::<Vec<_>>(),
                    splits);
     }
 
@@ -2464,51 +2461,52 @@ fn test_splitnator_mut() {
     fn test_rsplitator() {
         let xs = &[1,2,3,4,5];
 
-        let splits: &[&[int]] = &[&[5], &[3], &[1]];
-        assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[5], &[3], &[1]];
+        assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[2,3,4,5], &[]];
-        assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[2,3,4,5], &[]];
+        assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[], &[1,2,3,4]];
-        assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[], &[1,2,3,4]];
+        assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[1,2,3,4,5]];
-        assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[1,2,3,4,5]];
+        assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<_>>(),
                    splits);
 
-        let xs: &[int] = &[];
-        let splits: &[&[int]] = &[&[]];
-        assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>(), splits);
+        let xs: &[i32] = &[];
+        let splits: &[&[i32]] = &[&[]];
+        assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[i32]>>(), splits);
     }
 
     #[test]
     fn test_rsplitnator() {
         let xs = &[1,2,3,4,5];
 
-        let splits: &[&[int]] = &[&[1,2,3,4,5]];
-        assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[1,2,3,4,5]];
+        assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[5], &[1,2,3]];
-        assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[5], &[1,2,3]];
+        assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
                    splits);
-        let splits: &[&[int]] = &[&[], &[], &[], &[1,2]];
-        assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>(),
+        let splits: &[&[_]] = &[&[], &[], &[], &[1,2]];
+        assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<_>>(),
                    splits);
 
-        let xs: &[int] = &[];
-        let splits: &[&[int]] = &[&[]];
-        assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>(), splits);
+        let xs: &[i32]  = &[];
+        let splits: &[&[i32]] = &[&[]];
+        assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[i32]>>(), splits);
     }
 
     #[test]
     fn test_windowsator() {
         let v = &[1,2,3,4];
 
-        let wins: &[&[int]] = &[&[1,2], &[2,3], &[3,4]];
-        assert_eq!(v.windows(2).collect::<Vec<&[int]>>(), wins);
-        let wins: &[&[int]] = &[&[1,2,3], &[2,3,4]];
-        assert_eq!(v.windows(3).collect::<Vec<&[int]>>(), wins);
+        let wins: &[&[_]] = &[&[1,2], &[2,3], &[3,4]];
+        assert_eq!(v.windows(2).collect::<Vec<_>>(), wins);
+
+        let wins: &[&[_]] = &[&[1,2,3], &[2,3,4]];
+        assert_eq!(v.windows(3).collect::<Vec<_>>(), wins);
         assert!(v.windows(6).next().is_none());
     }
 
@@ -2527,22 +2525,23 @@ fn test_chunksator() {
 
         assert_eq!(v.chunks(2).len(), 3);
 
-        let chunks: &[&[int]] = &[&[1,2], &[3,4], &[5]];
-        assert_eq!(v.chunks(2).collect::<Vec<&[int]>>(), chunks);
-        let chunks: &[&[int]] = &[&[1,2,3], &[4,5]];
-        assert_eq!(v.chunks(3).collect::<Vec<&[int]>>(), chunks);
-        let chunks: &[&[int]] = &[&[1,2,3,4,5]];
-        assert_eq!(v.chunks(6).collect::<Vec<&[int]>>(), chunks);
+        let chunks: &[&[_]] = &[&[1,2], &[3,4], &[5]];
+        assert_eq!(v.chunks(2).collect::<Vec<_>>(), chunks);
+        let chunks: &[&[_]] = &[&[1,2,3], &[4,5]];
+        assert_eq!(v.chunks(3).collect::<Vec<_>>(), chunks);
+        let chunks: &[&[_]] = &[&[1,2,3,4,5]];
+        assert_eq!(v.chunks(6).collect::<Vec<_>>(), chunks);
 
-        let chunks: &[&[int]] = &[&[5], &[3,4], &[1,2]];
-        assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>(), chunks);
+        let chunks: &[&[_]] = &[&[5], &[3,4], &[1,2]];
+        assert_eq!(v.chunks(2).rev().collect::<Vec<_>>(), chunks);
         let mut it = v.chunks(2);
         assert_eq!(it.indexable(), 3);
-        let chunk: &[int] = &[1,2];
+
+        let chunk: &[_] = &[1,2];
         assert_eq!(it.idx(0).unwrap(), chunk);
-        let chunk: &[int] = &[3,4];
+        let chunk: &[_] = &[3,4];
         assert_eq!(it.idx(1).unwrap(), chunk);
-        let chunk: &[int] = &[5];
+        let chunk: &[_] = &[5];
         assert_eq!(it.idx(2).unwrap(), chunk);
         assert_eq!(it.idx(3), None);
     }
@@ -2587,23 +2586,23 @@ macro_rules! test_show_vec {
             ($x:expr, $x_str:expr) => ({
                 let (x, x_str) = ($x, $x_str);
                 assert_eq!(format!("{:?}", x), x_str);
-                assert_eq!(format!("{:?}", x.as_slice()), x_str);
+                assert_eq!(format!("{:?}", x), x_str);
             })
         }
-        let empty: Vec<int> = vec![];
+        let empty = Vec::<i32>::new();
         test_show_vec!(empty, "[]");
         test_show_vec!(vec![1], "[1]");
         test_show_vec!(vec![1, 2, 3], "[1, 2, 3]");
-        test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
+        test_show_vec!(vec![vec![], vec![1], vec![1, 1]],
                        "[[], [1], [1, 1]]");
 
-        let empty_mut: &mut [int] = &mut[];
+        let empty_mut: &mut [i32] = &mut[];
         test_show_vec!(empty_mut, "[]");
-        let v: &mut[int] = &mut[1];
+        let v = &mut[1];
         test_show_vec!(v, "[1]");
-        let v: &mut[int] = &mut[1, 2, 3];
+        let v = &mut[1, 2, 3];
         test_show_vec!(v, "[1, 2, 3]");
-        let v: &mut [&mut[uint]] = &mut[&mut[], &mut[1u], &mut[1u, 1u]];
+        let v: &mut[&mut[_]] = &mut[&mut[], &mut[1], &mut[1, 1]];
         test_show_vec!(v, "[[], [1], [1, 1]]");
     }
 
@@ -2616,8 +2615,8 @@ macro_rules! t {
             }}
         }
 
-        t!(&[int]);
-        t!(Vec<int>);
+        t!(&[i32]);
+        t!(Vec<i32>);
     }
 
     #[test]
@@ -2679,7 +2678,7 @@ fn test_mut_split_at() {
     fn test_iter_zero_sized() {
         let mut v = vec![Foo, Foo, Foo];
         assert_eq!(v.len(), 3);
-        let mut cnt = 0u;
+        let mut cnt = 0;
 
         for f in &v {
             assert!(*f == Foo);
@@ -2829,15 +2828,15 @@ fn test_mut_last() {
         let h = x.last_mut();
         assert_eq!(*h.unwrap(), 5);
 
-        let y: &mut [int] = &mut [];
+        let y: &mut [i32] = &mut [];
         assert!(y.last_mut().is_none());
     }
 
     #[test]
     fn test_to_vec() {
-        let xs = box [1u, 2, 3];
+        let xs = box [1, 2, 3];
         let ys = xs.to_vec();
-        assert_eq!(ys, [1u, 2, 3]);
+        assert_eq!(ys, [1, 2, 3]);
     }
 }
 
@@ -2854,7 +2853,7 @@ mod bench {
     fn iterator(b: &mut Bencher) {
         // peculiar numbers to stop LLVM from optimising the summation
         // out.
-        let v = (0u..100).map(|i| i ^ (i << 1) ^ (i >> 1)).collect::<Vec<_>>();
+        let v: Vec<_> = (0..100).map(|i| i ^ (i << 1) ^ (i >> 1)).collect();
 
         b.iter(|| {
             let mut sum = 0;
@@ -2868,7 +2867,7 @@ fn iterator(b: &mut Bencher) {
 
     #[bench]
     fn mut_iterator(b: &mut Bencher) {
-        let mut v = repeat(0).take(100).collect::<Vec<_>>();
+        let mut v: Vec<_> = repeat(0).take(100).collect();
 
         b.iter(|| {
             let mut i = 0;
@@ -2881,8 +2880,8 @@ fn mut_iterator(b: &mut Bencher) {
 
     #[bench]
     fn concat(b: &mut Bencher) {
-        let xss: Vec<Vec<uint>> =
-            (0..100u).map(|i| (0..i).collect()).collect();
+        let xss: Vec<Vec<i32>> =
+            (0..100).map(|i| (0..i).collect()).collect();
         b.iter(|| {
             xss.concat();
         });
@@ -2890,8 +2889,8 @@ fn concat(b: &mut Bencher) {
 
     #[bench]
     fn connect(b: &mut Bencher) {
-        let xss: Vec<Vec<uint>> =
-            (0..100u).map(|i| (0..i).collect()).collect();
+        let xss: Vec<Vec<i32>> =
+            (0..100).map(|i| (0..i).collect()).collect();
         b.iter(|| {
             xss.connect(&0)
         });
@@ -2899,7 +2898,7 @@ fn connect(b: &mut Bencher) {
 
     #[bench]
     fn push(b: &mut Bencher) {
-        let mut vec: Vec<uint> = vec![];
+        let mut vec = Vec::<i32>::new();
         b.iter(|| {
             vec.push(0);
             black_box(&vec);
@@ -2908,61 +2907,61 @@ fn push(b: &mut Bencher) {
 
     #[bench]
     fn starts_with_same_vector(b: &mut Bencher) {
-        let vec: Vec<uint> = (0u..100).collect();
+        let vec: Vec<_> = (0..100).collect();
         b.iter(|| {
-            vec.starts_with(vec.as_slice())
+            vec.starts_with(&vec)
         })
     }
 
     #[bench]
     fn starts_with_single_element(b: &mut Bencher) {
-        let vec: Vec<uint> = vec![0];
+        let vec: Vec<_> = vec![0];
         b.iter(|| {
-            vec.starts_with(vec.as_slice())
+            vec.starts_with(&vec)
         })
     }
 
     #[bench]
     fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
-        let vec: Vec<uint> = (0u..100).collect();
-        let mut match_vec: Vec<uint> = (0u..99).collect();
+        let vec: Vec<_> = (0..100).collect();
+        let mut match_vec: Vec<_> = (0..99).collect();
         match_vec.push(0);
         b.iter(|| {
-            vec.starts_with(match_vec.as_slice())
+            vec.starts_with(&match_vec)
         })
     }
 
     #[bench]
     fn ends_with_same_vector(b: &mut Bencher) {
-        let vec: Vec<uint> = (0u..100).collect();
+        let vec: Vec<_> = (0..100).collect();
         b.iter(|| {
-            vec.ends_with(vec.as_slice())
+            vec.ends_with(&vec)
         })
     }
 
     #[bench]
     fn ends_with_single_element(b: &mut Bencher) {
-        let vec: Vec<uint> = vec![0];
+        let vec: Vec<_> = vec![0];
         b.iter(|| {
-            vec.ends_with(vec.as_slice())
+            vec.ends_with(&vec)
         })
     }
 
     #[bench]
     fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
-        let vec: Vec<uint> = (0u..100).collect();
-        let mut match_vec: Vec<uint> = (0u..100).collect();
-        match_vec.as_mut_slice()[0] = 200;
+        let vec: Vec<_> = (0..100).collect();
+        let mut match_vec: Vec<_> = (0..100).collect();
+        match_vec[0] = 200;
         b.iter(|| {
-            vec.starts_with(match_vec.as_slice())
+            vec.starts_with(&match_vec)
         })
     }
 
     #[bench]
     fn contains_last_element(b: &mut Bencher) {
-        let vec: Vec<uint> = (0u..100).collect();
+        let vec: Vec<_> = (0..100).collect();
         b.iter(|| {
-            vec.contains(&99u)
+            vec.contains(&99)
         })
     }
 
@@ -2976,7 +2975,7 @@ fn zero_1kb_from_elem(b: &mut Bencher) {
     #[bench]
     fn zero_1kb_set_memory(b: &mut Bencher) {
         b.iter(|| {
-            let mut v: Vec<uint> = Vec::with_capacity(1024);
+            let mut v = Vec::<u8>::with_capacity(1024);
             unsafe {
                 let vp = v.as_mut_ptr();
                 ptr::set_memory(vp, 0, 1024);
@@ -2989,11 +2988,11 @@ fn zero_1kb_set_memory(b: &mut Bencher) {
     #[bench]
     fn zero_1kb_loop_set(b: &mut Bencher) {
         b.iter(|| {
-            let mut v: Vec<uint> = Vec::with_capacity(1024);
+            let mut v = Vec::<u8>::with_capacity(1024);
             unsafe {
                 v.set_len(1024);
             }
-            for i in 0u..1024 {
+            for i in 0..1024 {
                 v[i] = 0;
             }
         });
@@ -3002,7 +3001,7 @@ fn zero_1kb_loop_set(b: &mut Bencher) {
     #[bench]
     fn zero_1kb_mut_iter(b: &mut Bencher) {
         b.iter(|| {
-            let mut v = Vec::with_capacity(1024);
+            let mut v = Vec::<u8>::with_capacity(1024);
             unsafe {
                 v.set_len(1024);
             }
@@ -3017,10 +3016,10 @@ fn zero_1kb_mut_iter(b: &mut Bencher) {
     fn random_inserts(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = repeat((0u, 0u)).take(30).collect::<Vec<_>>();
-            for _ in 0u..100 {
+            let mut v: Vec<_> = repeat((0, 0)).take(30).collect();
+            for _ in 0..100 {
                 let l = v.len();
-                v.insert(rng.gen::<uint>() % (l + 1),
+                v.insert(rng.gen::<usize>() % (l + 1),
                          (1, 1));
             }
         })
@@ -3029,10 +3028,10 @@ fn random_inserts(b: &mut Bencher) {
     fn random_removes(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = repeat((0u, 0u)).take(130).collect::<Vec<_>>();
-            for _ in 0u..100 {
+            let mut v: Vec<_> = repeat((0, 0)).take(130).collect();
+            for _ in 0..100 {
                 let l = v.len();
-                v.remove(rng.gen::<uint>() % l);
+                v.remove(rng.gen::<usize>() % l);
             }
         })
     }
@@ -3041,8 +3040,8 @@ fn random_removes(b: &mut Bencher) {
     fn sort_random_small(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
-            v.as_mut_slice().sort();
+            let mut v: Vec<_> = rng.gen_iter::<u64>().take(5).collect();
+            v.sort();
         });
         b.bytes = 5 * mem::size_of::<u64>() as u64;
     }
@@ -3051,8 +3050,8 @@ fn sort_random_small(b: &mut Bencher) {
     fn sort_random_medium(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
-            v.as_mut_slice().sort();
+            let mut v: Vec<_> = rng.gen_iter::<u64>().take(100).collect();
+            v.sort();
         });
         b.bytes = 100 * mem::size_of::<u64>() as u64;
     }
@@ -3061,22 +3060,22 @@ fn sort_random_medium(b: &mut Bencher) {
     fn sort_random_large(b: &mut Bencher) {
         let mut rng = weak_rng();
         b.iter(|| {
-            let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
-            v.as_mut_slice().sort();
+            let mut v: Vec<_> = rng.gen_iter::<u64>().take(10000).collect();
+            v.sort();
         });
         b.bytes = 10000 * mem::size_of::<u64>() as u64;
     }
 
     #[bench]
     fn sort_sorted(b: &mut Bencher) {
-        let mut v = (0u..10000).collect::<Vec<_>>();
+        let mut v: Vec<_> = (0..10000).collect();
         b.iter(|| {
             v.sort();
         });
         b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
     }
 
-    type BigSortable = (u64,u64,u64,u64);
+    type BigSortable = (u64, u64, u64, u64);
 
     #[bench]
     fn sort_big_random_small(b: &mut Bencher) {
@@ -3113,7 +3112,7 @@ fn sort_big_random_large(b: &mut Bencher) {
 
     #[bench]
     fn sort_big_sorted(b: &mut Bencher) {
-        let mut v = (0..10000u).map(|i| (i, i, i, i)).collect::<Vec<_>>();
+        let mut v: Vec<BigSortable> = (0..10000).map(|i| (i, i, i, i)).collect();
         b.iter(|| {
             v.sort();
         });
index 75f7b812974d703daba644a855e53b9721e4b206..edb6d2de1c850add53cbe37659a1d14bc6011a67 100644 (file)
@@ -80,7 +80,7 @@
 pub use core::str::{Split, SplitTerminator};
 pub use core::str::{SplitN, RSplitN};
 pub use core::str::{from_utf8, CharEq, Chars, CharIndices, Bytes};
-pub use core::str::{from_utf8_unchecked, from_c_str};
+pub use core::str::{from_utf8_unchecked, from_c_str, ParseBoolError};
 pub use unicode::str::{Words, Graphemes, GraphemeIndices};
 
 /*
@@ -199,11 +199,11 @@ fn next(&mut self) -> Option<char> {
                 let buffer = &mut self.buffer;
                 let sorted = &mut self.sorted;
                 {
-                    let callback = |&mut: d| {
+                    let callback = |d| {
                         let class =
                             unicode::char::canonical_combining_class(d);
                         if class == 0 && !*sorted {
-                            canonical_sort(buffer.as_mut_slice());
+                            canonical_sort(buffer);
                             *sorted = true;
                         }
                         buffer.push((d, class));
@@ -224,7 +224,7 @@ fn next(&mut self) -> Option<char> {
         }
 
         if !self.sorted {
-            canonical_sort(self.buffer.as_mut_slice());
+            canonical_sort(&mut self.buffer);
             self.sorted = true;
         }
 
@@ -241,7 +241,7 @@ fn next(&mut self) -> Option<char> {
         }
     }
 
-    fn size_hint(&self) -> (uint, Option<uint>) {
+    fn size_hint(&self) -> (usize, Option<usize>) {
         let (lower, _) = self.iter.size_hint();
         (lower, None)
     }
@@ -367,7 +367,7 @@ impl<'a> Iterator for Utf16Units<'a> {
     fn next(&mut self) -> Option<u16> { self.encoder.next() }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) { self.encoder.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
 }
 
 /*
@@ -464,7 +464,7 @@ fn replace(&self, from: &str, to: &str) -> String {
     #[inline]
     #[unstable(feature = "collections",
                reason = "this functionality may be moved to libunicode")]
-    fn nfd_chars<'a>(&'a self) -> Decompositions<'a> {
+    fn nfd_chars(&self) -> Decompositions {
         Decompositions {
             iter: self[].chars(),
             buffer: Vec::new(),
@@ -478,7 +478,7 @@ fn nfd_chars<'a>(&'a self) -> Decompositions<'a> {
     #[inline]
     #[unstable(feature = "collections",
                reason = "this functionality may be moved to libunicode")]
-    fn nfkd_chars<'a>(&'a self) -> Decompositions<'a> {
+    fn nfkd_chars(&self) -> Decompositions {
         Decompositions {
             iter: self[].chars(),
             buffer: Vec::new(),
@@ -492,7 +492,7 @@ fn nfkd_chars<'a>(&'a self) -> Decompositions<'a> {
     #[inline]
     #[unstable(feature = "collections",
                reason = "this functionality may be moved to libunicode")]
-    fn nfc_chars<'a>(&'a self) -> Recompositions<'a> {
+    fn nfc_chars(&self) -> Recompositions {
         Recompositions {
             iter: self.nfd_chars(),
             state: Composing,
@@ -507,7 +507,7 @@ fn nfc_chars<'a>(&'a self) -> Recompositions<'a> {
     #[inline]
     #[unstable(feature = "collections",
                reason = "this functionality may be moved to libunicode")]
-    fn nfkc_chars<'a>(&'a self) -> Recompositions<'a> {
+    fn nfkc_chars(&self) -> Recompositions {
         Recompositions {
             iter: self.nfkd_chars(),
             state: Composing,
@@ -592,7 +592,7 @@ fn char_indices(&self) -> CharIndices {
     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
     /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
     ///
-    /// let v: Vec<&str> = "abc1def2ghi".split(|&: c: char| c.is_numeric()).collect();
+    /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
     /// assert_eq!(v, vec!["abc", "def", "ghi"]);
     ///
     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
@@ -616,7 +616,7 @@ fn split<P: CharEq>(&self, pat: P) -> Split<P> {
     /// let v: Vec<&str> = "Mary had a little lambda".splitn(2, ' ').collect();
     /// assert_eq!(v, vec!["Mary", "had", "a little lambda"]);
     ///
-    /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |&: c: char| c.is_numeric()).collect();
+    /// let v: Vec<&str> = "abc1def2ghi".splitn(1, |c: char| c.is_numeric()).collect();
     /// assert_eq!(v, vec!["abc", "def2ghi"]);
     ///
     /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(2, 'X').collect();
@@ -629,7 +629,7 @@ fn split<P: CharEq>(&self, pat: P) -> Split<P> {
     /// assert_eq!(v, vec![""]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn splitn<P: CharEq>(&self, count: uint, pat: P) -> SplitN<P> {
+    fn splitn<P: CharEq>(&self, count: usize, pat: P) -> SplitN<P> {
         core_str::StrExt::splitn(&self[], count, pat)
     }
 
@@ -651,7 +651,7 @@ fn splitn<P: CharEq>(&self, count: uint, pat: P) -> SplitN<P> {
     /// let v: Vec<&str> = "Mary had a little lamb".split(' ').rev().collect();
     /// assert_eq!(v, vec!["lamb", "little", "a", "had", "Mary"]);
     ///
-    /// let v: Vec<&str> = "abc1def2ghi".split(|&: c: char| c.is_numeric()).rev().collect();
+    /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).rev().collect();
     /// assert_eq!(v, vec!["ghi", "def", "abc"]);
     ///
     /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').rev().collect();
@@ -672,14 +672,14 @@ fn split_terminator<P: CharEq>(&self, pat: P) -> SplitTerminator<P> {
     /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(2, ' ').collect();
     /// assert_eq!(v, vec!["lamb", "little", "Mary had a"]);
     ///
-    /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |&: c: char| c.is_numeric()).collect();
+    /// let v: Vec<&str> = "abc1def2ghi".rsplitn(1, |c: char| c.is_numeric()).collect();
     /// assert_eq!(v, vec!["ghi", "abc1def"]);
     ///
     /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(2, 'X').collect();
     /// assert_eq!(v, vec!["leopard", "tiger", "lionX"]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn rsplitn<P: CharEq>(&self, count: uint, pat: P) -> RSplitN<P> {
+    fn rsplitn<P: CharEq>(&self, count: usize, pat: P) -> RSplitN<P> {
         core_str::StrExt::rsplitn(&self[], count, pat)
     }
 
@@ -694,13 +694,13 @@ fn rsplitn<P: CharEq>(&self, count: uint, pat: P) -> RSplitN<P> {
     /// # Example
     ///
     /// ```rust
-    /// let v: Vec<(uint, uint)> = "abcXXXabcYYYabc".match_indices("abc").collect();
+    /// let v: Vec<(usize, usize)> = "abcXXXabcYYYabc".match_indices("abc").collect();
     /// assert_eq!(v, vec![(0,3), (6,9), (12,15)]);
     ///
-    /// let v: Vec<(uint, uint)> = "1abcabc2".match_indices("abc").collect();
+    /// let v: Vec<(usize, usize)> = "1abcabc2".match_indices("abc").collect();
     /// assert_eq!(v, vec![(1,4), (4,7)]);
     ///
-    /// let v: Vec<(uint, uint)> = "ababa".match_indices("aba").collect();
+    /// let v: Vec<(usize, usize)> = "ababa".match_indices("aba").collect();
     /// assert_eq!(v, vec![(0, 3)]); // only the first `aba`
     /// ```
     #[unstable(feature = "collections",
@@ -762,19 +762,19 @@ fn lines_any(&self) -> LinesAny {
     #[unstable(feature = "collections",
                reason = "use slice notation [a..b] instead")]
     #[deprecated(since = "1.0.0", reason = "use slice notation [a..b] instead")]
-    fn slice(&self, begin: uint, end: uint) -> &str;
+    fn slice(&self, begin: usize, end: usize) -> &str;
 
     /// Deprecated: use `s[a..]` instead.
     #[unstable(feature = "collections",
                reason = "use slice notation [a..b] instead")]
     #[deprecated(since = "1.0.0", reason = "use slice notation [a..] instead")]
-    fn slice_from(&self, begin: uint) -> &str;
+    fn slice_from(&self, begin: usize) -> &str;
 
     /// Deprecated: use `s[..a]` instead.
     #[unstable(feature = "collections",
                reason = "use slice notation [a..b] instead")]
     #[deprecated(since = "1.0.0", reason = "use slice notation [..a] instead")]
-    fn slice_to(&self, end: uint) -> &str;
+    fn slice_to(&self, end: usize) -> &str;
 
     /// Returns a slice of the string from the character range
     /// [`begin`..`end`).
@@ -801,7 +801,7 @@ fn lines_any(&self) -> LinesAny {
     /// ```
     #[unstable(feature = "collections",
                reason = "may have yet to prove its worth")]
-    fn slice_chars(&self, begin: uint, end: uint) -> &str {
+    fn slice_chars(&self, begin: usize, end: usize) -> &str {
         core_str::StrExt::slice_chars(&self[], begin, end)
     }
 
@@ -812,7 +812,7 @@ fn slice_chars(&self, begin: uint, end: uint) -> &str {
     /// Caller must check both UTF-8 character boundaries and the boundaries of
     /// the entire slice as well.
     #[stable(feature = "rust1", since = "1.0.0")]
-    unsafe fn slice_unchecked(&self, begin: uint, end: uint) -> &str {
+    unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
         core_str::StrExt::slice_unchecked(&self[], begin, end)
     }
 
@@ -853,7 +853,7 @@ fn ends_with(&self, pat: &str) -> bool {
     /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
     /// let x: &[_] = &['1', '2'];
     /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
-    /// assert_eq!("123foo1bar123".trim_matches(|&: c: char| c.is_numeric()), "foo1bar");
+    /// assert_eq!("123foo1bar123".trim_matches(|c: char| c.is_numeric()), "foo1bar");
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     fn trim_matches<P: CharEq>(&self, pat: P) -> &str {
@@ -873,7 +873,7 @@ fn trim_matches<P: CharEq>(&self, pat: P) -> &str {
     /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
     /// let x: &[_] = &['1', '2'];
     /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
-    /// assert_eq!("123foo1bar123".trim_left_matches(|&: c: char| c.is_numeric()), "foo1bar123");
+    /// assert_eq!("123foo1bar123".trim_left_matches(|c: char| c.is_numeric()), "foo1bar123");
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     fn trim_left_matches<P: CharEq>(&self, pat: P) -> &str {
@@ -893,7 +893,7 @@ fn trim_left_matches<P: CharEq>(&self, pat: P) -> &str {
     /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
     /// let x: &[_] = &['1', '2'];
     /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
-    /// assert_eq!("123foo1bar123".trim_right_matches(|&: c: char| c.is_numeric()), "123foo1bar");
+    /// assert_eq!("123foo1bar123".trim_right_matches(|c: char| c.is_numeric()), "123foo1bar");
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     fn trim_right_matches<P: CharEq>(&self, pat: P) -> &str {
@@ -925,7 +925,7 @@ fn trim_right_matches<P: CharEq>(&self, pat: P) -> &str {
     /// ```
     #[unstable(feature = "collections",
                reason = "naming is uncertain with container conventions")]
-    fn is_char_boundary(&self, index: uint) -> bool {
+    fn is_char_boundary(&self, index: usize) -> bool {
         core_str::StrExt::is_char_boundary(&self[], index)
     }
 
@@ -945,7 +945,7 @@ fn is_char_boundary(&self, index: uint) -> bool {
     /// use std::str::CharRange;
     ///
     /// let s = "中华Việt Nam";
-    /// let mut i = 0u;
+    /// let mut i = 0;
     /// while i < s.len() {
     ///     let CharRange {ch, next} = s.char_range_at(i);
     ///     println!("{}: {}", i, ch);
@@ -975,7 +975,7 @@ fn is_char_boundary(&self, index: uint) -> bool {
     ///
     /// # Return value
     ///
-    /// A record {ch: char, next: uint} containing the char value and the byte
+    /// A record {ch: char, next: usize} containing the char value and the byte
     /// index of the next Unicode character.
     ///
     /// # Panics
@@ -984,7 +984,7 @@ fn is_char_boundary(&self, index: uint) -> bool {
     /// If `i` is not the index of the beginning of a valid UTF-8 character.
     #[unstable(feature = "collections",
                reason = "naming is uncertain with container conventions")]
-    fn char_range_at(&self, start: uint) -> CharRange {
+    fn char_range_at(&self, start: usize) -> CharRange {
         core_str::StrExt::char_range_at(&self[], start)
     }
 
@@ -1000,7 +1000,7 @@ fn char_range_at(&self, start: uint) -> CharRange {
     /// If `i` is not an index following a valid UTF-8 character.
     #[unstable(feature = "collections",
                reason = "naming is uncertain with container conventions")]
-    fn char_range_at_reverse(&self, start: uint) -> CharRange {
+    fn char_range_at_reverse(&self, start: usize) -> CharRange {
         core_str::StrExt::char_range_at_reverse(&self[], start)
     }
 
@@ -1021,7 +1021,7 @@ fn char_range_at_reverse(&self, start: uint) -> CharRange {
     /// If `i` is not the index of the beginning of a valid UTF-8 character.
     #[unstable(feature = "collections",
                reason = "naming is uncertain with container conventions")]
-    fn char_at(&self, i: uint) -> char {
+    fn char_at(&self, i: usize) -> char {
         core_str::StrExt::char_at(&self[], i)
     }
 
@@ -1033,7 +1033,7 @@ fn char_at(&self, i: uint) -> char {
     /// If `i` is not an index following a valid UTF-8 character.
     #[unstable(feature = "collections",
                reason = "naming is uncertain with container conventions")]
-    fn char_at_reverse(&self, i: uint) -> char {
+    fn char_at_reverse(&self, i: usize) -> char {
         core_str::StrExt::char_at_reverse(&self[], i)
     }
 
@@ -1066,14 +1066,14 @@ fn as_bytes(&self) -> &[u8] {
     /// assert_eq!(s.find('é'), Some(14));
     ///
     /// // the first space
-    /// assert_eq!(s.find(|&: c: char| c.is_whitespace()), Some(5));
+    /// assert_eq!(s.find(|c: char| c.is_whitespace()), Some(5));
     ///
     /// // neither are found
     /// let x: &[_] = &['1', '2'];
     /// assert_eq!(s.find(x), None);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn find<P: CharEq>(&self, pat: P) -> Option<uint> {
+    fn find<P: CharEq>(&self, pat: P) -> Option<usize> {
         core_str::StrExt::find(&self[], pat)
     }
 
@@ -1094,14 +1094,14 @@ fn find<P: CharEq>(&self, pat: P) -> Option<uint> {
     /// assert_eq!(s.rfind('é'), Some(14));
     ///
     /// // the second space
-    /// assert_eq!(s.rfind(|&: c: char| c.is_whitespace()), Some(12));
+    /// assert_eq!(s.rfind(|c: char| c.is_whitespace()), Some(12));
     ///
     /// // searches for an occurrence of either `1` or `2`, but neither are found
     /// let x: &[_] = &['1', '2'];
     /// assert_eq!(s.rfind(x), None);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn rfind<P: CharEq>(&self, pat: P) -> Option<uint> {
+    fn rfind<P: CharEq>(&self, pat: P) -> Option<usize> {
         core_str::StrExt::rfind(&self[], pat)
     }
 
@@ -1126,7 +1126,7 @@ fn rfind<P: CharEq>(&self, pat: P) -> Option<uint> {
     /// ```
     #[unstable(feature = "collections",
                reason = "might get removed in favor of a more generic find in the future")]
-    fn find_str(&self, needle: &str) -> Option<uint> {
+    fn find_str(&self, needle: &str) -> Option<usize> {
         core_str::StrExt::find_str(&self[], needle)
     }
 
@@ -1170,7 +1170,7 @@ fn slice_shift_char(&self) -> Option<(char, &str)> {
     /// ```
     #[unstable(feature = "collections",
                reason = "awaiting convention about comparability of arbitrary slices")]
-    fn subslice_offset(&self, inner: &str) -> uint {
+    fn subslice_offset(&self, inner: &str) -> usize {
         core_str::StrExt::subslice_offset(&self[], inner)
     }
 
@@ -1202,7 +1202,7 @@ fn utf16_units(&self) -> Utf16Units {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
-    fn len(&self) -> uint {
+    fn len(&self) -> usize {
         core_str::StrExt::len(&self[])
     }
 
@@ -1264,8 +1264,8 @@ fn graphemes(&self, is_extended: bool) -> Graphemes {
     /// # Example
     ///
     /// ```rust
-    /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(uint, &str)>>();
-    /// let b: &[_] = &[(0u, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
+    /// let gr_inds = "a̐éö̲\r\n".grapheme_indices(true).collect::<Vec<(usize, &str)>>();
+    /// let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
     /// assert_eq!(gr_inds.as_slice(), b);
     /// ```
     #[unstable(feature = "collections",
@@ -1301,7 +1301,7 @@ fn words(&self) -> Words {
     /// `is_cjk` = `false`) if the locale is unknown.
     #[unstable(feature = "collections",
                reason = "this functionality may only be provided by libunicode")]
-    fn width(&self, is_cjk: bool) -> uint {
+    fn width(&self, is_cjk: bool) -> usize {
         UnicodeStr::width(&self[], is_cjk)
     }
 
@@ -1326,15 +1326,15 @@ fn trim_right(&self) -> &str {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl StrExt for str {
-    fn slice(&self, begin: uint, end: uint) -> &str {
+    fn slice(&self, begin: usize, end: usize) -> &str {
         &self[begin..end]
     }
 
-    fn slice_from(&self, begin: uint) -> &str {
+    fn slice_from(&self, begin: usize) -> &str {
         &self[begin..]
     }
 
-    fn slice_to(&self, end: uint) -> &str {
+    fn slice_to(&self, end: usize) -> &str {
         &self[..end]
     }
 }
@@ -1357,51 +1357,51 @@ fn test_le() {
 
     #[test]
     fn test_len() {
-        assert_eq!("".len(), 0u);
-        assert_eq!("hello world".len(), 11u);
-        assert_eq!("\x63".len(), 1u);
-        assert_eq!("\u{a2}".len(), 2u);
-        assert_eq!("\u{3c0}".len(), 2u);
-        assert_eq!("\u{2620}".len(), 3u);
-        assert_eq!("\u{1d11e}".len(), 4u);
-
-        assert_eq!("".chars().count(), 0u);
-        assert_eq!("hello world".chars().count(), 11u);
-        assert_eq!("\x63".chars().count(), 1u);
-        assert_eq!("\u{a2}".chars().count(), 1u);
-        assert_eq!("\u{3c0}".chars().count(), 1u);
-        assert_eq!("\u{2620}".chars().count(), 1u);
-        assert_eq!("\u{1d11e}".chars().count(), 1u);
-        assert_eq!("ประเทศไทย中华Việt Nam".chars().count(), 19u);
-
-        assert_eq!("hello".width(false), 10u);
-        assert_eq!("hello".width(true), 10u);
-        assert_eq!("\0\0\0\0\0".width(false), 0u);
-        assert_eq!("\0\0\0\0\0".width(true), 0u);
-        assert_eq!("".width(false), 0u);
-        assert_eq!("".width(true), 0u);
-        assert_eq!("\u{2081}\u{2082}\u{2083}\u{2084}".width(false), 4u);
-        assert_eq!("\u{2081}\u{2082}\u{2083}\u{2084}".width(true), 8u);
+        assert_eq!("".len(), 0);
+        assert_eq!("hello world".len(), 11);
+        assert_eq!("\x63".len(), 1);
+        assert_eq!("\u{a2}".len(), 2);
+        assert_eq!("\u{3c0}".len(), 2);
+        assert_eq!("\u{2620}".len(), 3);
+        assert_eq!("\u{1d11e}".len(), 4);
+
+        assert_eq!("".chars().count(), 0);
+        assert_eq!("hello world".chars().count(), 11);
+        assert_eq!("\x63".chars().count(), 1);
+        assert_eq!("\u{a2}".chars().count(), 1);
+        assert_eq!("\u{3c0}".chars().count(), 1);
+        assert_eq!("\u{2620}".chars().count(), 1);
+        assert_eq!("\u{1d11e}".chars().count(), 1);
+        assert_eq!("ประเทศไทย中华Việt Nam".chars().count(), 19);
+
+        assert_eq!("hello".width(false), 10);
+        assert_eq!("hello".width(true), 10);
+        assert_eq!("\0\0\0\0\0".width(false), 0);
+        assert_eq!("\0\0\0\0\0".width(true), 0);
+        assert_eq!("".width(false), 0);
+        assert_eq!("".width(true), 0);
+        assert_eq!("\u{2081}\u{2082}\u{2083}\u{2084}".width(false), 4);
+        assert_eq!("\u{2081}\u{2082}\u{2083}\u{2084}".width(true), 8);
     }
 
     #[test]
     fn test_find() {
-        assert_eq!("hello".find('l'), Some(2u));
-        assert_eq!("hello".find(|&: c:char| c == 'o'), Some(4u));
+        assert_eq!("hello".find('l'), Some(2));
+        assert_eq!("hello".find(|c:char| c == 'o'), Some(4));
         assert!("hello".find('x').is_none());
-        assert!("hello".find(|&: c:char| c == 'x').is_none());
-        assert_eq!("ประเทศไทย中华Việt Nam".find('华'), Some(30u));
-        assert_eq!("ประเทศไทย中华Việt Nam".find(|&: c: char| c == '华'), Some(30u));
+        assert!("hello".find(|c:char| c == 'x').is_none());
+        assert_eq!("ประเทศไทย中华Việt Nam".find('华'), Some(30));
+        assert_eq!("ประเทศไทย中华Việt Nam".find(|c: char| c == '华'), Some(30));
     }
 
     #[test]
     fn test_rfind() {
-        assert_eq!("hello".rfind('l'), Some(3u));
-        assert_eq!("hello".rfind(|&: c:char| c == 'o'), Some(4u));
+        assert_eq!("hello".rfind('l'), Some(3));
+        assert_eq!("hello".rfind(|c:char| c == 'o'), Some(4));
         assert!("hello".rfind('x').is_none());
-        assert!("hello".rfind(|&: c:char| c == 'x').is_none());
-        assert_eq!("ประเทศไทย中华Việt Nam".rfind('华'), Some(30u));
-        assert_eq!("ประเทศไทย中华Việt Nam".rfind(|&: c: char| c == '华'), Some(30u));
+        assert!("hello".rfind(|c:char| c == 'x').is_none());
+        assert_eq!("ประเทศไทย中华Việt Nam".rfind('华'), Some(30));
+        assert_eq!("ประเทศไทย中华Việt Nam".rfind(|c: char| c == '华'), Some(30));
     }
 
     #[test]
@@ -1424,37 +1424,37 @@ fn test_into_bytes() {
     #[test]
     fn test_find_str() {
         // byte positions
-        assert_eq!("".find_str(""), Some(0u));
+        assert_eq!("".find_str(""), Some(0));
         assert!("banana".find_str("apple pie").is_none());
 
         let data = "abcabc";
-        assert_eq!(data[0u..6u].find_str("ab"), Some(0u));
-        assert_eq!(data[2u..6u].find_str("ab"), Some(3u - 2u));
-        assert!(data[2u..4u].find_str("ab").is_none());
+        assert_eq!(data[0..6].find_str("ab"), Some(0));
+        assert_eq!(data[2..6].find_str("ab"), Some(3 - 2));
+        assert!(data[2..4].find_str("ab").is_none());
 
         let string = "ประเทศไทย中华Việt Nam";
         let mut data = String::from_str(string);
         data.push_str(string);
         assert!(data.find_str("ไท华").is_none());
-        assert_eq!(data[0u..43u].find_str(""), Some(0u));
-        assert_eq!(data[6u..43u].find_str(""), Some(6u - 6u));
+        assert_eq!(data[0..43].find_str(""), Some(0));
+        assert_eq!(data[6..43].find_str(""), Some(6 - 6));
 
-        assert_eq!(data[0u..43u].find_str("ประ"), Some( 0u));
-        assert_eq!(data[0u..43u].find_str("ทศไ"), Some(12u));
-        assert_eq!(data[0u..43u].find_str("ย中"), Some(24u));
-        assert_eq!(data[0u..43u].find_str("iệt"), Some(34u));
-        assert_eq!(data[0u..43u].find_str("Nam"), Some(40u));
+        assert_eq!(data[0..43].find_str("ประ"), Some( 0));
+        assert_eq!(data[0..43].find_str("ทศไ"), Some(12));
+        assert_eq!(data[0..43].find_str("ย中"), Some(24));
+        assert_eq!(data[0..43].find_str("iệt"), Some(34));
+        assert_eq!(data[0..43].find_str("Nam"), Some(40));
 
-        assert_eq!(data[43u..86u].find_str("ประ"), Some(43u - 43u));
-        assert_eq!(data[43u..86u].find_str("ทศไ"), Some(55u - 43u));
-        assert_eq!(data[43u..86u].find_str("ย中"), Some(67u - 43u));
-        assert_eq!(data[43u..86u].find_str("iệt"), Some(77u - 43u));
-        assert_eq!(data[43u..86u].find_str("Nam"), Some(83u - 43u));
+        assert_eq!(data[43..86].find_str("ประ"), Some(43 - 43));
+        assert_eq!(data[43..86].find_str("ทศไ"), Some(55 - 43));
+        assert_eq!(data[43..86].find_str("ย中"), Some(67 - 43));
+        assert_eq!(data[43..86].find_str("iệt"), Some(77 - 43));
+        assert_eq!(data[43..86].find_str("Nam"), Some(83 - 43));
     }
 
     #[test]
     fn test_slice_chars() {
-        fn t(a: &str, b: &str, start: uint) {
+        fn t(a: &str, b: &str, start: usize) {
             assert_eq!(a.slice_chars(start, start + b.chars().count()), b);
         }
         t("", "", 0);
@@ -1480,7 +1480,7 @@ macro_rules! test_concat {
     fn test_concat_for_different_types() {
         test_concat!("ab", vec![s("a"), s("b")]);
         test_concat!("ab", vec!["a", "b"]);
-        test_concat!("ab", vec!["a", "b"].as_slice());
+        test_concat!("ab", vec!["a", "b"]);
         test_concat!("ab", vec![s("a"), s("b")]);
     }
 
@@ -1506,9 +1506,9 @@ macro_rules! test_connect {
     fn test_connect_for_different_types() {
         test_connect!("a-b", ["a", "b"], "-");
         let hyphen = "-".to_string();
-        test_connect!("a-b", [s("a"), s("b")], hyphen.as_slice());
-        test_connect!("a-b", vec!["a", "b"], hyphen.as_slice());
-        test_connect!("a-b", vec!["a", "b"].as_slice(), "-");
+        test_connect!("a-b", [s("a"), s("b")], &*hyphen);
+        test_connect!("a-b", vec!["a", "b"], &*hyphen);
+        test_connect!("a-b", &*vec!["a", "b"], "-");
         test_connect!("a-b", vec![s("a"), s("b")], "-");
     }
 
@@ -1527,7 +1527,7 @@ fn test_unsafe_slice() {
         assert_eq!("bc", unsafe {"abc".slice_unchecked(1, 3)});
         assert_eq!("", unsafe {"abc".slice_unchecked(1, 1)});
         fn a_million_letter_a() -> String {
-            let mut i = 0u;
+            let mut i = 0;
             let mut rs = String::new();
             while i < 100000 {
                 rs.push_str("aaaaaaaaaa");
@@ -1536,7 +1536,7 @@ fn a_million_letter_a() -> String {
             rs
         }
         fn half_a_million_letter_a() -> String {
-            let mut i = 0u;
+            let mut i = 0;
             let mut rs = String::new();
             while i < 100000 {
                 rs.push_str("aaaaa");
@@ -1547,7 +1547,7 @@ fn half_a_million_letter_a() -> String {
         let letters = a_million_letter_a();
         assert!(half_a_million_letter_a() ==
             unsafe {String::from_str(letters.slice_unchecked(
-                                     0u,
+                                     0,
                                      500000))});
     }
 
@@ -1644,7 +1644,7 @@ fn test_slice() {
         assert_eq!("华", data.slice(30, 33));
 
         fn a_million_letter_x() -> String {
-            let mut i = 0u;
+            let mut i = 0;
             let mut rs = String::new();
             while i < 100000 {
                 rs.push_str("华华华华华华华华华华");
@@ -1653,7 +1653,7 @@ fn a_million_letter_x() -> String {
             rs
         }
         fn half_a_million_letter_x() -> String {
-            let mut i = 0u;
+            let mut i = 0;
             let mut rs = String::new();
             while i < 100000 {
                 rs.push_str("华华华华华");
@@ -1663,23 +1663,23 @@ fn half_a_million_letter_x() -> String {
         }
         let letters = a_million_letter_x();
         assert!(half_a_million_letter_x() ==
-            String::from_str(letters.slice(0u, 3u * 500000u)));
+            String::from_str(letters.slice(0, 3 * 500000)));
     }
 
     #[test]
     fn test_slice_2() {
         let ss = "中华Việt Nam";
 
-        assert_eq!("华", ss.slice(3u, 6u));
-        assert_eq!("Việt Nam", ss.slice(6u, 16u));
+        assert_eq!("华", ss.slice(3, 6));
+        assert_eq!("Việt Nam", ss.slice(6, 16));
 
-        assert_eq!("ab", "abc".slice(0u, 2u));
-        assert_eq!("bc", "abc".slice(1u, 3u));
-        assert_eq!("", "abc".slice(1u, 1u));
+        assert_eq!("ab", "abc".slice(0, 2));
+        assert_eq!("bc", "abc".slice(1, 3));
+        assert_eq!("", "abc".slice(1, 1));
 
-        assert_eq!("中", ss.slice(0u, 3u));
-        assert_eq!("华V", ss.slice(3u, 7u));
-        assert_eq!("", ss.slice(3u, 3u));
+        assert_eq!("中", ss.slice(0, 3));
+        assert_eq!("华V", ss.slice(3, 7));
+        assert_eq!("", ss.slice(3, 3));
         /*0: 中
           3: 华
           6: V
@@ -1695,7 +1695,7 @@ fn test_slice_2() {
     #[test]
     #[should_fail]
     fn test_slice_fail() {
-        "中华Việt Nam".slice(0u, 2u);
+        "中华Việt Nam".slice(0, 2);
     }
 
     #[test]
@@ -1723,7 +1723,7 @@ fn test_trim_left_matches() {
         assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
         let chars: &[char] = &['1', '2'];
         assert_eq!("12foo1bar12".trim_left_matches(chars), "foo1bar12");
-        assert_eq!("123foo1bar123".trim_left_matches(|&: c: char| c.is_numeric()), "foo1bar123");
+        assert_eq!("123foo1bar123".trim_left_matches(|c: char| c.is_numeric()), "foo1bar123");
     }
 
     #[test]
@@ -1738,7 +1738,7 @@ fn test_trim_right_matches() {
         assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
         let chars: &[char] = &['1', '2'];
         assert_eq!("12foo1bar12".trim_right_matches(chars), "12foo1bar");
-        assert_eq!("123foo1bar123".trim_right_matches(|&: c: char| c.is_numeric()), "123foo1bar");
+        assert_eq!("123foo1bar123".trim_right_matches(|c: char| c.is_numeric()), "123foo1bar");
     }
 
     #[test]
@@ -1753,7 +1753,7 @@ fn test_trim_matches() {
         assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
         let chars: &[char] = &['1', '2'];
         assert_eq!("12foo1bar12".trim_matches(chars), "foo1bar");
-        assert_eq!("123foo1bar123".trim_matches(|&: c: char| c.is_numeric()), "foo1bar");
+        assert_eq!("123foo1bar123".trim_matches(|c: char| c.is_numeric()), "foo1bar");
     }
 
     #[test]
@@ -1960,10 +1960,10 @@ fn vec_str_conversions() {
         let s1: String = String::from_str("All mimsy were the borogoves");
 
         let v: Vec<u8> = s1.as_bytes().to_vec();
-        let s2: String = String::from_str(from_utf8(v.as_slice()).unwrap());
-        let mut i: uint = 0u;
-        let n1: uint = s1.len();
-        let n2: uint = v.len();
+        let s2: String = String::from_str(from_utf8(&v).unwrap());
+        let mut i = 0;
+        let n1 = s1.len();
+        let n2 = v.len();
         assert_eq!(n1, n2);
         while i < n1 {
             let a: u8 = s1.as_bytes()[i];
@@ -1971,7 +1971,7 @@ fn vec_str_conversions() {
             debug!("{}", a);
             debug!("{}", b);
             assert_eq!(a, b);
-            i += 1u;
+            i += 1;
         }
     }
 
@@ -2093,7 +2093,7 @@ fn test_iterator() {
         let v = ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
 
         let mut pos = 0;
-        let mut it = s.chars();
+        let it = s.chars();
 
         for c in it {
             assert_eq!(c, v[pos]);
@@ -2108,7 +2108,7 @@ fn test_rev_iterator() {
         let v = ['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ'];
 
         let mut pos = 0;
-        let mut it = s.chars().rev();
+        let it = s.chars().rev();
 
         for c in it {
             assert_eq!(c, v[pos]);
@@ -2188,7 +2188,7 @@ fn test_char_indicesator() {
         let v = ['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m'];
 
         let mut pos = 0;
-        let mut it = s.char_indices();
+        let it = s.char_indices();
 
         for c in it {
             assert_eq!(c, (p[pos], v[pos]));
@@ -2205,7 +2205,7 @@ fn test_char_indices_revator() {
         let v = ['m', 'a', 'N', ' ', 't', 'ệ','i','V','华','中','ย','ท','ไ','ศ'];
 
         let mut pos = 0;
-        let mut it = s.char_indices().rev();
+        let it = s.char_indices().rev();
 
         for c in it {
             assert_eq!(c, (p[pos], v[pos]));
@@ -2222,14 +2222,14 @@ fn test_splitn_char_iterator() {
         let split: Vec<&str> = data.splitn(3, ' ').collect();
         assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
 
-        let split: Vec<&str> = data.splitn(3, |&: c: char| c == ' ').collect();
+        let split: Vec<&str> = data.splitn(3, |c: char| c == ' ').collect();
         assert_eq!(split, vec!["\nMäry", "häd", "ä", "little lämb\nLittle lämb\n"]);
 
         // Unicode
         let split: Vec<&str> = data.splitn(3, 'ä').collect();
         assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
 
-        let split: Vec<&str> = data.splitn(3, |&: c: char| c == 'ä').collect();
+        let split: Vec<&str> = data.splitn(3, |c: char| c == 'ä').collect();
         assert_eq!(split, vec!["\nM", "ry h", "d ", " little lämb\nLittle lämb\n"]);
     }
 
@@ -2725,11 +2725,11 @@ fn test_graphemes() {
 
         // test the indices iterators
         let s = "a̐éö̲\r\n";
-        let gr_inds = s.grapheme_indices(true).collect::<Vec<(uint, &str)>>();
-        let b: &[_] = &[(0u, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
+        let gr_inds = s.grapheme_indices(true).collect::<Vec<(usize, &str)>>();
+        let b: &[_] = &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")];
         assert_eq!(gr_inds, b);
-        let gr_inds = s.grapheme_indices(true).rev().collect::<Vec<(uint, &str)>>();
-        let b: &[_] = &[(11, "\r\n"), (6, "ö̲"), (3, "é"), (0u, "a̐")];
+        let gr_inds = s.grapheme_indices(true).rev().collect::<Vec<(usize, &str)>>();
+        let b: &[_] = &[(11, "\r\n"), (6, "ö̲"), (3, "é"), (0, "a̐")];
         assert_eq!(gr_inds, b);
         let mut gr_inds_iter = s.grapheme_indices(true);
         {
@@ -2785,17 +2785,17 @@ fn t<S: Default + Str>() {
 
     #[test]
     fn test_str_container() {
-        fn sum_len(v: &[&str]) -> uint {
+        fn sum_len(v: &[&str]) -> usize {
             v.iter().map(|x| x.len()).sum()
         }
 
         let s = String::from_str("01234");
         assert_eq!(5, sum_len(&["012", "", "34"]));
-        assert_eq!(5, sum_len(&[String::from_str("01").as_slice(),
-                                String::from_str("2").as_slice(),
-                                String::from_str("34").as_slice(),
-                                String::from_str("").as_slice()]));
-        assert_eq!(5, sum_len(&[s.as_slice()]));
+        assert_eq!(5, sum_len(&[&String::from_str("01"),
+                                &String::from_str("2"),
+                                &String::from_str("34"),
+                                &String::from_str("")]));
+        assert_eq!(5, sum_len(&[&s]));
     }
 
     #[test]
@@ -2940,7 +2940,7 @@ fn split_closure(b: &mut Bencher) {
         let s = "Mary had a little lamb, Little lamb, little-lamb.";
         let len = s.split(' ').count();
 
-        b.iter(|| assert_eq!(s.split(|&: c: char| c == ' ').count(), len));
+        b.iter(|| assert_eq!(s.split(|c: char| c == ' ').count(), len));
     }
 
     #[bench]
index 554eee765f3eb5efc4a792ed6162b7c06cea5403..63483d30dd202a46e3fbbedd95646bcb55a3c14c 100644 (file)
@@ -49,7 +49,6 @@ pub struct FromUtf8Error {
 
 /// A possible error value from the `String::from_utf16` function.
 #[stable(feature = "rust1", since = "1.0.0")]
-#[allow(missing_copy_implementations)]
 #[derive(Debug)]
 pub struct FromUtf16Error(());
 
@@ -80,7 +79,7 @@ pub fn new() -> String {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(capacity: uint) -> String {
+    pub fn with_capacity(capacity: usize) -> String {
         String {
             vec: Vec::with_capacity(capacity),
         }
@@ -126,7 +125,7 @@ pub fn from_str(string: &str) -> String {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> {
-        match str::from_utf8(vec.as_slice()) {
+        match str::from_utf8(&vec) {
             Ok(..) => Ok(String { vec: vec }),
             Err(e) => Err(FromUtf8Error { bytes: vec, error: e })
         }
@@ -157,10 +156,10 @@ pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> {
         static TAG_CONT_U8: u8 = 128u8;
         static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
         let total = v.len();
-        fn unsafe_get(xs: &[u8], i: uint) -> u8 {
+        fn unsafe_get(xs: &[u8], i: usize) -> u8 {
             unsafe { *xs.get_unchecked(i) }
         }
-        fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 {
+        fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 {
             if i >= total {
                 0
             } else {
@@ -319,7 +318,7 @@ pub fn from_utf16_lossy(v: &[u16]) -> String {
     /// * We assume that the `Vec` contains valid UTF-8.
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
+    pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String {
         String {
             vec: Vec::from_raw_parts(buf, length, capacity),
         }
@@ -375,7 +374,7 @@ pub fn push_str(&mut self, string: &str) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint {
+    pub fn capacity(&self) -> usize {
         self.vec.capacity()
     }
 
@@ -385,7 +384,7 @@ pub fn capacity(&self) -> uint {
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -396,7 +395,7 @@ pub fn capacity(&self) -> uint {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve(&mut self, additional: uint) {
+    pub fn reserve(&mut self, additional: usize) {
         self.vec.reserve(additional)
     }
 
@@ -410,7 +409,7 @@ pub fn reserve(&mut self, additional: uint) {
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -421,7 +420,7 @@ pub fn reserve(&mut self, additional: uint) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_exact(&mut self, additional: uint) {
+    pub fn reserve_exact(&mut self, additional: usize) {
         self.vec.reserve_exact(additional)
     }
 
@@ -469,7 +468,7 @@ pub fn push(&mut self, ch: char) {
             // Attempt to not use an intermediate buffer by just pushing bytes
             // directly onto this string.
             let slice = RawSlice {
-                data: self.vec.as_ptr().offset(cur_len as int),
+                data: self.vec.as_ptr().offset(cur_len as isize),
                 len: 4,
             };
             let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0);
@@ -488,8 +487,8 @@ pub fn push(&mut self, ch: char) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
-        self.vec.as_slice()
+    pub fn as_bytes(&self) -> &[u8] {
+        &self.vec
     }
 
     /// Shortens a string to the specified length.
@@ -508,7 +507,7 @@ pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn truncate(&mut self, new_len: uint) {
+    pub fn truncate(&mut self, new_len: usize) {
         assert!(self.is_char_boundary(new_len));
         self.vec.truncate(new_len)
     }
@@ -563,14 +562,14 @@ pub fn pop(&mut self) -> Option<char> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn remove(&mut self, idx: uint) -> char {
+    pub fn remove(&mut self, idx: usize) -> char {
         let len = self.len();
         assert!(idx <= len);
 
         let CharRange { ch, next } = self.char_range_at(idx);
         unsafe {
-            ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
-                             self.vec.as_ptr().offset(next as int),
+            ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as isize),
+                             self.vec.as_ptr().offset(next as isize),
                              len - next);
             self.vec.set_len(len - (next - idx));
         }
@@ -590,7 +589,7 @@ pub fn remove(&mut self, idx: uint) -> char {
     /// this function will panic.
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn insert(&mut self, idx: uint, ch: char) {
+    pub fn insert(&mut self, idx: usize, ch: char) {
         let len = self.len();
         assert!(idx <= len);
         assert!(self.is_char_boundary(idx));
@@ -599,10 +598,10 @@ pub fn insert(&mut self, idx: uint, ch: char) {
         let amt = ch.encode_utf8(&mut bits).unwrap();
 
         unsafe {
-            ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int),
-                             self.vec.as_ptr().offset(idx as int),
+            ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as isize),
+                             self.vec.as_ptr().offset(idx as isize),
                              len - idx);
-            ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int),
+            ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as isize),
                              bits.as_ptr(),
                              amt);
             self.vec.set_len(len + amt);
@@ -627,7 +626,7 @@ pub fn insert(&mut self, idx: uint, ch: char) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
+    pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
         &mut self.vec
     }
 
@@ -641,7 +640,7 @@ pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { self.vec.len() }
+    pub fn len(&self) -> usize { self.vec.len() }
 
     /// Returns true if the string contains no bytes
     ///
@@ -803,8 +802,8 @@ fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) }
 impl Str for String {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn as_slice<'a>(&'a self) -> &'a str {
-        unsafe { mem::transmute(self.vec.as_slice()) }
+    fn as_slice(&self) -> &str {
+        unsafe { mem::transmute(&*self.vec) }
     }
 }
 
@@ -854,26 +853,26 @@ fn add(mut self, other: &str) -> String {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl ops::Index<ops::Range<uint>> for String {
+impl ops::Index<ops::Range<usize>> for String {
     type Output = str;
     #[inline]
-    fn index(&self, index: &ops::Range<uint>) -> &str {
+    fn index(&self, index: &ops::Range<usize>) -> &str {
         &self[][*index]
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
-impl ops::Index<ops::RangeTo<uint>> for String {
+impl ops::Index<ops::RangeTo<usize>> for String {
     type Output = str;
     #[inline]
-    fn index(&self, index: &ops::RangeTo<uint>) -> &str {
+    fn index(&self, index: &ops::RangeTo<usize>) -> &str {
         &self[][*index]
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
-impl ops::Index<ops::RangeFrom<uint>> for String {
+impl ops::Index<ops::RangeFrom<usize>> for String {
     type Output = str;
     #[inline]
-    fn index(&self, index: &ops::RangeFrom<uint>) -> &str {
+    fn index(&self, index: &ops::RangeFrom<usize>) -> &str {
         &self[][*index]
     }
 }
@@ -882,7 +881,7 @@ impl ops::Index<ops::RangeFull> for String {
     type Output = str;
     #[inline]
     fn index(&self, _index: &ops::RangeFull) -> &str {
-        unsafe { mem::transmute(self.vec.as_slice()) }
+        unsafe { mem::transmute(&*self.vec) }
     }
 }
 
@@ -891,7 +890,7 @@ impl ops::Deref for String {
     type Target = str;
 
     #[inline]
-    fn deref<'a>(&'a self) -> &'a str {
+    fn deref(&self) -> &str {
         unsafe { mem::transmute(&self.vec[]) }
     }
 }
@@ -980,7 +979,7 @@ fn into_cow(self) -> CowString<'a> {
 impl<'a> Str for CowString<'a> {
     #[inline]
     fn as_slice<'b>(&'b self) -> &'b str {
-        (**self).as_slice()
+        &**self
     }
 }
 
@@ -1005,13 +1004,13 @@ mod tests {
     #[test]
     fn test_as_string() {
         let x = "foo";
-        assert_eq!(x, as_string(x).as_slice());
+        assert_eq!(x, &**as_string(x));
     }
 
     #[test]
     fn test_from_str() {
       let owned: Option<::std::string::String> = "string".parse().ok();
-      assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string"));
+      assert_eq!(owned.as_ref().map(|s| &**s), Some("string"));
     }
 
     #[test]
@@ -1121,15 +1120,15 @@ fn test_from_utf16() {
         for p in &pairs {
             let (s, u) = (*p).clone();
             let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>();
-            let u_as_string = String::from_utf16(u.as_slice()).unwrap();
+            let u_as_string = String::from_utf16(&u).unwrap();
 
-            assert!(::unicode::str::is_utf16(u.as_slice()));
+            assert!(::unicode::str::is_utf16(&u));
             assert_eq!(s_as_utf16, u);
 
             assert_eq!(u_as_string, s);
-            assert_eq!(String::from_utf16_lossy(u.as_slice()), s);
+            assert_eq!(String::from_utf16_lossy(&u), s);
 
-            assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s);
+            assert_eq!(String::from_utf16(&s_as_utf16).unwrap(), s);
             assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u);
         }
     }
@@ -1298,7 +1297,7 @@ fn test_slicing() {
     fn test_simple_types() {
         assert_eq!(1.to_string(), "1");
         assert_eq!((-1).to_string(), "-1");
-        assert_eq!(200u.to_string(), "200");
+        assert_eq!(200.to_string(), "200");
         assert_eq!(2u8.to_string(), "2");
         assert_eq!(true.to_string(), "true");
         assert_eq!(false.to_string(), "false");
@@ -1307,7 +1306,7 @@ fn test_simple_types() {
 
     #[test]
     fn test_vectors() {
-        let x: Vec<int> = vec![];
+        let x: Vec<i32> = vec![];
         assert_eq!(format!("{:?}", x), "[]");
         assert_eq!(format!("{:?}", vec![1]), "[1]");
         assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]");
@@ -1419,7 +1418,7 @@ fn from_utf8_lossy_invalid(b: &mut Bencher) {
     fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
         let s = repeat(0xf5u8).take(100).collect::<Vec<_>>();
         b.iter(|| {
-            let _ = String::from_utf8_lossy(s.as_slice());
+            let _ = String::from_utf8_lossy(&s);
         });
     }
 
index e9ddfd4872f7e3671c77dd1bc1aabbb879ae4412..70097c956cd0ef942f5515465691be8a6669f534 100644 (file)
@@ -66,7 +66,7 @@
 use core::ptr;
 use core::raw::Slice as RawSlice;
 use core::slice;
-use core::uint;
+use core::usize;
 
 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
 ///
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Vec<T> {
     ptr: NonZero<*mut T>,
-    len: uint,
-    cap: uint,
+    len: usize,
+    cap: usize,
 }
 
 unsafe impl<T: Send> Send for Vec<T> { }
@@ -196,9 +196,9 @@ pub fn new() -> Vec<T> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(capacity: uint) -> Vec<T> {
+    pub fn with_capacity(capacity: usize) -> Vec<T> {
         if mem::size_of::<T>() == 0 {
-            Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: uint::MAX }
+            Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: usize::MAX }
         } else if capacity == 0 {
             Vec::new()
         } else {
@@ -234,7 +234,7 @@ pub fn with_capacity(capacity: uint) -> Vec<T> {
     ///         mem::forget(v);
     ///
     ///         // Overwrite memory with 4, 5, 6
-    ///         for i in 0..len as int {
+    ///         for i in 0..len as isize {
     ///             ptr::write(p.offset(i), 4 + i);
     ///         }
     ///
@@ -245,8 +245,8 @@ pub fn with_capacity(capacity: uint) -> Vec<T> {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub unsafe fn from_raw_parts(ptr: *mut T, length: uint,
-                                 capacity: uint) -> Vec<T> {
+    pub unsafe fn from_raw_parts(ptr: *mut T, length: usize,
+                                 capacity: usize) -> Vec<T> {
         Vec { ptr: NonZero::new(ptr), len: length, cap: capacity }
     }
 
@@ -258,7 +258,7 @@ pub unsafe fn from_raw_parts(ptr: *mut T, length: uint,
     #[inline]
     #[unstable(feature = "collections",
                reason = "may be better expressed via composition")]
-    pub unsafe fn from_raw_buf(ptr: *const T, elts: uint) -> Vec<T> {
+    pub unsafe fn from_raw_buf(ptr: *const T, elts: usize) -> Vec<T> {
         let mut dst = Vec::with_capacity(elts);
         dst.set_len(elts);
         ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
@@ -276,7 +276,7 @@ pub unsafe fn from_raw_buf(ptr: *const T, elts: uint) -> Vec<T> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint {
+    pub fn capacity(&self) -> usize {
         self.cap
     }
 
@@ -285,7 +285,7 @@ pub fn capacity(&self) -> uint {
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -295,9 +295,9 @@ pub fn capacity(&self) -> uint {
     /// assert!(vec.capacity() >= 11);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve(&mut self, additional: uint) {
+    pub fn reserve(&mut self, additional: usize) {
         if self.cap - self.len < additional {
-            let err_msg = "Vec::reserve: `uint` overflow";
+            let err_msg = "Vec::reserve: `usize` overflow";
             let new_cap = self.len.checked_add(additional).expect(err_msg)
                 .checked_next_power_of_two().expect(err_msg);
             self.grow_capacity(new_cap);
@@ -314,7 +314,7 @@ pub fn reserve(&mut self, additional: uint) {
     ///
     /// # Panics
     ///
-    /// Panics if the new capacity overflows `uint`.
+    /// Panics if the new capacity overflows `usize`.
     ///
     /// # Examples
     ///
@@ -324,10 +324,10 @@ pub fn reserve(&mut self, additional: uint) {
     /// assert!(vec.capacity() >= 11);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_exact(&mut self, additional: uint) {
+    pub fn reserve_exact(&mut self, additional: usize) {
         if self.cap - self.len < additional {
             match self.len.checked_add(additional) {
-                None => panic!("Vec::reserve: `uint` overflow"),
+                None => panic!("Vec::reserve: `usize` overflow"),
                 Some(new_cap) => self.grow_capacity(new_cap)
             }
         }
@@ -382,7 +382,7 @@ pub fn shrink_to_fit(&mut self) {
     pub fn into_boxed_slice(mut self) -> Box<[T]> {
         self.shrink_to_fit();
         unsafe {
-            let xs: Box<[T]> = mem::transmute(self.as_mut_slice());
+            let xs: Box<[T]> = mem::transmute(&mut *self);
             mem::forget(self);
             xs
         }
@@ -401,7 +401,7 @@ pub fn into_boxed_slice(mut self) -> Box<[T]> {
     /// assert_eq!(vec, vec![1, 2]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn truncate(&mut self, len: uint) {
+    pub fn truncate(&mut self, len: usize) {
         unsafe {
             // drop any extra elements
             while len < self.len {
@@ -425,7 +425,7 @@ pub fn truncate(&mut self, len: uint) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
+    pub fn as_mut_slice(&mut self) -> &mut [T] {
         unsafe {
             mem::transmute(RawSlice {
                 data: *self.ptr,
@@ -455,9 +455,9 @@ pub fn into_iter(self) -> IntoIter<T> {
             let cap = self.cap;
             let begin = ptr as *const T;
             let end = if mem::size_of::<T>() == 0 {
-                (ptr as uint + self.len()) as *const T
+                (ptr as usize + self.len()) as *const T
             } else {
-                ptr.offset(self.len() as int) as *const T
+                ptr.offset(self.len() as isize) as *const T
             };
             mem::forget(self);
             IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
@@ -473,14 +473,14 @@ pub fn into_iter(self) -> IntoIter<T> {
     /// # Examples
     ///
     /// ```
-    /// let mut v = vec![1u, 2, 3, 4];
+    /// let mut v = vec![1, 2, 3, 4];
     /// unsafe {
     ///     v.set_len(1);
     /// }
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub unsafe fn set_len(&mut self, len: uint) {
+    pub unsafe fn set_len(&mut self, len: usize) {
         self.len = len;
     }
 
@@ -506,7 +506,7 @@ pub unsafe fn set_len(&mut self, len: uint) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn swap_remove(&mut self, index: uint) -> T {
+    pub fn swap_remove(&mut self, index: usize) -> T {
         let length = self.len();
         self.swap(index, length - 1);
         self.pop().unwrap()
@@ -530,7 +530,7 @@ pub fn swap_remove(&mut self, index: uint) -> T {
     /// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn insert(&mut self, index: uint, element: T) {
+    pub fn insert(&mut self, index: usize, element: T) {
         let len = self.len();
         assert!(index <= len);
         // space for the new element
@@ -539,7 +539,7 @@ pub fn insert(&mut self, index: uint, element: T) {
         unsafe { // infallible
             // The spot to put the new value
             {
-                let p = self.as_mut_ptr().offset(index as int);
+                let p = self.as_mut_ptr().offset(index as isize);
                 // Shift everything over to make space. (Duplicating the
                 // `index`th element into two consecutive places.)
                 ptr::copy_memory(p.offset(1), &*p, len - index);
@@ -566,14 +566,14 @@ pub fn insert(&mut self, index: uint, element: T) {
     /// assert_eq!(v, vec![1, 3]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn remove(&mut self, index: uint) -> T {
+    pub fn remove(&mut self, index: usize) -> T {
         let len = self.len();
         assert!(index < len);
         unsafe { // infallible
             let ret;
             {
                 // the place we are taking from.
-                let ptr = self.as_mut_ptr().offset(index as int);
+                let ptr = self.as_mut_ptr().offset(index as isize);
                 // copy it out, unsafely having a copy of the value on
                 // the stack and in the vector at the same time.
                 ret = ptr::read(ptr);
@@ -602,11 +602,11 @@ pub fn remove(&mut self, index: uint) -> T {
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
         let len = self.len();
-        let mut del = 0u;
+        let mut del = 0;
         {
-            let v = self.as_mut_slice();
+            let v = &mut **self;
 
-            for i in 0u..len {
+            for i in 0..len {
                 if !f(&v[i]) {
                     del += 1;
                 } else if del > 0 {
@@ -623,7 +623,7 @@ pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
     ///
     /// # Panics
     ///
-    /// Panics if the number of elements in the vector overflows a `uint`.
+    /// Panics if the number of elements in the vector overflows a `usize`.
     ///
     /// # Examples
     ///
@@ -655,7 +655,7 @@ pub fn push(&mut self, value: T) {
         }
 
         unsafe {
-            let end = (*self.ptr).offset(self.len as int);
+            let end = (*self.ptr).offset(self.len as isize);
             ptr::write(&mut *end, value);
             self.len += 1;
         }
@@ -687,10 +687,11 @@ pub fn pop(&mut self) -> Option<T> {
     ///
     /// # Panics
     ///
-    /// Panics if the number of elements in the vector overflows a `uint`.
+    /// Panics if the number of elements in the vector overflows a `usize`.
     ///
     /// # Examples
-    /// ```rust
+    ///
+    /// ```
     /// let mut vec = vec![1, 2, 3];
     /// let mut vec2 = vec![4, 5, 6];
     /// vec.append(&mut vec2);
@@ -737,13 +738,13 @@ pub fn append(&mut self, other: &mut Self) {
     #[inline]
     #[unstable(feature = "collections",
                reason = "matches collection reform specification, waiting for dust to settle")]
-    pub fn drain<'a>(&'a mut self) -> Drain<'a, T> {
+    pub fn drain(&mut self) -> Drain<T> {
         unsafe {
             let begin = *self.ptr as *const T;
             let end = if mem::size_of::<T>() == 0 {
-                (*self.ptr as uint + self.len()) as *const T
+                (*self.ptr as usize + self.len()) as *const T
             } else {
-                (*self.ptr).offset(self.len() as int) as *const T
+                (*self.ptr).offset(self.len() as isize) as *const T
             };
             self.set_len(0);
             Drain {
@@ -781,7 +782,7 @@ pub fn clear(&mut self) {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { self.len }
+    pub fn len(&self) -> usize { self.len }
 
     /// Returns `true` if the vector contains no elements.
     ///
@@ -808,7 +809,7 @@ pub fn is_empty(&self) -> bool { self.len() == 0 }
     /// # Examples
     ///
     /// ```
-    /// let v = vec![0u, 1, 2];
+    /// let v = vec![0, 1, 2];
     /// let w = v.map_in_place(|i| i + 3);
     /// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
     ///
@@ -835,7 +836,7 @@ pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
             // types are passed to the allocator by `Vec`.
             assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());
 
-            // This `as int` cast is safe, because the size of the elements of the
+            // This `as isize` cast is safe, because the size of the elements of the
             // vector is not 0, and:
             //
             // 1) If the size of the elements in the vector is 1, the `int` may
@@ -850,9 +851,9 @@ pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
             //        After `array.offset(offset)`: 0x9.
             //        (0x1 + 0x8 = 0x1 - 0x8)
             //
-            // 2) If the size of the elements in the vector is >1, the `uint` ->
+            // 2) If the size of the elements in the vector is >1, the `usize` ->
             //    `int` conversion can't overflow.
-            let offset = vec.len() as int;
+            let offset = vec.len() as isize;
             let start = vec.as_mut_ptr();
 
             let mut pv = PartialVecNonZeroSized {
@@ -977,8 +978,8 @@ pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
                     let u = f(t);
 
                     // Forget the `U` and increment `num_u`. This increment
-                    // cannot overflow the `uint` as we only do this for a
-                    // number of times that fits into a `uint` (and start with
+                    // cannot overflow the `usize` as we only do this for a
+                    // number of times that fits into a `usize` (and start with
                     // `0`). Again, we should not panic between these steps.
                     mem::forget(u);
                     pv.num_u += 1;
@@ -1002,8 +1003,13 @@ pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
     ///
     /// Note that the capacity of `self` does not change.
     ///
+    /// # Panics
+    ///
+    /// Panics if `at > len`.
+    ///
     /// # Examples
-    /// ```rust
+    ///
+    /// ```
     /// let mut vec = vec![1,2,3];
     /// let vec2 = vec.split_off(1);
     /// assert_eq!(vec, vec![1]);
@@ -1013,7 +1019,7 @@ pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
     #[unstable(feature = "collections",
                reason = "new API, waiting for dust to settle")]
     pub fn split_off(&mut self, at: usize) -> Self {
-        assert!(at < self.len(), "`at` out of bounds");
+        assert!(at <= self.len(), "`at` out of bounds");
 
         let other_len = self.len - at;
         let mut other = Vec::with_capacity(other_len);
@@ -1052,7 +1058,7 @@ impl<T: Clone> Vec<T> {
     /// ```
     #[unstable(feature = "collections",
                reason = "matches collection reform specification; waiting for dust to settle")]
-    pub fn resize(&mut self, new_len: uint, value: T) {
+    pub fn resize(&mut self, new_len: usize, value: T) {
         let len = self.len();
 
         if new_len > len {
@@ -1179,8 +1185,8 @@ pub fn dedup(&mut self) {
             let mut w = 1;
 
             while r < ln {
-                let p_r = p.offset(r as int);
-                let p_wm1 = p.offset((w - 1) as int);
+                let p_r = p.offset(r as isize);
+                let p_wm1 = p.offset((w - 1) as isize);
                 if *p_r != *p_wm1 {
                     if r != w {
                         let p_w = p_wm1.offset(1);
@@ -1205,7 +1211,7 @@ impl<T> Vec<T> {
     ///
     /// If the capacity for `self` is already equal to or greater than the
     /// requested capacity, then no action is taken.
-    fn grow_capacity(&mut self, capacity: uint) {
+    fn grow_capacity(&mut self, capacity: usize) {
         if mem::size_of::<T>() == 0 { return }
 
         if capacity > self.cap {
@@ -1223,7 +1229,7 @@ fn grow_capacity(&mut self, capacity: uint) {
 
 // FIXME: #13996: need a way to mark the return value as `noalias`
 #[inline(never)]
-unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: uint, size: uint) -> *mut T {
+unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: usize, size: usize) -> *mut T {
     if old_size == 0 {
         allocate(size, mem::min_align_of::<T>()) as *mut T
     } else {
@@ -1232,7 +1238,7 @@ unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: uint, size: uint) -> *mut T
 }
 
 #[inline]
-unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
+unsafe fn dealloc<T>(ptr: *mut T, len: usize) {
     if mem::size_of::<T>() != 0 {
         deallocate(ptr as *mut u8,
                    len * mem::size_of::<T>(),
@@ -1246,7 +1252,7 @@ unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
 
 #[unstable(feature = "collections")]
 impl<T:Clone> Clone for Vec<T> {
-    fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(self.as_slice()) }
+    fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(&**self) }
 
     fn clone_from(&mut self, other: &Vec<T>) {
         // drop anything in self that will not be overwritten
@@ -1269,53 +1275,53 @@ fn clone_from(&mut self, other: &Vec<T>) {
 impl<S: hash::Writer + hash::Hasher, T: Hash<S>> Hash<S> for Vec<T> {
     #[inline]
     fn hash(&self, state: &mut S) {
-        self.as_slice().hash(state);
+        Hash::hash(&**self, state)
     }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> Index<uint> for Vec<T> {
+impl<T> Index<usize> for Vec<T> {
     type Output = T;
 
     #[inline]
-    fn index<'a>(&'a self, index: &uint) -> &'a T {
-        &self.as_slice()[*index]
+    fn index(&self, index: &usize) -> &T {
+        // NB built-in indexing via `&[T]`
+        &(**self)[*index]
     }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> IndexMut<uint> for Vec<T> {
-    type Output = T;
-
+impl<T> IndexMut<usize> for Vec<T> {
     #[inline]
-    fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
-        &mut self.as_mut_slice()[*index]
+    fn index_mut(&mut self, index: &usize) -> &mut T {
+        // NB built-in indexing via `&mut [T]`
+        &mut (**self)[*index]
     }
 }
 
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> ops::Index<ops::Range<uint>> for Vec<T> {
+impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
     type Output = [T];
     #[inline]
-    fn index(&self, index: &ops::Range<uint>) -> &[T] {
-        self.as_slice().index(index)
+    fn index(&self, index: &ops::Range<usize>) -> &[T] {
+        Index::index(&**self, index)
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> ops::Index<ops::RangeTo<uint>> for Vec<T> {
+impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
     type Output = [T];
     #[inline]
-    fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
-        self.as_slice().index(index)
+    fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
+        Index::index(&**self, index)
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> ops::Index<ops::RangeFrom<uint>> for Vec<T> {
+impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
     type Output = [T];
     #[inline]
-    fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
-        self.as_slice().index(index)
+    fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
+        Index::index(&**self, index)
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -1328,32 +1334,28 @@ fn index(&self, _index: &ops::RangeFull) -> &[T] {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> ops::IndexMut<ops::Range<uint>> for Vec<T> {
-    type Output = [T];
+impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
     #[inline]
-    fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
-        self.as_mut_slice().index_mut(index)
+    fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
+        IndexMut::index_mut(&mut **self, index)
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> ops::IndexMut<ops::RangeTo<uint>> for Vec<T> {
-    type Output = [T];
+impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
     #[inline]
-    fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
-        self.as_mut_slice().index_mut(index)
+    fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
+        IndexMut::index_mut(&mut **self, index)
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> ops::IndexMut<ops::RangeFrom<uint>> for Vec<T> {
-    type Output = [T];
+impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
     #[inline]
-    fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
-        self.as_mut_slice().index_mut(index)
+    fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
+        IndexMut::index_mut(&mut **self, index)
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, _index: &ops::RangeFull) -> &mut [T] {
         self.as_mut_slice()
@@ -1364,12 +1366,12 @@ fn index_mut(&mut self, _index: &ops::RangeFull) -> &mut [T] {
 impl<T> ops::Deref for Vec<T> {
     type Target = [T];
 
-    fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
+    fn deref(&self) -> &[T] { self.as_slice() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> ops::DerefMut for Vec<T> {
-    fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() }
+    fn deref_mut(&mut self) -> &mut [T] { self.as_mut_slice() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -1489,7 +1491,7 @@ fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
 impl<T: PartialOrd> PartialOrd for Vec<T> {
     #[inline]
     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
-        self.as_slice().partial_cmp(other.as_slice())
+        PartialOrd::partial_cmp(&**self, &**other)
     }
 }
 
@@ -1500,7 +1502,7 @@ impl<T: Eq> Eq for Vec<T> {}
 impl<T: Ord> Ord for Vec<T> {
     #[inline]
     fn cmp(&self, other: &Vec<T>) -> Ordering {
-        self.as_slice().cmp(other.as_slice())
+        Ord::cmp(&**self, &**other)
     }
 }
 
@@ -1517,7 +1519,7 @@ impl<T> AsSlice<T> for Vec<T> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn as_slice<'a>(&'a self) -> &'a [T] {
+    fn as_slice(&self) -> &[T] {
         unsafe {
             mem::transmute(RawSlice {
                 data: *self.ptr,
@@ -1567,7 +1569,7 @@ fn default() -> Vec<T> {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        fmt::Debug::fmt(self.as_slice(), f)
+        fmt::Debug::fmt(&**self, f)
     }
 }
 
@@ -1607,7 +1609,7 @@ fn into_cow(self) -> CowVec<'a, T> {
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct IntoIter<T> {
     allocation: *mut T, // the block of memory allocated for the vector
-    cap: uint, // the capacity of the vector
+    cap: usize, // the capacity of the vector
     ptr: *const T,
     end: *const T
 }
@@ -1634,7 +1636,7 @@ impl<T> Iterator for IntoIter<T> {
     type Item = T;
 
     #[inline]
-    fn next<'a>(&'a mut self) -> Option<T> {
+    fn next(&mut self) -> Option<T> {
         unsafe {
             if self.ptr == self.end {
                 None
@@ -1643,10 +1645,10 @@ fn next<'a>(&'a mut self) -> Option<T> {
                     // purposefully don't use 'ptr.offset' because for
                     // vectors with 0-size elements this would return the
                     // same pointer.
-                    self.ptr = mem::transmute(self.ptr as uint + 1);
+                    self.ptr = mem::transmute(self.ptr as usize + 1);
 
                     // Use a non-null pointer value
-                    Some(ptr::read(mem::transmute(1u)))
+                    Some(ptr::read(EMPTY as *mut T))
                 } else {
                     let old = self.ptr;
                     self.ptr = self.ptr.offset(1);
@@ -1658,8 +1660,8 @@ fn next<'a>(&'a mut self) -> Option<T> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
-        let diff = (self.end as uint) - (self.ptr as uint);
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let diff = (self.end as usize) - (self.ptr as usize);
         let size = mem::size_of::<T>();
         let exact = diff / (if size == 0 {1} else {size});
         (exact, Some(exact))
@@ -1669,17 +1671,17 @@ fn size_hint(&self) -> (uint, Option<uint>) {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> DoubleEndedIterator for IntoIter<T> {
     #[inline]
-    fn next_back<'a>(&'a mut self) -> Option<T> {
+    fn next_back(&mut self) -> Option<T> {
         unsafe {
             if self.end == self.ptr {
                 None
             } else {
                 if mem::size_of::<T>() == 0 {
                     // See above for why 'ptr.offset' isn't used
-                    self.end = mem::transmute(self.end as uint - 1);
+                    self.end = mem::transmute(self.end as usize - 1);
 
                     // Use a non-null pointer value
-                    Some(ptr::read(mem::transmute(1u)))
+                    Some(ptr::read(EMPTY as *mut T))
                 } else {
                     self.end = self.end.offset(-1);
 
@@ -1731,10 +1733,10 @@ fn next(&mut self) -> Option<T> {
                     // purposefully don't use 'ptr.offset' because for
                     // vectors with 0-size elements this would return the
                     // same pointer.
-                    self.ptr = mem::transmute(self.ptr as uint + 1);
+                    self.ptr = mem::transmute(self.ptr as usize + 1);
 
                     // Use a non-null pointer value
-                    Some(ptr::read(mem::transmute(1u)))
+                    Some(ptr::read(EMPTY as *mut T))
                 } else {
                     let old = self.ptr;
                     self.ptr = self.ptr.offset(1);
@@ -1746,8 +1748,8 @@ fn next(&mut self) -> Option<T> {
     }
 
     #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
-        let diff = (self.end as uint) - (self.ptr as uint);
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let diff = (self.end as usize) - (self.ptr as usize);
         let size = mem::size_of::<T>();
         let exact = diff / (if size == 0 {1} else {size});
         (exact, Some(exact))
@@ -1764,10 +1766,10 @@ fn next_back(&mut self) -> Option<T> {
             } else {
                 if mem::size_of::<T>() == 0 {
                     // See above for why 'ptr.offset' isn't used
-                    self.end = mem::transmute(self.end as uint - 1);
+                    self.end = mem::transmute(self.end as usize - 1);
 
                     // Use a non-null pointer value
-                    Some(ptr::read(mem::transmute(1u)))
+                    Some(ptr::read(EMPTY as *mut T))
                 } else {
                     self.end = self.end.offset(-1);
 
@@ -1860,8 +1862,8 @@ struct PartialVecNonZeroSized<T,U> {
 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
 /// are destructed.
 struct PartialVecZeroSized<T,U> {
-    num_t: uint,
-    num_u: uint,
+    num_t: usize,
+    num_u: usize,
     marker_t: InvariantType<T>,
     marker_u: InvariantType<U>,
 }
@@ -1918,7 +1920,7 @@ mod tests {
     use super::as_vec;
 
     struct DropCounter<'a> {
-        count: &'a mut int
+        count: &'a mut u32
     }
 
     #[unsafe_destructor]
@@ -1931,7 +1933,7 @@ fn drop(&mut self) {
     #[test]
     fn test_as_vec() {
         let xs = [1u8, 2u8, 3u8];
-        assert_eq!(as_vec(&xs).as_slice(), xs);
+        assert_eq!(&**as_vec(&xs), xs);
     }
 
     #[test]
@@ -1947,7 +1949,7 @@ fn test_as_vec_dtor() {
 
     #[test]
     fn test_small_vec_struct() {
-        assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
+        assert!(size_of::<Vec<u8>>() == size_of::<usize>() * 3);
     }
 
     #[test]
@@ -2018,7 +2020,7 @@ fn test_extend() {
 
     #[test]
     fn test_slice_from_mut() {
-        let mut values = vec![1u8,2,3,4,5];
+        let mut values = vec![1, 2, 3, 4, 5];
         {
             let slice = &mut values[2 ..];
             assert!(slice == [3, 4, 5]);
@@ -2032,7 +2034,7 @@ fn test_slice_from_mut() {
 
     #[test]
     fn test_slice_to_mut() {
-        let mut values = vec![1u8,2,3,4,5];
+        let mut values = vec![1, 2, 3, 4, 5];
         {
             let slice = &mut values[.. 2];
             assert!(slice == [1, 2]);
@@ -2046,7 +2048,7 @@ fn test_slice_to_mut() {
 
     #[test]
     fn test_split_at_mut() {
-        let mut values = vec![1u8,2,3,4,5];
+        let mut values = vec![1, 2, 3, 4, 5];
         {
             let (left, right) = values.split_at_mut(2);
             {
@@ -2066,12 +2068,12 @@ fn test_split_at_mut() {
             }
         }
 
-        assert!(values == vec![2u8, 3, 5, 6, 7]);
+        assert!(values == vec![2, 3, 5, 6, 7]);
     }
 
     #[test]
     fn test_clone() {
-        let v: Vec<int> = vec!();
+        let v: Vec<i32> = vec![];
         let w = vec!(1, 2, 3);
 
         assert_eq!(v, v.clone());
@@ -2106,9 +2108,9 @@ fn test_clone_from() {
 
     #[test]
     fn test_retain() {
-        let mut vec = vec![1u, 2, 3, 4];
+        let mut vec = vec![1, 2, 3, 4];
         vec.retain(|&x| x % 2 == 0);
-        assert!(vec == vec![2u, 4]);
+        assert!(vec == vec![2, 4]);
     }
 
     #[test]
@@ -2144,10 +2146,10 @@ fn zero_sized_values() {
 
     #[test]
     fn test_partition() {
-        assert_eq!(vec![].into_iter().partition(|x: &int| *x < 3), (vec![], vec![]));
-        assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
-        assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
-        assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
+        assert_eq!(vec![].into_iter().partition(|x: &i32| *x < 3), (vec![], vec![]));
+        assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 4), (vec![1, 2, 3], vec![]));
+        assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 2), (vec![1], vec![2, 3]));
+        assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 0), (vec![], vec![1, 2, 3]));
     }
 
     #[test]
@@ -2167,21 +2169,21 @@ fn test_unsafe_ptrs() {
             // Test on-stack copy-from-buf.
             let a = [1, 2, 3];
             let ptr = a.as_ptr();
-            let b = Vec::from_raw_buf(ptr, 3u);
+            let b = Vec::from_raw_buf(ptr, 3);
             assert_eq!(b, vec![1, 2, 3]);
 
             // Test on-heap copy-from-buf.
             let c = vec![1, 2, 3, 4, 5];
             let ptr = c.as_ptr();
-            let d = Vec::from_raw_buf(ptr, 5u);
+            let d = Vec::from_raw_buf(ptr, 5);
             assert_eq!(d, vec![1, 2, 3, 4, 5]);
         }
     }
 
     #[test]
     fn test_vec_truncate_drop() {
-        static mut drops: uint = 0;
-        struct Elem(int);
+        static mut drops: u32 = 0;
+        struct Elem(i32);
         impl Drop for Elem {
             fn drop(&mut self) {
                 unsafe { drops += 1; }
@@ -2199,7 +2201,7 @@ fn drop(&mut self) {
     #[test]
     #[should_fail]
     fn test_vec_truncate_fail() {
-        struct BadElem(int);
+        struct BadElem(i32);
         impl Drop for BadElem {
             fn drop(&mut self) {
                 let BadElem(ref mut x) = *self;
@@ -2215,62 +2217,62 @@ fn drop(&mut self) {
 
     #[test]
     fn test_index() {
-        let vec = vec!(1, 2, 3);
+        let vec = vec![1, 2, 3];
         assert!(vec[1] == 2);
     }
 
     #[test]
     #[should_fail]
     fn test_index_out_of_bounds() {
-        let vec = vec!(1, 2, 3);
+        let vec = vec![1, 2, 3];
         let _ = vec[3];
     }
 
     #[test]
     #[should_fail]
     fn test_slice_out_of_bounds_1() {
-        let x: Vec<int> = vec![1, 2, 3, 4, 5];
+        let x = vec![1, 2, 3, 4, 5];
         &x[-1..];
     }
 
     #[test]
     #[should_fail]
     fn test_slice_out_of_bounds_2() {
-        let x: Vec<int> = vec![1, 2, 3, 4, 5];
+        let x = vec![1, 2, 3, 4, 5];
         &x[..6];
     }
 
     #[test]
     #[should_fail]
     fn test_slice_out_of_bounds_3() {
-        let x: Vec<int> = vec![1, 2, 3, 4, 5];
+        let x = vec![1, 2, 3, 4, 5];
         &x[-1..4];
     }
 
     #[test]
     #[should_fail]
     fn test_slice_out_of_bounds_4() {
-        let x: Vec<int> = vec![1, 2, 3, 4, 5];
+        let x = vec![1, 2, 3, 4, 5];
         &x[1..6];
     }
 
     #[test]
     #[should_fail]
     fn test_slice_out_of_bounds_5() {
-        let x: Vec<int> = vec![1, 2, 3, 4, 5];
+        let x = vec![1, 2, 3, 4, 5];
         &x[3..2];
     }
 
     #[test]
     #[should_fail]
     fn test_swap_remove_empty() {
-        let mut vec: Vec<uint> = vec!();
+        let mut vec= Vec::<i32>::new();
         vec.swap_remove(0);
     }
 
     #[test]
     fn test_move_iter_unwrap() {
-        let mut vec: Vec<uint> = Vec::with_capacity(7);
+        let mut vec = Vec::with_capacity(7);
         vec.push(1);
         vec.push(2);
         let ptr = vec.as_ptr();
@@ -2283,14 +2285,14 @@ fn test_move_iter_unwrap() {
     #[test]
     #[should_fail]
     fn test_map_in_place_incompatible_types_fail() {
-        let v = vec![0u, 1, 2];
+        let v = vec![0, 1, 2];
         v.map_in_place(|_| ());
     }
 
     #[test]
     fn test_map_in_place() {
-        let v = vec![0u, 1, 2];
-        assert_eq!(v.map_in_place(|i: uint| i as int - 1), [-1, 0, 1]);
+        let v = vec![0, 1, 2];
+        assert_eq!(v.map_in_place(|i: u32| i as i32 - 1), [-1, 0, 1]);
     }
 
     #[test]
@@ -2316,7 +2318,7 @@ fn drop(&mut self) {
                 DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
             }
         }
-        const NUM_ELEMENTS: uint = 2;
+        const NUM_ELEMENTS: usize = 2;
         static DROP_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
 
         let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>();
@@ -2332,7 +2334,7 @@ fn drop(&mut self) {
     #[test]
     fn test_move_items() {
         let vec = vec![1, 2, 3];
-        let mut vec2 : Vec<i32> = vec![];
+        let mut vec2 = vec![];
         for i in vec {
             vec2.push(i);
         }
@@ -2342,7 +2344,7 @@ fn test_move_items() {
     #[test]
     fn test_move_items_reverse() {
         let vec = vec![1, 2, 3];
-        let mut vec2 : Vec<i32> = vec![];
+        let mut vec2 = vec![];
         for i in vec.into_iter().rev() {
             vec2.push(i);
         }
@@ -2352,7 +2354,7 @@ fn test_move_items_reverse() {
     #[test]
     fn test_move_items_zero_sized() {
         let vec = vec![(), (), ()];
-        let mut vec2 : Vec<()> = vec![];
+        let mut vec2 = vec![];
         for i in vec {
             vec2.push(i);
         }
@@ -2362,7 +2364,7 @@ fn test_move_items_zero_sized() {
     #[test]
     fn test_drain_items() {
         let mut vec = vec![1, 2, 3];
-        let mut vec2: Vec<i32> = vec![];
+        let mut vec2 = vec![];
         for i in vec.drain() {
             vec2.push(i);
         }
@@ -2373,18 +2375,18 @@ fn test_drain_items() {
     #[test]
     fn test_drain_items_reverse() {
         let mut vec = vec![1, 2, 3];
-        let mut vec2: Vec<i32> = vec![];
+        let mut vec2 = vec![];
         for i in vec.drain().rev() {
             vec2.push(i);
         }
         assert_eq!(vec, []);
-        assert_eq!(vec2, [ 3, 2, 1 ]);
+        assert_eq!(vec2, [3, 2, 1]);
     }
 
     #[test]
     fn test_drain_items_zero_sized() {
         let mut vec = vec![(), (), ()];
-        let mut vec2: Vec<()> = vec![];
+        let mut vec2 = vec![];
         for i in vec.drain() {
             vec2.push(i);
         }
@@ -2394,9 +2396,9 @@ fn test_drain_items_zero_sized() {
 
     #[test]
     fn test_into_boxed_slice() {
-        let xs = vec![1u, 2, 3];
+        let xs = vec![1, 2, 3];
         let ys = xs.into_boxed_slice();
-        assert_eq!(ys.as_slice(), [1u, 2, 3]);
+        assert_eq!(ys, [1, 2, 3]);
     }
 
     #[test]
@@ -2419,17 +2421,17 @@ fn test_split_off() {
     #[bench]
     fn bench_new(b: &mut Bencher) {
         b.iter(|| {
-            let v: Vec<uint> = Vec::new();
+            let v: Vec<u32> = Vec::new();
             assert_eq!(v.len(), 0);
             assert_eq!(v.capacity(), 0);
         })
     }
 
-    fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
+    fn do_bench_with_capacity(b: &mut Bencher, src_len: usize) {
         b.bytes = src_len as u64;
 
         b.iter(|| {
-            let v: Vec<uint> = Vec::with_capacity(src_len);
+            let v: Vec<u32> = Vec::with_capacity(src_len);
             assert_eq!(v.len(), 0);
             assert_eq!(v.capacity(), src_len);
         })
@@ -2455,7 +2457,7 @@ fn bench_with_capacity_1000(b: &mut Bencher) {
         do_bench_with_capacity(b, 1000)
     }
 
-    fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
+    fn do_bench_from_fn(b: &mut Bencher, src_len: usize) {
         b.bytes = src_len as u64;
 
         b.iter(|| {
@@ -2485,11 +2487,11 @@ fn bench_from_fn_1000(b: &mut Bencher) {
         do_bench_from_fn(b, 1000)
     }
 
-    fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
+    fn do_bench_from_elem(b: &mut Bencher, src_len: usize) {
         b.bytes = src_len as u64;
 
         b.iter(|| {
-            let dst: Vec<uint> = repeat(5).take(src_len).collect();
+            let dst: Vec<usize> = repeat(5).take(src_len).collect();
             assert_eq!(dst.len(), src_len);
             assert!(dst.iter().all(|x| *x == 5));
         })
@@ -2515,8 +2517,8 @@ fn bench_from_elem_1000(b: &mut Bencher) {
         do_bench_from_elem(b, 1000)
     }
 
-    fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
-        let src: Vec<uint> = FromIterator::from_iter(0..src_len);
+    fn do_bench_from_slice(b: &mut Bencher, src_len: usize) {
+        let src: Vec<_> = FromIterator::from_iter(0..src_len);
 
         b.bytes = src_len as u64;
 
@@ -2547,13 +2549,13 @@ fn bench_from_slice_1000(b: &mut Bencher) {
         do_bench_from_slice(b, 1000)
     }
 
-    fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
-        let src: Vec<uint> = FromIterator::from_iter(0..src_len);
+    fn do_bench_from_iter(b: &mut Bencher, src_len: usize) {
+        let src: Vec<_> = FromIterator::from_iter(0..src_len);
 
         b.bytes = src_len as u64;
 
         b.iter(|| {
-            let dst: Vec<uint> = FromIterator::from_iter(src.clone().into_iter());
+            let dst: Vec<_> = FromIterator::from_iter(src.clone().into_iter());
             assert_eq!(dst.len(), src_len);
             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
         });
@@ -2579,9 +2581,9 @@ fn bench_from_iter_1000(b: &mut Bencher) {
         do_bench_from_iter(b, 1000)
     }
 
-    fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
-        let dst: Vec<uint> = FromIterator::from_iter(0..dst_len);
-        let src: Vec<uint> = FromIterator::from_iter(dst_len..dst_len + src_len);
+    fn do_bench_extend(b: &mut Bencher, dst_len: usize, src_len: usize) {
+        let dst: Vec<_> = FromIterator::from_iter(0..dst_len);
+        let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len);
 
         b.bytes = src_len as u64;
 
@@ -2628,15 +2630,15 @@ fn bench_extend_1000_1000(b: &mut Bencher) {
         do_bench_extend(b, 1000, 1000)
     }
 
-    fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
-        let dst: Vec<uint> = FromIterator::from_iter(0..dst_len);
-        let src: Vec<uint> = FromIterator::from_iter(dst_len..dst_len + src_len);
+    fn do_bench_push_all(b: &mut Bencher, dst_len: usize, src_len: usize) {
+        let dst: Vec<_> = FromIterator::from_iter(0..dst_len);
+        let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len);
 
         b.bytes = src_len as u64;
 
         b.iter(|| {
             let mut dst = dst.clone();
-            dst.push_all(src.as_slice());
+            dst.push_all(&src);
             assert_eq!(dst.len(), dst_len + src_len);
             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
         });
@@ -2677,9 +2679,9 @@ fn bench_push_all_1000_1000(b: &mut Bencher) {
         do_bench_push_all(b, 1000, 1000)
     }
 
-    fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
-        let dst: Vec<uint> = FromIterator::from_iter(0u..dst_len);
-        let src: Vec<uint> = FromIterator::from_iter(dst_len..dst_len + src_len);
+    fn do_bench_push_all_move(b: &mut Bencher, dst_len: usize, src_len: usize) {
+        let dst: Vec<_> = FromIterator::from_iter(0..dst_len);
+        let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len);
 
         b.bytes = src_len as u64;
 
@@ -2726,8 +2728,8 @@ fn bench_push_all_move_1000_1000(b: &mut Bencher) {
         do_bench_push_all_move(b, 1000, 1000)
     }
 
-    fn do_bench_clone(b: &mut Bencher, src_len: uint) {
-        let src: Vec<uint> = FromIterator::from_iter(0..src_len);
+    fn do_bench_clone(b: &mut Bencher, src_len: usize) {
+        let src: Vec<usize> = FromIterator::from_iter(0..src_len);
 
         b.bytes = src_len as u64;
 
@@ -2758,9 +2760,9 @@ fn bench_clone_1000(b: &mut Bencher) {
         do_bench_clone(b, 1000)
     }
 
-    fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
-        let dst: Vec<uint> = FromIterator::from_iter(0..src_len);
-        let src: Vec<uint> = FromIterator::from_iter(dst_len..dst_len + src_len);
+    fn do_bench_clone_from(b: &mut Bencher, times: usize, dst_len: usize, src_len: usize) {
+        let dst: Vec<_> = FromIterator::from_iter(0..src_len);
+        let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len);
 
         b.bytes = (times * src_len) as u64;
 
index abcf358a1926c00baee9db9d8f8d8042da941603..739b8d8ce19c24899abcd9d06f2a25d62d848623 100644 (file)
@@ -13,7 +13,7 @@
 
 #![allow(missing_docs)]
 
-pub use self::Entry::*;
+use self::Entry::*;
 
 use core::prelude::*;
 
@@ -29,8 +29,6 @@
 use {vec, slice};
 use vec::Vec;
 
-// FIXME(conventions): capacity management???
-
 /// A map optimized for small integer keys.
 ///
 /// # Examples
@@ -117,7 +115,7 @@ impl<S: Writer + Hasher, V: Hash<S>> Hash<S> for VecMap<V> {
     fn hash(&self, state: &mut S) {
         // In order to not traverse the `VecMap` twice, count the elements
         // during iteration.
-        let mut count: uint = 0;
+        let mut count: usize = 0;
         for elt in self {
             elt.hash(state);
             count += 1;
@@ -148,7 +146,7 @@ pub fn new() -> VecMap<V> { VecMap { v: vec![] } }
     /// let mut map: VecMap<&str> = VecMap::with_capacity(10);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(capacity: uint) -> VecMap<V> {
+    pub fn with_capacity(capacity: usize) -> VecMap<V> {
         VecMap { v: Vec::with_capacity(capacity) }
     }
 
@@ -164,7 +162,7 @@ pub fn with_capacity(capacity: uint) -> VecMap<V> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint {
+    pub fn capacity(&self) -> usize {
         self.v.capacity()
     }
 
@@ -183,7 +181,7 @@ pub fn capacity(&self) -> uint {
     /// assert!(map.capacity() >= 10);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_len(&mut self, len: uint) {
+    pub fn reserve_len(&mut self, len: usize) {
         let cur_len = self.v.len();
         if len >= cur_len {
             self.v.reserve(len - cur_len);
@@ -207,7 +205,7 @@ pub fn reserve_len(&mut self, len: uint) {
     /// assert!(map.capacity() >= 10);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve_len_exact(&mut self, len: uint) {
+    pub fn reserve_len_exact(&mut self, len: usize) {
         let cur_len = self.v.len();
         if len >= cur_len {
             self.v.reserve_exact(len - cur_len);
@@ -215,11 +213,11 @@ pub fn reserve_len_exact(&mut self, len: uint) {
     }
 
     /// Returns an iterator visiting all keys in ascending order of the keys.
-    /// The iterator's element type is `uint`.
+    /// The iterator's element type is `usize`.
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn keys<'r>(&'r self) -> Keys<'r, V> {
         fn first<A, B>((a, _): (A, B)) -> A { a }
-        let first: fn((uint, &'r V)) -> uint = first; // coerce to fn pointer
+        let first: fn((usize, &'r V)) -> usize = first; // coerce to fn pointer
 
         Keys { iter: self.iter().map(first) }
     }
@@ -229,13 +227,13 @@ fn first<A, B>((a, _): (A, B)) -> A { a }
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn values<'r>(&'r self) -> Values<'r, V> {
         fn second<A, B>((_, b): (A, B)) -> B { b }
-        let second: fn((uint, &'r V)) -> &'r V = second; // coerce to fn pointer
+        let second: fn((usize, &'r V)) -> &'r V = second; // coerce to fn pointer
 
         Values { iter: self.iter().map(second) }
     }
 
     /// Returns an iterator visiting all key-value pairs in ascending order of the keys.
-    /// The iterator's element type is `(uint, &'r V)`.
+    /// The iterator's element type is `(usize, &'r V)`.
     ///
     /// # Examples
     ///
@@ -263,7 +261,7 @@ pub fn iter<'r>(&'r self) -> Iter<'r, V> {
 
     /// Returns an iterator visiting all key-value pairs in ascending order of the keys,
     /// with mutable references to the values.
-    /// The iterator's element type is `(uint, &'r mut V)`.
+    /// The iterator's element type is `(usize, &'r mut V)`.
     ///
     /// # Examples
     ///
@@ -294,7 +292,7 @@ pub fn iter_mut<'r>(&'r mut self) -> IterMut<'r, V> {
 
     /// Returns an iterator visiting all key-value pairs in ascending order of
     /// the keys, consuming the original `VecMap`.
-    /// The iterator's element type is `(uint, &'r V)`.
+    /// The iterator's element type is `(usize, &'r V)`.
     ///
     /// # Examples
     ///
@@ -306,23 +304,23 @@ pub fn iter_mut<'r>(&'r mut self) -> IterMut<'r, V> {
     /// map.insert(3, "c");
     /// map.insert(2, "b");
     ///
-    /// let vec: Vec<(uint, &str)> = map.into_iter().collect();
+    /// let vec: Vec<(usize, &str)> = map.into_iter().collect();
     ///
     /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn into_iter(self) -> IntoIter<V> {
-        fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
+        fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
             v.map(|v| (i, v))
         }
-        let filter: fn((uint, Option<V>)) -> Option<(uint, V)> = filter; // coerce to fn ptr
+        let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr
 
         IntoIter { iter: self.v.into_iter().enumerate().filter_map(filter) }
     }
 
     /// Returns an iterator visiting all key-value pairs in ascending order of
     /// the keys, emptying (but not consuming) the original `VecMap`.
-    /// The iterator's element type is `(uint, &'r V)`. Keeps the allocated memory for reuse.
+    /// The iterator's element type is `(usize, &'r V)`. Keeps the allocated memory for reuse.
     ///
     /// # Examples
     ///
@@ -334,17 +332,17 @@ fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
     /// map.insert(3, "c");
     /// map.insert(2, "b");
     ///
-    /// let vec: Vec<(uint, &str)> = map.drain().collect();
+    /// let vec: Vec<(usize, &str)> = map.drain().collect();
     ///
     /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
     /// ```
     #[unstable(feature = "collections",
                reason = "matches collection reform specification, waiting for dust to settle")]
     pub fn drain<'a>(&'a mut self) -> Drain<'a, V> {
-        fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
+        fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
             v.map(|v| (i, v))
         }
-        let filter: fn((uint, Option<V>)) -> Option<(uint, V)> = filter; // coerce to fn ptr
+        let filter: fn((usize, Option<V>)) -> Option<(usize, V)> = filter; // coerce to fn ptr
 
         Drain { iter: self.v.drain().enumerate().filter_map(filter) }
     }
@@ -362,7 +360,7 @@ fn filter<A>((i, v): (uint, Option<A>)) -> Option<(uint, A)> {
     /// assert_eq!(a.len(), 1);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint {
+    pub fn len(&self) -> usize {
         self.v.iter().filter(|elt| elt.is_some()).count()
     }
 
@@ -411,7 +409,7 @@ pub fn clear(&mut self) { self.v.clear() }
     /// assert_eq!(map.get(&2), None);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get(&self, key: &uint) -> Option<&V> {
+    pub fn get(&self, key: &usize) -> Option<&V> {
         if *key < self.v.len() {
             match self.v[*key] {
               Some(ref value) => Some(value),
@@ -436,7 +434,7 @@ pub fn get(&self, key: &uint) -> Option<&V> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn contains_key(&self, key: &uint) -> bool {
+    pub fn contains_key(&self, key: &usize) -> bool {
         self.get(key).is_some()
     }
 
@@ -456,7 +454,7 @@ pub fn contains_key(&self, key: &uint) -> bool {
     /// assert_eq!(map[1], "b");
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get_mut(&mut self, key: &uint) -> Option<&mut V> {
+    pub fn get_mut(&mut self, key: &usize) -> Option<&mut V> {
         if *key < self.v.len() {
             match *(&mut self.v[*key]) {
               Some(ref mut value) => Some(value),
@@ -484,7 +482,7 @@ pub fn get_mut(&mut self, key: &uint) -> Option<&mut V> {
     /// assert_eq!(map[37], "c");
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn insert(&mut self, key: uint, value: V) -> Option<V> {
+    pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
         let len = self.v.len();
         if len <= key {
             self.v.extend((0..key - len + 1).map(|_| None));
@@ -506,7 +504,7 @@ pub fn insert(&mut self, key: uint, value: V) -> Option<V> {
     /// assert_eq!(map.remove(&1), None);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn remove(&mut self, key: &uint) -> Option<V> {
+    pub fn remove(&mut self, key: &usize) -> Option<V> {
         if *key >= self.v.len() {
             return None;
         }
@@ -539,8 +537,7 @@ pub fn remove(&mut self, key: &uint) -> Option<V> {
     ///
     /// assert_eq!(count[1], 3);
     /// ```
-    #[unstable(feature = "collections",
-               reason = "precise API still under development")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn entry(&mut self, key: usize) -> Entry<V> {
         // FIXME(Gankro): this is basically the dumbest implementation of
         // entry possible, because weird non-lexical borrows issues make it
@@ -576,8 +573,7 @@ pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, V>> {
 impl<'a, V> VacantEntry<'a, V> {
     /// Sets the value of the entry with the VacantEntry's key,
     /// and returns a mutable reference to it.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn insert(self, value: V) -> &'a mut V {
         let index = self.index;
         self.map.insert(index, value);
@@ -587,24 +583,21 @@ pub fn insert(self, value: V) -> &'a mut V {
 
 impl<'a, V> OccupiedEntry<'a, V> {
     /// Gets a reference to the value in the entry.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn get(&self) -> &V {
         let index = self.index;
         &self.map[index]
     }
 
     /// Gets a mutable reference to the value in the entry.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn get_mut(&mut self) -> &mut V {
         let index = self.index;
         &mut self.map[index]
     }
 
     /// Converts the entry into a mutable reference to its value.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn into_mut(self) -> &'a mut V {
         let index = self.index;
         &mut self.map[index]
@@ -612,16 +605,14 @@ pub fn into_mut(self) -> &'a mut V {
 
     /// Sets the value of the entry with the OccupiedEntry's key,
     /// and returns the entry's old value.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn insert(&mut self, value: V) -> V {
         let index = self.index;
         self.map.insert(index, value).unwrap()
     }
 
     /// Takes the value of the entry out of the map, and returns it.
-    #[unstable(feature = "collections",
-               reason = "matches collection reform v2 specification, waiting for dust to settle")]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn remove(self) -> V {
         let index = self.index;
         self.map.remove(&index).unwrap()
@@ -669,8 +660,8 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<V> FromIterator<(uint, V)> for VecMap<V> {
-    fn from_iter<Iter: Iterator<Item=(uint, V)>>(iter: Iter) -> VecMap<V> {
+impl<V> FromIterator<(usize, V)> for VecMap<V> {
+    fn from_iter<Iter: Iterator<Item=(usize, V)>>(iter: Iter) -> VecMap<V> {
         let mut map = VecMap::new();
         map.extend(iter);
         map
@@ -702,29 +693,27 @@ fn into_iter(mut self) -> IterMut<'a, T> {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<V> Extend<(uint, V)> for VecMap<V> {
-    fn extend<Iter: Iterator<Item=(uint, V)>>(&mut self, iter: Iter) {
+impl<V> Extend<(usize, V)> for VecMap<V> {
+    fn extend<Iter: Iterator<Item=(usize, V)>>(&mut self, iter: Iter) {
         for (k, v) in iter {
             self.insert(k, v);
         }
     }
 }
 
-impl<V> Index<uint> for VecMap<V> {
+impl<V> Index<usize> for VecMap<V> {
     type Output = V;
 
     #[inline]
-    fn index<'a>(&'a self, i: &uint) -> &'a V {
+    fn index<'a>(&'a self, i: &usize) -> &'a V {
         self.get(i).expect("key not present")
     }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<V> IndexMut<uint> for VecMap<V> {
-    type Output = V;
-
+impl<V> IndexMut<usize> for VecMap<V> {
     #[inline]
-    fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
+    fn index_mut<'a>(&'a mut self, i: &usize) -> &'a mut V {
         self.get_mut(i).expect("key not present")
     }
 }
@@ -757,7 +746,7 @@ fn next(&mut self) -> Option<$elem> {
             }
 
             #[inline]
-            fn size_hint(&self) -> (uint, Option<uint>) {
+            fn size_hint(&self) -> (usize, Option<usize>) {
                 (0, Some(self.back - self.front))
             }
         }
@@ -794,8 +783,8 @@ fn next_back(&mut self) -> Option<$elem> {
 /// An iterator over the key-value pairs of a map.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Iter<'a, V:'a> {
-    front: uint,
-    back: uint,
+    front: usize,
+    back: usize,
     iter: slice::Iter<'a, Option<V>>
 }
 
@@ -810,25 +799,25 @@ fn clone(&self) -> Iter<'a, V> {
     }
 }
 
-iterator! { impl Iter -> (uint, &'a V), as_ref }
-double_ended_iterator! { impl Iter -> (uint, &'a V), as_ref }
+iterator! { impl Iter -> (usize, &'a V), as_ref }
+double_ended_iterator! { impl Iter -> (usize, &'a V), as_ref }
 
 /// An iterator over the key-value pairs of a map, with the
 /// values being mutable.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct IterMut<'a, V:'a> {
-    front: uint,
-    back: uint,
+    front: usize,
+    back: usize,
     iter: slice::IterMut<'a, Option<V>>
 }
 
-iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
-double_ended_iterator! { impl IterMut -> (uint, &'a mut V), as_mut }
+iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
+double_ended_iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
 
 /// An iterator over the keys of a map.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Keys<'a, V: 'a> {
-    iter: Map<Iter<'a, V>, fn((uint, &'a V)) -> uint>
+    iter: Map<Iter<'a, V>, fn((usize, &'a V)) -> usize>
 }
 
 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
@@ -843,7 +832,7 @@ fn clone(&self) -> Keys<'a, V> {
 /// An iterator over the values of a map.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Values<'a, V: 'a> {
-    iter: Map<Iter<'a, V>, fn((uint, &'a V)) -> &'a V>
+    iter: Map<Iter<'a, V>, fn((usize, &'a V)) -> &'a V>
 }
 
 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
@@ -860,39 +849,39 @@ fn clone(&self) -> Values<'a, V> {
 pub struct IntoIter<V> {
     iter: FilterMap<
     Enumerate<vec::IntoIter<Option<V>>>,
-    fn((uint, Option<V>)) -> Option<(uint, V)>>
+    fn((usize, Option<V>)) -> Option<(usize, V)>>
 }
 
 #[unstable(feature = "collections")]
 pub struct Drain<'a, V> {
     iter: FilterMap<
     Enumerate<vec::Drain<'a, Option<V>>>,
-    fn((uint, Option<V>)) -> Option<(uint, V)>>
+    fn((usize, Option<V>)) -> Option<(usize, V)>>
 }
 
 #[unstable(feature = "collections")]
 impl<'a, V> Iterator for Drain<'a, V> {
-    type Item = (uint, V);
+    type Item = (usize, V);
 
-    fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 
 #[unstable(feature = "collections")]
 impl<'a, V> DoubleEndedIterator for Drain<'a, V> {
-    fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
+    fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, V> Iterator for Keys<'a, V> {
-    type Item = uint;
+    type Item = usize;
 
-    fn next(&mut self) -> Option<uint> { self.iter.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn next(&mut self) -> Option<usize> { self.iter.next() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
-    fn next_back(&mut self) -> Option<uint> { self.iter.next_back() }
+    fn next_back(&mut self) -> Option<usize> { self.iter.next_back() }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -900,7 +889,7 @@ impl<'a, V> Iterator for Values<'a, V> {
     type Item = &'a V;
 
     fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, V> DoubleEndedIterator for Values<'a, V> {
@@ -909,14 +898,14 @@ fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<V> Iterator for IntoIter<V> {
-    type Item = (uint, V);
+    type Item = (usize, V);
 
-    fn next(&mut self) -> Option<(uint, V)> { self.iter.next() }
-    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
+    fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
+    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<V> DoubleEndedIterator for IntoIter<V> {
-    fn next_back(&mut self) -> Option<(uint, V)> { self.iter.next_back() }
+    fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
 }
 
 #[cfg(test)]
@@ -924,7 +913,8 @@ mod test_map {
     use prelude::*;
     use core::hash::{hash, SipHasher};
 
-    use super::{VecMap, Occupied, Vacant};
+    use super::VecMap;
+    use super::Entry::{Occupied, Vacant};
 
     #[test]
     fn test_get_mut() {
@@ -990,7 +980,7 @@ fn test_keys() {
         map.insert(1, 'a');
         map.insert(2, 'b');
         map.insert(3, 'c');
-        let keys = map.keys().collect::<Vec<uint>>();
+        let keys: Vec<_> = map.keys().collect();
         assert_eq!(keys.len(), 3);
         assert!(keys.contains(&1));
         assert!(keys.contains(&2));
@@ -1003,7 +993,7 @@ fn test_values() {
         map.insert(1, 'a');
         map.insert(2, 'b');
         map.insert(3, 'c');
-        let values = map.values().map(|&v| v).collect::<Vec<char>>();
+        let values: Vec<_> = map.values().cloned().collect();
         assert_eq!(values.len(), 3);
         assert!(values.contains(&'a'));
         assert!(values.contains(&'b'));
@@ -1062,7 +1052,7 @@ fn test_mut_iterator() {
         assert!(m.insert(10, 11).is_none());
 
         for (k, v) in &mut m {
-            *v += k as int;
+            *v += k as isize;
         }
 
         let mut it = m.iter();
@@ -1104,7 +1094,7 @@ fn test_mut_rev_iterator() {
         assert!(m.insert(10, 11).is_none());
 
         for (k, v) in m.iter_mut().rev() {
-            *v += k as int;
+            *v += k as isize;
         }
 
         let mut it = m.iter();
@@ -1137,7 +1127,7 @@ fn test_drain_iterator() {
         map.insert(3, "c");
         map.insert(2, "b");
 
-        let vec: Vec<(usize, &str)> = map.drain().collect();
+        let vec: Vec<_> = map.drain().collect();
 
         assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
         assert_eq!(map.len(), 0);
@@ -1146,7 +1136,7 @@ fn test_drain_iterator() {
     #[test]
     fn test_show() {
         let mut map = VecMap::new();
-        let empty = VecMap::<int>::new();
+        let empty = VecMap::<i32>::new();
 
         map.insert(1, 2);
         map.insert(3, 4);
@@ -1195,7 +1185,7 @@ fn test_lt() {
         let mut b = VecMap::new();
 
         assert!(!(a < b) && !(b < a));
-        assert!(b.insert(2u, 5).is_none());
+        assert!(b.insert(2, 5).is_none());
         assert!(a < b);
         assert!(a.insert(2, 7).is_none());
         assert!(!(a < b) && b < a);
@@ -1213,7 +1203,7 @@ fn test_ord() {
         let mut b = VecMap::new();
 
         assert!(a <= b && a >= b);
-        assert!(a.insert(1u, 1).is_none());
+        assert!(a.insert(1, 1).is_none());
         assert!(a > b && a >= b);
         assert!(b < a && b <= a);
         assert!(b.insert(2, 2).is_none());
@@ -1245,9 +1235,9 @@ fn test_hash() {
 
     #[test]
     fn test_from_iter() {
-        let xs: Vec<(uint, char)> = vec![(1u, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
+        let xs = vec![(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')];
 
-        let map: VecMap<char> = xs.iter().map(|&x| x).collect();
+        let map: VecMap<_> = xs.iter().cloned().collect();
 
         for &(k, v) in &xs {
             assert_eq!(map.get(&k), Some(&v));
@@ -1256,7 +1246,7 @@ fn test_from_iter() {
 
     #[test]
     fn test_index() {
-        let mut map: VecMap<int> = VecMap::new();
+        let mut map = VecMap::new();
 
         map.insert(1, 2);
         map.insert(2, 1);
@@ -1268,7 +1258,7 @@ fn test_index() {
     #[test]
     #[should_fail]
     fn test_index_nonexistent() {
-        let mut map: VecMap<int> = VecMap::new();
+        let mut map = VecMap::new();
 
         map.insert(1, 2);
         map.insert(2, 1);
@@ -1281,7 +1271,7 @@ fn test_index_nonexistent() {
     fn test_entry(){
         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
 
-        let mut map: VecMap<i32> = xs.iter().map(|&x| x).collect();
+        let mut map: VecMap<_> = xs.iter().cloned().collect();
 
         // Existing key (insert)
         match map.entry(1) {
@@ -1337,7 +1327,7 @@ mod bench {
 
     #[bench]
     pub fn insert_rand_100(b: &mut Bencher) {
-        let mut m : VecMap<uint> = VecMap::new();
+        let mut m = VecMap::new();
         insert_rand_n(100, &mut m, b,
                       |m, i| { m.insert(i, 1); },
                       |m, i| { m.remove(&i); });
@@ -1345,7 +1335,7 @@ pub fn insert_rand_100(b: &mut Bencher) {
 
     #[bench]
     pub fn insert_rand_10_000(b: &mut Bencher) {
-        let mut m : VecMap<uint> = VecMap::new();
+        let mut m = VecMap::new();
         insert_rand_n(10_000, &mut m, b,
                       |m, i| { m.insert(i, 1); },
                       |m, i| { m.remove(&i); });
@@ -1354,7 +1344,7 @@ pub fn insert_rand_10_000(b: &mut Bencher) {
     // Insert seq
     #[bench]
     pub fn insert_seq_100(b: &mut Bencher) {
-        let mut m : VecMap<uint> = VecMap::new();
+        let mut m = VecMap::new();
         insert_seq_n(100, &mut m, b,
                      |m, i| { m.insert(i, 1); },
                      |m, i| { m.remove(&i); });
@@ -1362,7 +1352,7 @@ pub fn insert_seq_100(b: &mut Bencher) {
 
     #[bench]
     pub fn insert_seq_10_000(b: &mut Bencher) {
-        let mut m : VecMap<uint> = VecMap::new();
+        let mut m = VecMap::new();
         insert_seq_n(10_000, &mut m, b,
                      |m, i| { m.insert(i, 1); },
                      |m, i| { m.remove(&i); });
@@ -1371,7 +1361,7 @@ pub fn insert_seq_10_000(b: &mut Bencher) {
     // Find rand
     #[bench]
     pub fn find_rand_100(b: &mut Bencher) {
-        let mut m : VecMap<uint> = VecMap::new();
+        let mut m = VecMap::new();
         find_rand_n(100, &mut m, b,
                     |m, i| { m.insert(i, 1); },
                     |m, i| { m.get(&i); });
@@ -1379,7 +1369,7 @@ pub fn find_rand_100(b: &mut Bencher) {
 
     #[bench]
     pub fn find_rand_10_000(b: &mut Bencher) {
-        let mut m : VecMap<uint> = VecMap::new();
+        let mut m = VecMap::new();
         find_rand_n(10_000, &mut m, b,
                     |m, i| { m.insert(i, 1); },
                     |m, i| { m.get(&i); });
@@ -1388,7 +1378,7 @@ pub fn find_rand_10_000(b: &mut Bencher) {
     // Find seq
     #[bench]
     pub fn find_seq_100(b: &mut Bencher) {
-        let mut m : VecMap<uint> = VecMap::new();
+        let mut m = VecMap::new();
         find_seq_n(100, &mut m, b,
                    |m, i| { m.insert(i, 1); },
                    |m, i| { m.get(&i); });
@@ -1396,7 +1386,7 @@ pub fn find_seq_100(b: &mut Bencher) {
 
     #[bench]
     pub fn find_seq_10_000(b: &mut Bencher) {
-        let mut m : VecMap<uint> = VecMap::new();
+        let mut m = VecMap::new();
         find_seq_n(10_000, &mut m, b,
                    |m, i| { m.insert(i, 1); },
                    |m, i| { m.get(&i); });
index 0f444ef186f9abe37ec960601b91a334c3cc74d0..182851002d9426bc35d49a3dd7ae2e42231e4d59 100644 (file)
@@ -23,7 +23,7 @@
 //!
 //! use std::finally::Finally;
 //!
-//! (|&mut:| {
+//! (|| {
 //!     // ...
 //! }).finally(|| {
 //!     // this code is always run
index 0963afaf72e21009c2a372fe97de5756153b11e2..25bb959b9b3aa9db02d12d0dbc894c151077555f 100644 (file)
@@ -225,10 +225,10 @@ pub fn float_to_str_bytes_common<T: Float, U, F>(
         // cut off the one extra digit, and depending on its value
         // round the remaining ones.
         if limit_digits && dig == digit_count {
-            let ascii2value = |&: chr: u8| {
+            let ascii2value = |chr: u8| {
                 (chr as char).to_digit(radix).unwrap()
             };
-            let value2ascii = |&: val: uint| {
+            let value2ascii = |val: uint| {
                 char::from_digit(val, radix).unwrap() as u8
             };
 
index 60262857765e26854a24012b825df22eb3f06ae9..0357b723b3c7aa29af0f9ff43ae9b4cf519d309a 100644 (file)
@@ -483,7 +483,7 @@ pub fn pad_integral(&mut self,
         }
 
         // Writes the sign if it exists, and then the prefix if it was requested
-        let write_prefix = |&: f: &mut Formatter| {
+        let write_prefix = |f: &mut Formatter| {
             if let Some(c) = sign {
                 let mut b = [0; 4];
                 let n = c.encode_utf8(&mut b).unwrap_or(0);
index d73e6ed589ff3bed1455121de3cc80a76ee8062e..a5d2618eff948959e881f655beaa839d75b4536d 100644 (file)
@@ -123,7 +123,7 @@ fn hash(&self, state: &mut S) {
                 let a: [u8; ::$ty::BYTES] = unsafe {
                     mem::transmute((*self as $uty).to_le() as $ty)
                 };
-                state.write(a.as_slice())
+                state.write(&a)
             }
         }
     }
index bef196d48246040ebef25f1d7688ae907a58eff0..d405d0d28beb3636fbac2387771a037a4f9f02cf 100644 (file)
@@ -30,7 +30,6 @@
 /// strong, this implementation has not been reviewed for such purposes.
 /// As such, all cryptographic uses of this implementation are strongly
 /// discouraged.
-#[allow(missing_copy_implementations)]
 pub struct SipHasher {
     k0: u64,
     k1: u64,
index 23157072d536b554e14e47d01207755a4120665b..5df64cfaadaaab243b41d17ba90fc4fa19eea810 100644 (file)
@@ -67,7 +67,7 @@
 use ops::{Add, Deref, FnMut};
 use option::Option;
 use option::Option::{Some, None};
-use std::marker::Sized;
+use marker::Sized;
 use usize;
 
 /// An interface for dealing with "external iterators". These types of iterators
@@ -260,7 +260,7 @@ fn map<B, F>(self, f: F) -> Map<Self, F> where
     }
 
     /// Creates an iterator that applies the predicate to each element returned
-    /// by this iterator. The only elements that will be yieled are those that
+    /// by this iterator. The only elements that will be yielded are those that
     /// make the predicate evaluate to `true`.
     ///
     /// # Examples
index 5e9793f270dedea1d37d6b2b565dab1b8b645dae..df4942b509b4c347440e6d57c7dad56422b817cf 100644 (file)
@@ -56,6 +56,7 @@
        html_root_url = "http://doc.rust-lang.org/nightly/",
        html_playground_url = "http://play.rust-lang.org/")]
 
+#![feature(no_std)]
 #![no_std]
 #![allow(raw_pointer_derive)]
 #![deny(missing_docs)]
 mod core {
     pub use panicking;
     pub use fmt;
+    #[cfg(not(stage0))] pub use clone;
+    #[cfg(not(stage0))] pub use cmp;
+    #[cfg(not(stage0))] pub use hash;
+    #[cfg(not(stage0))] pub use marker;
+    #[cfg(not(stage0))] pub use option;
+    #[cfg(not(stage0))] pub use iter;
 }
 
 #[doc(hidden)]
 mod std {
-    pub use clone;
-    pub use cmp;
-    pub use fmt;
-    pub use hash;
-    pub use marker;
+    // NOTE: remove after next snapshot
+    #[cfg(stage0)] pub use clone;
+    #[cfg(stage0)] pub use cmp;
+    #[cfg(stage0)] pub use hash;
+    #[cfg(stage0)] pub use marker;
+    #[cfg(stage0)] pub use option;
+    #[cfg(stage0)] pub use fmt;
+    #[cfg(stage0)] pub use iter;
+
+    // range syntax
     pub use ops;
-    pub use option;
-    // for-loops
-    pub use iter;
 }
index 299cdbda3cc7481a3087d625cb807fb0eef4e212..bf9e6bccc71a2562422786a70ea385c0050a4e4a 100644 (file)
@@ -311,16 +311,17 @@ fn clone(&self) -> ContravariantType<T> { *self }
 ///
 /// # Example
 ///
-/// The Cell type is an example which uses unsafe code to achieve
-/// "interior" mutability:
+/// The Cell type is an example of an `InvariantType` which uses unsafe
+/// code to achieve "interior" mutability:
 ///
 /// ```
 /// struct Cell<T> { value: T }
 /// ```
 ///
-/// The type system would infer that `value` is only read here and
-/// never written, but in fact `Cell` uses unsafe code to achieve
-/// interior mutability.
+/// The type system would infer that `value` is only read here
+/// and never written, but in fact `Cell` uses unsafe code to achieve
+/// interior mutability. In order to get correct behavior, the
+/// `InvariantType` marker must be applied.
 #[unstable(feature = "core",
            reason = "likely to change with new variance strategy")]
 #[lang="invariant_type"]
@@ -396,7 +397,6 @@ fn clone(&self) -> InvariantType<T> { *self }
            reason = "likely to change with new variance strategy")]
 #[lang="no_copy_bound"]
 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
-#[allow(missing_copy_implementations)]
 pub struct NoCopy;
 
 /// A type which is considered managed by the GC. This is typically
@@ -405,5 +405,4 @@ fn clone(&self) -> InvariantType<T> { *self }
            reason = "likely to change with new variance strategy")]
 #[lang="managed_bound"]
 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
-#[allow(missing_copy_implementations)]
 pub struct Managed;
index 0d26c8e79142ae728bf071fc216143a496387841..51bf3c1648f568482abce0ad2ea1e54c6269435a 100644 (file)
@@ -331,8 +331,9 @@ pub unsafe fn copy_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,
 #[unstable(feature = "core",
            reason = "this function may be removed in the future due to its \
                      questionable utility")]
-pub unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a mut S,
-                                                            ptr: &mut T)
-                                                            -> &'a mut T {
+pub unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S,
+                                                               ptr: &mut T)
+                                                              -> &'a mut T
+{
     transmute(ptr)
 }
index 7af94c73f324d80324fdacec9a44edd95df61698..782483a34fc89744465e4f09bd47c08a4c229b49 100644 (file)
@@ -897,14 +897,14 @@ macro_rules! shr_impl_all {
 /// }
 /// ```
 #[lang="index"]
-#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Index}`"]
+#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
 #[stable(feature = "rust1", since = "1.0.0")]
-pub trait Index<Index: ?Sized> {
+pub trait Index<Idx: ?Sized> {
     type Output: ?Sized;
 
     /// The method for the indexing (`Foo[Bar]`) operation
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn index<'a>(&'a self, index: &Index) -> &'a Self::Output;
+    fn index<'a>(&'a self, index: &Idx) -> &'a Self::Output;
 }
 
 /// The `IndexMut` trait is used to specify the functionality of indexing
@@ -916,15 +916,21 @@ pub trait Index<Index: ?Sized> {
 /// calling `index_mut`, and therefore, `main` prints `Indexing!`.
 ///
 /// ```
-/// use std::ops::IndexMut;
+/// use std::ops::{Index, IndexMut};
 ///
 /// #[derive(Copy)]
 /// struct Foo;
 /// struct Bar;
 ///
-/// impl IndexMut<Bar> for Foo {
+/// impl Index<Bar> for Foo {
 ///     type Output = Foo;
 ///
+///     fn index<'a>(&'a self, _index: &Bar) -> &'a Foo {
+///         self
+///     }
+/// }
+///
+/// impl IndexMut<Bar> for Foo {
 ///     fn index_mut<'a>(&'a mut self, _index: &Bar) -> &'a mut Foo {
 ///         println!("Indexing!");
 ///         self
@@ -936,14 +942,12 @@ pub trait Index<Index: ?Sized> {
 /// }
 /// ```
 #[lang="index_mut"]
-#[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Index}`"]
+#[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
 #[stable(feature = "rust1", since = "1.0.0")]
-pub trait IndexMut<Index: ?Sized> {
-    type Output: ?Sized;
-
+pub trait IndexMut<Idx: ?Sized>: Index<Idx> {
     /// The method for the indexing (`Foo[Bar]`) operation
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn index_mut<'a>(&'a mut self, index: &Index) -> &'a mut Self::Output;
+    fn index_mut<'a>(&'a mut self, index: &Idx) -> &'a mut Self::Output;
 }
 
 /// An unbounded range.
index 9c18cd0f6d9af0cc9d3dac1c4313ba2492aaf973..ba1eae551ff2a15f9dba0fa52253c0b10b346dbd 100644 (file)
@@ -190,7 +190,7 @@ pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
     src
 }
 
-/// Reads the value from `src` without dropping it. This leaves the
+/// Reads the value from `src` without moving it. This leaves the
 /// memory in `src` unchanged.
 ///
 /// # Safety
index a750e81bf596b7fd9aeebbec55822b0146c0956d..fc51920ec6b82de1941863fbb4a48849f69d709e 100644 (file)
@@ -502,8 +502,6 @@ fn index(&self, &index: &uint) -> &T {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> ops::IndexMut<uint> for [T] {
-    type Output = T;
-
     fn index_mut(&mut self, &index: &uint) -> &mut T {
         assert!(index < self.len());
 
@@ -553,7 +551,6 @@ fn index(&self, _index: &RangeFull) -> &[T] {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> ops::IndexMut<ops::Range<uint>> for [T] {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
         assert!(index.start <= index.end);
@@ -568,7 +565,6 @@ fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> ops::IndexMut<ops::RangeTo<uint>> for [T] {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
         self.index_mut(&ops::Range{ start: 0, end: index.end })
@@ -576,7 +572,6 @@ fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
         let len = self.len();
@@ -585,7 +580,6 @@ fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T> ops::IndexMut<RangeFull> for [T] {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
         self
@@ -865,7 +859,6 @@ fn index(&self, _index: &RangeFull) -> &[T] {
 
 #[unstable(feature = "core")]
 impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
         self.index_mut(&RangeFull).index_mut(index)
@@ -873,7 +866,6 @@ fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
 }
 #[unstable(feature = "core")]
 impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
         self.index_mut(&RangeFull).index_mut(index)
@@ -881,7 +873,6 @@ fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
 }
 #[unstable(feature = "core")]
 impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
         self.index_mut(&RangeFull).index_mut(index)
@@ -889,7 +880,6 @@ fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
 }
 #[unstable(feature = "core")]
 impl<'a, T> ops::IndexMut<RangeFull> for IterMut<'a, T> {
-    type Output = [T];
     #[inline]
     fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
         make_slice!(T => &mut [T]: self.ptr, self.end)
@@ -1357,6 +1347,52 @@ pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
     }
 }
 
+/// Forms a slice from a pointer and a length.
+///
+/// The `len` argument is the number of **elements**, not the number of bytes.
+///
+/// This function is unsafe as there is no guarantee that the given pointer is
+/// valid for `len` elements, nor whether the lifetime inferred is a suitable
+/// lifetime for the returned slice.
+///
+/// # Caveat
+///
+/// The lifetime for the returned slice is inferred from its usage. To
+/// prevent accidental misuse, it's suggested to tie the lifetime to whichever
+/// source lifetime is safe in the context, such as by providing a helper
+/// function taking the lifetime of a host value for the slice, or by explicit
+/// annotation.
+///
+/// # Example
+///
+/// ```rust
+/// use std::slice;
+///
+/// // manifest a slice out of thin air!
+/// let ptr = 0x1234 as *const uint;
+/// let amt = 10;
+/// unsafe {
+///     let slice = slice::from_raw_parts(ptr, amt);
+/// }
+/// ```
+#[inline]
+#[unstable(feature = "core")]
+pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: uint) -> &'a [T] {
+    transmute(RawSlice { data: p, len: len })
+}
+
+/// Performs the same functionality as `from_raw_parts`, except that a mutable
+/// slice is returned.
+///
+/// This function is unsafe for the same reasons as `from_raw_parts`, as well
+/// as not being able to provide a non-aliasing guarantee of the returned
+/// mutable slice.
+#[inline]
+#[unstable(feature = "core")]
+pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: uint) -> &'a mut [T] {
+    transmute(RawSlice { data: p, len: len })
+}
+
 /// Forms a slice from a pointer and a length.
 ///
 /// The pointer given is actually a reference to the base of the slice. This
@@ -1383,8 +1419,9 @@ pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
 /// }
 /// ```
 #[inline]
-#[unstable(feature = "core",
-           reason = "should be renamed to from_raw_parts")]
+#[unstable(feature = "core")]
+#[deprecated(since = "1.0.0",
+             reason = "use from_raw_parts")]
 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: uint) -> &'a [T] {
     transmute(RawSlice { data: *p, len: len })
 }
@@ -1396,8 +1433,9 @@ pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: uint) -> &'a [T] {
 /// not being able to provide a non-aliasing guarantee of the returned mutable
 /// slice.
 #[inline]
-#[unstable(feature = "core",
-           reason = "should be renamed to from_raw_parts_mut")]
+#[unstable(feature = "core")]
+#[deprecated(since = "1.0.0",
+             reason = "use from_raw_parts_mut")]
 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] {
     transmute(RawSlice { data: *p, len: len })
 }
index 8c0c16bafc4c586b860d57ebb81339ebe2c3719c..013b7f27839dabd518ea39a4585cafa9aae8c1e5 100644 (file)
@@ -149,7 +149,6 @@ fn from_str(s: &str) -> Result<bool, ParseBoolError> {
 
 /// An error returned when parsing a `bool` from a string fails.
 #[derive(Debug, Clone, PartialEq)]
-#[allow(missing_copy_implementations)]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct ParseBoolError { _priv: () }
 
@@ -1518,11 +1517,11 @@ fn ends_with(&self, needle: &str) -> bool {
 
     #[inline]
     fn trim_matches<P: CharEq>(&self, mut pat: P) -> &str {
-        let cur = match self.find(|&mut: c: char| !pat.matches(c)) {
+        let cur = match self.find(|c: char| !pat.matches(c)) {
             None => "",
             Some(i) => unsafe { self.slice_unchecked(i, self.len()) }
         };
-        match cur.rfind(|&mut: c: char| !pat.matches(c)) {
+        match cur.rfind(|c: char| !pat.matches(c)) {
             None => "",
             Some(i) => {
                 let right = cur.char_range_at(i).next;
@@ -1533,7 +1532,7 @@ fn trim_matches<P: CharEq>(&self, mut pat: P) -> &str {
 
     #[inline]
     fn trim_left_matches<P: CharEq>(&self, mut pat: P) -> &str {
-        match self.find(|&mut: c: char| !pat.matches(c)) {
+        match self.find(|c: char| !pat.matches(c)) {
             None => "",
             Some(first) => unsafe { self.slice_unchecked(first, self.len()) }
         }
@@ -1541,7 +1540,7 @@ fn trim_left_matches<P: CharEq>(&self, mut pat: P) -> &str {
 
     #[inline]
     fn trim_right_matches<P: CharEq>(&self, mut pat: P) -> &str {
-        match self.rfind(|&mut: c: char| !pat.matches(c)) {
+        match self.rfind(|c: char| !pat.matches(c)) {
             None => "",
             Some(last) => {
                 let next = self.char_range_at(last).next;
index 2e29b1c41c418f1fb098735d3df6ee353e942d3a..9ba9c2c4a9ca57599a0d12ea8f43625294660520 100644 (file)
@@ -166,7 +166,7 @@ fn string(c: char) -> String { c.escape_unicode().collect() }
 fn test_encode_utf8() {
     fn check(input: char, expect: &[u8]) {
         let mut buf = [0u8; 4];
-        let n = input.encode_utf8(buf.as_mut_slice()).unwrap_or(0);
+        let n = input.encode_utf8(&mut buf).unwrap_or(0);
         assert_eq!(&buf[..n], expect);
     }
 
@@ -180,7 +180,7 @@ fn check(input: char, expect: &[u8]) {
 fn test_encode_utf16() {
     fn check(input: char, expect: &[u16]) {
         let mut buf = [0u16; 2];
-        let n = input.encode_utf16(buf.as_mut_slice()).unwrap_or(0);
+        let n = input.encode_utf16(&mut buf).unwrap_or(0);
         assert_eq!(&buf[..n], expect);
     }
 
index 22917b09ce9959856b3dcbb8c3451c380290d61f..42c2dfbda082af112e9b208bc1839428f792eee8 100644 (file)
@@ -47,8 +47,9 @@ fn test_fail() {
 
 #[test]
 fn test_retval() {
-    let mut closure = |&mut:| 10;
-    let i = closure.finally(|| { });
+    let mut closure = || 10;
+    // FIXME(#16640) `: i32` annotation shouldn't be necessary
+    let i: i32 = closure.finally(|| { });
     assert_eq!(i, 10);
 }
 
index a493f71925e0a2a15a53158be8a9bf837fcea39c..248cad32ef4d24c7af645dc16543d783bf9cf682 100644 (file)
@@ -110,7 +110,7 @@ fn test_siphash() {
     fn to_hex_str(r: &[u8; 8]) -> String {
         let mut s = String::new();
         for b in r {
-            s.push_str(format!("{}", fmt::radix(*b, 16)).as_slice());
+            s.push_str(format!("{}", fmt::radix(*b, 16)));
         }
         s
     }
@@ -131,7 +131,7 @@ fn result_str(h: u64) -> String {
         let r = result_bytes(h);
         let mut s = String::new();
         for b in &r {
-            s.push_str(format!("{}", fmt::radix(*b, 16)).as_slice());
+            s.push_str(format!("{}", fmt::radix(*b, 16)));
         }
         s
     }
@@ -139,12 +139,12 @@ fn result_str(h: u64) -> String {
     while t < 64 {
         debug!("siphash test {}: {}", t, buf);
         let vec = u8to64_le!(vecs[t], 0);
-        let out = hash_with_keys(k0, k1, &Bytes(buf.as_slice()));
+        let out = hash_with_keys(k0, k1, &Bytes(buf));
         debug!("got {}, expected {}", out, vec);
         assert_eq!(vec, out);
 
         state_full.reset();
-        state_full.write(buf.as_slice());
+        state_full.write(buf);
         let f = result_str(state_full.result());
         let i = result_str(state_inc.result());
         let v = to_hex_str(&vecs[t]);
index f2a1b0ac584d3d34875b5ede0d2db196fbb50c3e..375564c39bb5b1846f5a4d0f7fd27310ead2cb07 100644 (file)
@@ -54,7 +54,7 @@ fn test_rsplitn_char_iterator() {
     split.reverse();
     assert_eq!(split, vec!["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
 
-    let mut split: Vec<&str> = data.rsplitn(3, |&: c: char| c == ' ').collect();
+    let mut split: Vec<&str> = data.rsplitn(3, |c: char| c == ' ').collect();
     split.reverse();
     assert_eq!(split, vec!["\nMäry häd ä", "little", "lämb\nLittle", "lämb\n"]);
 
@@ -63,7 +63,7 @@ fn test_rsplitn_char_iterator() {
     split.reverse();
     assert_eq!(split, vec!["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
 
-    let mut split: Vec<&str> = data.rsplitn(3, |&: c: char| c == 'ä').collect();
+    let mut split: Vec<&str> = data.rsplitn(3, |c: char| c == 'ä').collect();
     split.reverse();
     assert_eq!(split, vec!["\nMäry häd ", " little l", "mb\nLittle l", "mb\n"]);
 }
@@ -79,10 +79,10 @@ fn test_split_char_iterator() {
     rsplit.reverse();
     assert_eq!(rsplit, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
 
-    let split: Vec<&str> = data.split(|&: c: char| c == ' ').collect();
+    let split: Vec<&str> = data.split(|c: char| c == ' ').collect();
     assert_eq!( split, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
 
-    let mut rsplit: Vec<&str> = data.split(|&: c: char| c == ' ').rev().collect();
+    let mut rsplit: Vec<&str> = data.split(|c: char| c == ' ').rev().collect();
     rsplit.reverse();
     assert_eq!(rsplit, vec!["\nMäry", "häd", "ä", "little", "lämb\nLittle", "lämb\n"]);
 
@@ -94,10 +94,10 @@ fn test_split_char_iterator() {
     rsplit.reverse();
     assert_eq!(rsplit, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
 
-    let split: Vec<&str> = data.split(|&: c: char| c == 'ä').collect();
+    let split: Vec<&str> = data.split(|c: char| c == 'ä').collect();
     assert_eq!( split, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
 
-    let mut rsplit: Vec<&str> = data.split(|&: c: char| c == 'ä').rev().collect();
+    let mut rsplit: Vec<&str> = data.split(|c: char| c == 'ä').rev().collect();
     rsplit.reverse();
     assert_eq!(rsplit, vec!["\nM", "ry h", "d ", " little l", "mb\nLittle l", "mb\n"]);
 }
index a3bbba6d7b432eb0f4ee48d541b50cd187cf9c45..a81b8777af40281197e7732a225918f72c99cfa1 100644 (file)
@@ -45,7 +45,7 @@ pub struct Bytes {
 impl Deref for Bytes {
     type Target = [u8];
     fn deref(&self) -> &[u8] {
-        unsafe { slice::from_raw_mut_buf(&self.ptr.0, self.len) }
+        unsafe { slice::from_raw_parts_mut(self.ptr.0, self.len) }
     }
 }
 
@@ -147,24 +147,24 @@ fn test_flate_round_trip() {
         for _ in 0..20 {
             let mut input = vec![];
             for _ in 0..2000 {
-                input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
+                input.push_all(r.choose(&words).unwrap());
             }
             debug!("de/inflate of {} bytes of random word-sequences",
                    input.len());
-            let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
-            let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
+            let cmp = deflate_bytes(&input).expect("deflation failed");
+            let out = inflate_bytes(&cmp).expect("inflation failed");
             debug!("{} bytes deflated to {} ({:.1}% size)",
                    input.len(), cmp.len(),
                    100.0 * ((cmp.len() as f64) / (input.len() as f64)));
-            assert_eq!(input, out.as_slice());
+            assert_eq!(&*input, &*out);
         }
     }
 
     #[test]
     fn test_zlib_flate() {
         let bytes = vec!(1, 2, 3, 4, 5);
-        let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
-        let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
-        assert_eq!(inflated.as_slice(), bytes);
+        let deflated = deflate_bytes(&bytes).expect("deflation failed");
+        let inflated = inflate_bytes(&deflated).expect("inflation failed");
+        assert_eq!(&*inflated, &*bytes);
     }
 }
index 9cfd4933ac22980c9264f1f768ca7fd0ef6c61a2..1b30bdf230ec127b8af67e203f0bc4dd4f0fb468 100644 (file)
@@ -316,7 +316,7 @@ pub fn opt_count(&self, nm: &str) -> uint {
     /// Returns true if any of several options were matched.
     pub fn opts_present(&self, names: &[String]) -> bool {
         for nm in names {
-            match find_opt(self.opts.as_slice(), Name::from_str(&nm[])) {
+            match find_opt(&self.opts, Name::from_str(&**nm)) {
                 Some(id) if !self.vals[id].is_empty() => return true,
                 _ => (),
             };
@@ -627,7 +627,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
                        interpreted correctly
                     */
 
-                    let opt_id = match find_opt(opts.as_slice(), opt.clone()) {
+                    let opt_id = match find_opt(&opts, opt.clone()) {
                       Some(id) => id,
                       None => return Err(UnrecognizedOption(opt.to_string()))
                     };
@@ -650,7 +650,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
             let mut name_pos = 0;
             for nm in &names {
                 name_pos += 1;
-                let optid = match find_opt(opts.as_slice(), (*nm).clone()) {
+                let optid = match find_opt(&opts, (*nm).clone()) {
                   Some(id) => id,
                   None => return Err(UnrecognizedOption(nm.to_string()))
                 };
@@ -889,7 +889,7 @@ fn each_split_within<F>(ss: &str, lim: uint, mut it: F) -> bool where
         lim = fake_i;
     }
 
-    let mut machine = |&mut: cont: &mut bool, (i, c): (uint, char)| -> bool {
+    let mut machine = |cont: &mut bool, (i, c): (uint, char)| -> bool {
         let whitespace = if c.is_whitespace() { Ws }       else { Cr };
         let limit      = if (i - slice_start + 1) <= lim  { UnderLim } else { OverLim };
 
@@ -981,7 +981,7 @@ mod tests {
     fn test_reqopt() {
         let long_args = vec!("--test=20".to_string());
         let opts = vec!(reqopt("t", "test", "testing", "TEST"));
-        let rs = getopts(long_args.as_slice(), opts.as_slice());
+        let rs = getopts(&long_args, &opts);
         match rs {
           Ok(ref m) => {
             assert!(m.opt_present("test"));
@@ -992,7 +992,7 @@ fn test_reqopt() {
           _ => { panic!("test_reqopt failed (long arg)"); }
         }
         let short_args = vec!("-t".to_string(), "20".to_string());
-        match getopts(short_args.as_slice(), opts.as_slice()) {
+        match getopts(&short_args, &opts) {
           Ok(ref m) => {
             assert!((m.opt_present("test")));
             assert_eq!(m.opt_str("test").unwrap(), "20");
@@ -1007,7 +1007,7 @@ fn test_reqopt() {
     fn test_reqopt_missing() {
         let args = vec!("blah".to_string());
         let opts = vec!(reqopt("t", "test", "testing", "TEST"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Err(OptionMissing(_)) => {},
           _ => panic!()
@@ -1018,13 +1018,13 @@ fn test_reqopt_missing() {
     fn test_reqopt_no_arg() {
         let long_args = vec!("--test".to_string());
         let opts = vec!(reqopt("t", "test", "testing", "TEST"));
-        let rs = getopts(long_args.as_slice(), opts.as_slice());
+        let rs = getopts(&long_args, &opts);
         match rs {
           Err(ArgumentMissing(_)) => {},
           _ => panic!()
         }
         let short_args = vec!("-t".to_string());
-        match getopts(short_args.as_slice(), opts.as_slice()) {
+        match getopts(&short_args, &opts) {
           Err(ArgumentMissing(_)) => {},
           _ => panic!()
         }
@@ -1034,7 +1034,7 @@ fn test_reqopt_no_arg() {
     fn test_reqopt_multi() {
         let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
         let opts = vec!(reqopt("t", "test", "testing", "TEST"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Err(OptionDuplicated(_)) => {},
           _ => panic!()
@@ -1046,7 +1046,7 @@ fn test_reqopt_multi() {
     fn test_optopt() {
         let long_args = vec!("--test=20".to_string());
         let opts = vec!(optopt("t", "test", "testing", "TEST"));
-        let rs = getopts(long_args.as_slice(), opts.as_slice());
+        let rs = getopts(&long_args, &opts);
         match rs {
           Ok(ref m) => {
             assert!(m.opt_present("test"));
@@ -1057,7 +1057,7 @@ fn test_optopt() {
           _ => panic!()
         }
         let short_args = vec!("-t".to_string(), "20".to_string());
-        match getopts(short_args.as_slice(), opts.as_slice()) {
+        match getopts(&short_args, &opts) {
           Ok(ref m) => {
             assert!((m.opt_present("test")));
             assert_eq!(m.opt_str("test").unwrap(), "20");
@@ -1072,7 +1072,7 @@ fn test_optopt() {
     fn test_optopt_missing() {
         let args = vec!("blah".to_string());
         let opts = vec!(optopt("t", "test", "testing", "TEST"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert!(!m.opt_present("test"));
@@ -1086,13 +1086,13 @@ fn test_optopt_missing() {
     fn test_optopt_no_arg() {
         let long_args = vec!("--test".to_string());
         let opts = vec!(optopt("t", "test", "testing", "TEST"));
-        let rs = getopts(long_args.as_slice(), opts.as_slice());
+        let rs = getopts(&long_args, &opts);
         match rs {
           Err(ArgumentMissing(_)) => {},
           _ => panic!()
         }
         let short_args = vec!("-t".to_string());
-        match getopts(short_args.as_slice(), opts.as_slice()) {
+        match getopts(&short_args, &opts) {
           Err(ArgumentMissing(_)) => {},
           _ => panic!()
         }
@@ -1102,7 +1102,7 @@ fn test_optopt_no_arg() {
     fn test_optopt_multi() {
         let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
         let opts = vec!(optopt("t", "test", "testing", "TEST"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Err(OptionDuplicated(_)) => {},
           _ => panic!()
@@ -1114,7 +1114,7 @@ fn test_optopt_multi() {
     fn test_optflag() {
         let long_args = vec!("--test".to_string());
         let opts = vec!(optflag("t", "test", "testing"));
-        let rs = getopts(long_args.as_slice(), opts.as_slice());
+        let rs = getopts(&long_args, &opts);
         match rs {
           Ok(ref m) => {
             assert!(m.opt_present("test"));
@@ -1123,7 +1123,7 @@ fn test_optflag() {
           _ => panic!()
         }
         let short_args = vec!("-t".to_string());
-        match getopts(short_args.as_slice(), opts.as_slice()) {
+        match getopts(&short_args, &opts) {
           Ok(ref m) => {
             assert!(m.opt_present("test"));
             assert!(m.opt_present("t"));
@@ -1136,7 +1136,7 @@ fn test_optflag() {
     fn test_optflag_missing() {
         let args = vec!("blah".to_string());
         let opts = vec!(optflag("t", "test", "testing"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert!(!m.opt_present("test"));
@@ -1150,7 +1150,7 @@ fn test_optflag_missing() {
     fn test_optflag_long_arg() {
         let args = vec!("--test=20".to_string());
         let opts = vec!(optflag("t", "test", "testing"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Err(UnexpectedArgument(_)) => {},
           _ => panic!()
@@ -1161,7 +1161,7 @@ fn test_optflag_long_arg() {
     fn test_optflag_multi() {
         let args = vec!("--test".to_string(), "-t".to_string());
         let opts = vec!(optflag("t", "test", "testing"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Err(OptionDuplicated(_)) => {},
           _ => panic!()
@@ -1172,7 +1172,7 @@ fn test_optflag_multi() {
     fn test_optflag_short_arg() {
         let args = vec!("-t".to_string(), "20".to_string());
         let opts = vec!(optflag("t", "test", "testing"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             // The next variable after the flag is just a free argument
@@ -1188,7 +1188,7 @@ fn test_optflag_short_arg() {
     fn test_optflagmulti_short1() {
         let args = vec!("-v".to_string());
         let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert_eq!(m.opt_count("v"), 1);
@@ -1201,7 +1201,7 @@ fn test_optflagmulti_short1() {
     fn test_optflagmulti_short2a() {
         let args = vec!("-v".to_string(), "-v".to_string());
         let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert_eq!(m.opt_count("v"), 2);
@@ -1214,7 +1214,7 @@ fn test_optflagmulti_short2a() {
     fn test_optflagmulti_short2b() {
         let args = vec!("-vv".to_string());
         let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert_eq!(m.opt_count("v"), 2);
@@ -1227,7 +1227,7 @@ fn test_optflagmulti_short2b() {
     fn test_optflagmulti_long1() {
         let args = vec!("--verbose".to_string());
         let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert_eq!(m.opt_count("verbose"), 1);
@@ -1240,7 +1240,7 @@ fn test_optflagmulti_long1() {
     fn test_optflagmulti_long2() {
         let args = vec!("--verbose".to_string(), "--verbose".to_string());
         let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert_eq!(m.opt_count("verbose"), 2);
@@ -1254,7 +1254,7 @@ fn test_optflagmulti_mix() {
         let args = vec!("--verbose".to_string(), "-v".to_string(),
                         "-vv".to_string(), "verbose".to_string());
         let opts = vec!(optflagmulti("v", "verbose", "verbosity"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert_eq!(m.opt_count("verbose"), 4);
@@ -1269,7 +1269,7 @@ fn test_optflagmulti_mix() {
     fn test_optmulti() {
         let long_args = vec!("--test=20".to_string());
         let opts = vec!(optmulti("t", "test", "testing", "TEST"));
-        let rs = getopts(long_args.as_slice(), opts.as_slice());
+        let rs = getopts(&long_args, &opts);
         match rs {
           Ok(ref m) => {
             assert!((m.opt_present("test")));
@@ -1280,7 +1280,7 @@ fn test_optmulti() {
           _ => panic!()
         }
         let short_args = vec!("-t".to_string(), "20".to_string());
-        match getopts(short_args.as_slice(), opts.as_slice()) {
+        match getopts(&short_args, &opts) {
           Ok(ref m) => {
             assert!((m.opt_present("test")));
             assert_eq!(m.opt_str("test").unwrap(), "20");
@@ -1295,7 +1295,7 @@ fn test_optmulti() {
     fn test_optmulti_missing() {
         let args = vec!("blah".to_string());
         let opts = vec!(optmulti("t", "test", "testing", "TEST"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert!(!m.opt_present("test"));
@@ -1309,13 +1309,13 @@ fn test_optmulti_missing() {
     fn test_optmulti_no_arg() {
         let long_args = vec!("--test".to_string());
         let opts = vec!(optmulti("t", "test", "testing", "TEST"));
-        let rs = getopts(long_args.as_slice(), opts.as_slice());
+        let rs = getopts(&long_args, &opts);
         match rs {
           Err(ArgumentMissing(_)) => {},
           _ => panic!()
         }
         let short_args = vec!("-t".to_string());
-        match getopts(short_args.as_slice(), opts.as_slice()) {
+        match getopts(&short_args, &opts) {
           Err(ArgumentMissing(_)) => {},
           _ => panic!()
         }
@@ -1325,7 +1325,7 @@ fn test_optmulti_no_arg() {
     fn test_optmulti_multi() {
         let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string());
         let opts = vec!(optmulti("t", "test", "testing", "TEST"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
               assert!(m.opt_present("test"));
@@ -1344,13 +1344,13 @@ fn test_optmulti_multi() {
     fn test_unrecognized_option() {
         let long_args = vec!("--untest".to_string());
         let opts = vec!(optmulti("t", "test", "testing", "TEST"));
-        let rs = getopts(long_args.as_slice(), opts.as_slice());
+        let rs = getopts(&long_args, &opts);
         match rs {
           Err(UnrecognizedOption(_)) => {},
           _ => panic!()
         }
         let short_args = vec!("-u".to_string());
-        match getopts(short_args.as_slice(), opts.as_slice()) {
+        match getopts(&short_args, &opts) {
           Err(UnrecognizedOption(_)) => {},
           _ => panic!()
         }
@@ -1383,7 +1383,7 @@ fn test_combined() {
               optmulti("m", "", "mmmmmm", "YUM"),
               optmulti("n", "", "nothing", "NOTHING"),
               optopt("", "notpresent", "nothing to see here", "NOPE"));
-        let rs = getopts(args.as_slice(), opts.as_slice());
+        let rs = getopts(&args, &opts);
         match rs {
           Ok(ref m) => {
             assert!(m.free[0] == "prog");
@@ -1412,8 +1412,7 @@ fn test_multi() {
                      optopt("f", "", "flag", "FLAG"));
 
         let args_single = vec!("-e".to_string(), "foo".to_string());
-        let matches_single = &match getopts(args_single.as_slice(),
-                                            opts.as_slice()) {
+        let matches_single = &match getopts(&args_single, &opts) {
           result::Result::Ok(m) => m,
           result::Result::Err(_) => panic!()
         };
@@ -1432,8 +1431,7 @@ fn test_multi() {
 
         let args_both = vec!("-e".to_string(), "foo".to_string(), "--encrypt".to_string(),
                              "foo".to_string());
-        let matches_both = &match getopts(args_both.as_slice(),
-                                          opts.as_slice()) {
+        let matches_both = &match getopts(&args_both, &opts) {
           result::Result::Ok(m) => m,
           result::Result::Err(_) => panic!()
         };
@@ -1458,7 +1456,7 @@ fn test_nospace() {
         let args = vec!("-Lfoo".to_string(), "-M.".to_string());
         let opts = vec!(optmulti("L", "", "library directory", "LIB"),
                      optmulti("M", "", "something", "MMMM"));
-        let matches = &match getopts(args.as_slice(), opts.as_slice()) {
+        let matches = &match getopts(&args, &opts) {
           result::Result::Ok(m) => m,
           result::Result::Err(_) => panic!()
         };
@@ -1474,7 +1472,7 @@ fn test_nospace_conflict() {
         let args = vec!("-vvLverbose".to_string(), "-v".to_string() );
         let opts = vec!(optmulti("L", "", "library directory", "LIB"),
                      optflagmulti("v", "verbose", "Verbose"));
-        let matches = &match getopts(args.as_slice(), opts.as_slice()) {
+        let matches = &match getopts(&args, &opts) {
           result::Result::Ok(m) => m,
           result::Result::Err(e) => panic!( "{}", e )
         };
@@ -1508,7 +1506,7 @@ fn test_aliases_long_and_short() {
 
         let args = vec!("-a".to_string(), "--apple".to_string(), "-a".to_string());
 
-        let matches = getopts(args.as_slice(), opts.as_slice()).unwrap();
+        let matches = getopts(&args, &opts).unwrap();
         assert_eq!(3, matches.opt_count("a"));
         assert_eq!(3, matches.opt_count("apple"));
     }
@@ -1535,7 +1533,7 @@ fn test_usage() {
     -l VAL              Desc
 ";
 
-        let generated_usage = usage("Usage: fruits", optgroups.as_slice());
+        let generated_usage = usage("Usage: fruits", &optgroups);
 
         debug!("expected: <<{}>>", expected);
         debug!("generated: <<{}>>", generated_usage);
@@ -1562,7 +1560,7 @@ fn test_usage_description_wrapping() {
                         wrapped..+..
 ";
 
-        let usage = usage("Usage: fruits", optgroups.as_slice());
+        let usage = usage("Usage: fruits", &optgroups);
 
         debug!("expected: <<{}>>", expected);
         debug!("generated: <<{}>>", usage);
@@ -1588,7 +1586,7 @@ fn test_usage_description_multibyte_handling() {
                         some parts of Europe.
 ";
 
-        let usage = usage("Usage: fruits", optgroups.as_slice());
+        let usage = usage("Usage: fruits", &optgroups);
 
         debug!("expected: <<{}>>", expected);
         debug!("generated: <<{}>>", usage);
@@ -1606,7 +1604,7 @@ fn test_short_usage() {
             optmulti("l", "", "Desc", "VAL"));
 
         let expected = "Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..".to_string();
-        let generated_usage = short_usage("fruits", optgroups.as_slice());
+        let generated_usage = short_usage("fruits", &optgroups);
 
         debug!("expected: <<{}>>", expected);
         debug!("generated: <<{}>>", generated_usage);
index b33ca3fd7ec01d35639341adc458458629b5351e..2d94ddaef18355fe146551e0bb40e6598544003c 100644 (file)
 #![feature(collections)]
 #![feature(core)]
 #![feature(io)]
-#![feature(path)]
 
 use self::LabelText::*;
 
 use std::string::CowString;
 use std::vec::CowVec;
 
-pub mod maybe_owned_vec;
-
 /// The text for a graphviz label on a node or edge.
 pub enum LabelText<'a> {
     /// This kind of label preserves the text directly as is.
@@ -565,7 +562,7 @@ fn indent<W:Writer>(w: &mut W) -> old_io::IoResult<()> {
         } else {
             let escaped = g.node_label(n).escape();
             try!(writeln(w, &[id.as_slice(),
-                              "[label=\"", escaped.as_slice(), "\"];"]));
+                              "[label=\"", &escaped, "\"];"]));
         }
     }
 
@@ -582,7 +579,7 @@ fn indent<W:Writer>(w: &mut W) -> old_io::IoResult<()> {
         } else {
             try!(writeln(w, &[source_id.as_slice(),
                               " -> ", target_id.as_slice(),
-                              "[label=\"", escaped_label.as_slice(), "\"];"]));
+                              "[label=\"", &escaped_label, "\"];"]));
         }
     }
 
@@ -746,7 +743,7 @@ fn target(&'a self, edge: & &'a Edge) -> Node {
     fn test_input(g: LabelledGraph) -> IoResult<String> {
         let mut writer = Vec::new();
         render(&g, &mut writer).unwrap();
-        (&mut writer.as_slice()).read_to_string()
+        (&mut &*writer).read_to_string()
     }
 
     // All of the tests use raw-strings as the format for the expected outputs,
@@ -858,7 +855,7 @@ fn left_aligned_text() {
                  edge(1, 3, ";"),    edge(2, 3, ";"   )));
 
         render(&g, &mut writer).unwrap();
-        let r = (&mut writer.as_slice()).read_to_string();
+        let r = (&mut &*writer).read_to_string();
 
         assert_eq!(r.unwrap(),
 r#"digraph syntax_tree {
diff --git a/src/libgraphviz/maybe_owned_vec.rs b/src/libgraphviz/maybe_owned_vec.rs
deleted file mode 100644 (file)
index 1c93185..0000000
+++ /dev/null
@@ -1,165 +0,0 @@
-// 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.
-
-#![unstable(feature = "rustc_private")]
-#![deprecated(since = "1.0.0", reason = "use std::vec::CowVec")]
-
-pub use self::MaybeOwnedVector::*;
-
-use std::cmp::Ordering;
-use std::default::Default;
-use std::fmt;
-use std::iter::FromIterator;
-use std::old_path::BytesContainer;
-use std::slice;
-
-// Note 1: It is not clear whether the flexibility of providing both
-// the `Growable` and `FixedLen` variants is sufficiently useful.
-// Consider restricting to just a two variant enum.
-
-// Note 2: Once Dynamically Sized Types (DST) lands, it might be
-// reasonable to replace this with something like `enum MaybeOwned<'a,
-// U: ?Sized>{ Owned(Box<U>), Borrowed(&'a U) }`; and then `U` could be
-// instantiated with `[T]` or `str`, etc.  Of course, that would imply
-// removing the `Growable` variant, which relates to note 1 above.
-// Alternatively, we might add `MaybeOwned` for the general case but
-// keep some form of `MaybeOwnedVector` to avoid unnecessary copying
-// of the contents of `Vec<T>`, since we anticipate that to be a
-// frequent way to dynamically construct a vector.
-
-/// MaybeOwnedVector<'a,T> abstracts over `Vec<T>`, `&'a [T]`.
-///
-/// Some clients will have a pre-allocated vector ready to hand off in
-/// a slice; others will want to create the set on the fly and hand
-/// off ownership, via `Growable`.
-pub enum MaybeOwnedVector<'a,T:'a> {
-    Growable(Vec<T>),
-    Borrowed(&'a [T]),
-}
-
-/// Trait for moving into a `MaybeOwnedVector`
-pub trait IntoMaybeOwnedVector<'a,T> {
-    /// Moves self into a `MaybeOwnedVector`
-    fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T>;
-}
-
-#[allow(deprecated)]
-impl<'a,T:'a> IntoMaybeOwnedVector<'a,T> for Vec<T> {
-    #[allow(deprecated)]
-    #[inline]
-    fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Growable(self) }
-}
-
-#[allow(deprecated)]
-impl<'a,T> IntoMaybeOwnedVector<'a,T> for &'a [T] {
-    #[allow(deprecated)]
-    #[inline]
-    fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Borrowed(self) }
-}
-
-impl<'a,T> MaybeOwnedVector<'a,T> {
-    pub fn iter(&'a self) -> slice::Iter<'a,T> {
-        match self {
-            &Growable(ref v) => v.as_slice().iter(),
-            &Borrowed(ref v) => v.iter(),
-        }
-    }
-
-    pub fn len(&self) -> uint { self.as_slice().len() }
-
-    #[allow(deprecated)]
-    pub fn is_empty(&self) -> bool { self.len() == 0 }
-}
-
-impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> {
-    fn eq(&self, other: &MaybeOwnedVector<T>) -> bool {
-        self.as_slice() == other.as_slice()
-    }
-}
-
-impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {}
-
-impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> {
-    fn partial_cmp(&self, other: &MaybeOwnedVector<T>) -> Option<Ordering> {
-        self.as_slice().partial_cmp(other.as_slice())
-    }
-}
-
-impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> {
-    fn cmp(&self, other: &MaybeOwnedVector<T>) -> Ordering {
-        self.as_slice().cmp(other.as_slice())
-    }
-}
-
-// The `Vector` trait is provided in the prelude and is implemented on
-// both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it
-// seamlessly.  The other vector related traits from the prelude do
-// not appear to be implemented on both `&'a [T]` and `Vec<T>`.  (It
-// is possible that this is an oversight in some cases.)
-//
-// In any case, with `Vector` in place, the client can just use
-// `as_slice` if they prefer that over `match`.
-
-impl<'b,T> AsSlice<T> for MaybeOwnedVector<'b,T> {
-    fn as_slice<'a>(&'a self) -> &'a [T] {
-        match self {
-            &Growable(ref v) => v.as_slice(),
-            &Borrowed(ref v) => v.as_slice(),
-        }
-    }
-}
-
-impl<'a,T> FromIterator<T> for MaybeOwnedVector<'a,T> {
-    #[allow(deprecated)]
-    fn from_iter<I:Iterator<Item=T>>(iterator: I) -> MaybeOwnedVector<'a,T> {
-        // If we are building from scratch, might as well build the
-        // most flexible variant.
-        Growable(iterator.collect())
-    }
-}
-
-impl<'a,T:fmt::Debug> fmt::Debug for MaybeOwnedVector<'a,T> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        self.as_slice().fmt(f)
-    }
-}
-
-impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> {
-    #[allow(deprecated)]
-    fn clone(&self) -> MaybeOwnedVector<'a, T> {
-        match *self {
-            Growable(ref v) => Growable(v.clone()),
-            Borrowed(v) => Borrowed(v)
-        }
-    }
-}
-
-impl<'a, T> Default for MaybeOwnedVector<'a, T> {
-    #[allow(deprecated)]
-    fn default() -> MaybeOwnedVector<'a, T> {
-        Growable(Vec::new())
-    }
-}
-
-impl<'a> BytesContainer for MaybeOwnedVector<'a, u8> {
-    fn container_as_bytes(&self) -> &[u8] {
-        self.as_slice()
-    }
-}
-
-impl<'a,T:Clone> MaybeOwnedVector<'a,T> {
-    /// Convert `self` into a growable `Vec`, not making a copy if possible.
-    pub fn into_vec(self) -> Vec<T> {
-        match self {
-            Growable(v) => v,
-            Borrowed(v) => v.to_vec(),
-        }
-    }
-}
index c5ea10beb83c525303da145b09541e5870eecf44..38d5c5eb27ae2d449739d8cceca055067fad4ad1 100644 (file)
@@ -16,6 +16,7 @@
 #![cfg_attr(not(feature = "cargo-build"), staged_api)]
 #![cfg_attr(not(feature = "cargo-build"), feature(core))]
 #![feature(int_uint)]
+#![feature(no_std)]
 #![no_std]
 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
@@ -332,15 +333,12 @@ pub mod c95 {
             /// variants, because the compiler complains about the repr attribute
             /// otherwise.
             #[repr(u8)]
-            #[allow(missing_copy_implementations)]
             pub enum c_void {
                 __variant1,
                 __variant2,
             }
 
-            #[allow(missing_copy_implementations)]
             pub enum FILE {}
-            #[allow(missing_copy_implementations)]
             pub enum fpos_t {}
         }
         pub mod c99 {
@@ -354,9 +352,7 @@ pub mod c99 {
             pub type uint64_t = u64;
         }
         pub mod posix88 {
-            #[allow(missing_copy_implementations)]
             pub enum DIR {}
-            #[allow(missing_copy_implementations)]
             pub enum dirent_t {}
         }
         pub mod posix01 {}
@@ -5734,8 +5730,9 @@ pub fn issue_14344_workaround() {} // FIXME #14344 force linkage to happen corre
 
 #[test] fn work_on_windows() { } // FIXME #10872 needed for a happy windows
 
+// NOTE: remove after next snapshot
 #[doc(hidden)]
-#[cfg(not(test))]
+#[cfg(all(stage0, not(test)))]
 mod std {
     pub use core::marker;
 }
index 34216518c21d2073bb61909101eae42b6c089c69..15f50188919b02d8060ddd41f18e54af6b705eb7 100644 (file)
@@ -428,7 +428,7 @@ fn init() {
         DIRECTIVES = mem::transmute(box directives);
 
         // Schedule the cleanup for the globals for when the runtime exits.
-        rt::at_exit(move |:| {
+        rt::at_exit(move || {
             assert!(!DIRECTIVES.is_null());
             let _directives: Box<Vec<directive::LogDirective>> =
                 mem::transmute(DIRECTIVES);
index 9f44f9debf6e2e9fb362b88c4f6903cbbf72036c..2673649f3440cc9170cff3d79e4d0cd556d418b8 100644 (file)
@@ -213,8 +213,8 @@ mod test {
     #[test]
     fn test_rng_rand_seeded() {
         let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
-        let mut ra: ChaChaRng = SeedableRng::from_seed(s.as_slice());
-        let mut rb: ChaChaRng = SeedableRng::from_seed(s.as_slice());
+        let mut ra: ChaChaRng = SeedableRng::from_seed(&*s);
+        let mut rb: ChaChaRng = SeedableRng::from_seed(&*s);
         assert!(order::equals(ra.gen_ascii_chars().take(100),
                               rb.gen_ascii_chars().take(100)));
     }
@@ -231,10 +231,10 @@ fn test_rng_seeded() {
     #[test]
     fn test_rng_reseed() {
         let s = ::test::rng().gen_iter::<u32>().take(8).collect::<Vec<u32>>();
-        let mut r: ChaChaRng = SeedableRng::from_seed(s.as_slice());
+        let mut r: ChaChaRng = SeedableRng::from_seed(&*s);
         let string1: String = r.gen_ascii_chars().take(100).collect();
 
-        r.reseed(s.as_slice());
+        r.reseed(&s);
 
         let string2: String = r.gen_ascii_chars().take(100).collect();
         assert_eq!(string1, string2);
index 180248aa1560a5e1d20bbf63b47a7b812672d922..d1d24cea8714e7c1b4fe544c9dfaf363b9903cb7 100644 (file)
@@ -300,7 +300,7 @@ fn test_weighted_choice() {
         macro_rules! t {
             ($items:expr, $expected:expr) => {{
                 let mut items = $items;
-                let wc = WeightedChoice::new(items.as_mut_slice());
+                let wc = WeightedChoice::new(&mut items);
                 let expected = $expected;
 
                 let mut rng = CountingRng { i: 0 };
index d399c244e83b8fe4ee8367dc2f56ac2f5b6bdcb4..f15523fc010b61118d77eaac322844de6cdb5d6b 100644 (file)
@@ -246,7 +246,7 @@ fn rand<R: Rng>(other: &mut R) -> IsaacRng {
         unsafe {
             let ptr = ret.rsl.as_mut_ptr() as *mut u8;
 
-            let slice = slice::from_raw_mut_buf(&ptr, (RAND_SIZE * 4) as uint);
+            let slice = slice::from_raw_parts_mut(ptr, (RAND_SIZE * 4) as uint);
             other.fill_bytes(slice);
         }
         ret.cnt = 0;
@@ -489,7 +489,7 @@ fn rand<R: Rng>(other: &mut R) -> Isaac64Rng {
         unsafe {
             let ptr = ret.rsl.as_mut_ptr() as *mut u8;
 
-            let slice = slice::from_raw_mut_buf(&ptr, (RAND_SIZE_64 * 8) as uint);
+            let slice = slice::from_raw_parts_mut(ptr, (RAND_SIZE_64 * 8) as uint);
             other.fill_bytes(slice);
         }
         ret.cnt = 0;
@@ -514,16 +514,16 @@ mod test {
     #[test]
     fn test_rng_32_rand_seeded() {
         let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
-        let mut ra: IsaacRng = SeedableRng::from_seed(s.as_slice());
-        let mut rb: IsaacRng = SeedableRng::from_seed(s.as_slice());
+        let mut ra: IsaacRng = SeedableRng::from_seed(&*s);
+        let mut rb: IsaacRng = SeedableRng::from_seed(&*s);
         assert!(order::equals(ra.gen_ascii_chars().take(100),
                               rb.gen_ascii_chars().take(100)));
     }
     #[test]
     fn test_rng_64_rand_seeded() {
         let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
-        let mut ra: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
-        let mut rb: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
+        let mut ra: Isaac64Rng = SeedableRng::from_seed(&*s);
+        let mut rb: Isaac64Rng = SeedableRng::from_seed(&*s);
         assert!(order::equals(ra.gen_ascii_chars().take(100),
                               rb.gen_ascii_chars().take(100)));
     }
@@ -548,10 +548,10 @@ fn test_rng_64_seeded() {
     #[test]
     fn test_rng_32_reseed() {
         let s = ::test::rng().gen_iter::<u32>().take(256).collect::<Vec<u32>>();
-        let mut r: IsaacRng = SeedableRng::from_seed(s.as_slice());
+        let mut r: IsaacRng = SeedableRng::from_seed(&*s);
         let string1: String = r.gen_ascii_chars().take(100).collect();
 
-        r.reseed(s.as_slice());
+        r.reseed(&s);
 
         let string2: String = r.gen_ascii_chars().take(100).collect();
         assert_eq!(string1, string2);
@@ -559,10 +559,10 @@ fn test_rng_32_reseed() {
     #[test]
     fn test_rng_64_reseed() {
         let s = ::test::rng().gen_iter::<u64>().take(256).collect::<Vec<u64>>();
-        let mut r: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
+        let mut r: Isaac64Rng = SeedableRng::from_seed(&*s);
         let string1: String = r.gen_ascii_chars().take(100).collect();
 
-        r.reseed(s.as_slice());
+        r.reseed(&s);
 
         let string2: String = r.gen_ascii_chars().take(100).collect();
         assert_eq!(string1, string2);
index 0627b461fdb0c2bec691da0c28f460cbae6161f2..4113718cfd15b92989dd8e86d894883470a3e3e1 100644 (file)
@@ -23,6 +23,7 @@
        html_root_url = "http://doc.rust-lang.org/nightly/",
        html_playground_url = "http://play.rust-lang.org/")]
 #![feature(int_uint)]
+#![feature(no_std)]
 #![no_std]
 #![unstable(feature = "rand")]
 #![feature(staged_api)]
@@ -387,7 +388,6 @@ pub trait SeedableRng<Seed>: Rng {
 /// [1]: Marsaglia, George (July 2003). ["Xorshift
 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
 /// Statistical Software*. Vol. 8 (Issue 14).
-#[allow(missing_copy_implementations)]
 #[derive(Clone)]
 pub struct XorShiftRng {
     x: u32,
@@ -497,13 +497,15 @@ fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
 /// ```
 pub struct Closed01<F>(pub F);
 
-#[cfg(not(test))]
+// NOTE: remove after next snapshot
+#[cfg(all(stage0, not(test)))]
 mod std {
     pub use core::{option, fmt}; // panic!()
     pub use core::clone; // derive Clone
     pub use core::marker;
     // for-loops
     pub use core::iter;
+    pub use core::ops; // slicing syntax
 }
 
 #[cfg(test)]
index 26c7afc21eb9571dc6bf2485dedbbc1b13d66029..06828911471466d2e1e3eb58786eb04567aacf1a 100644 (file)
@@ -216,7 +216,7 @@ fn test_rng_reseed() {
     #[test]
     fn test_rng_fill_bytes() {
         let mut v = repeat(0u8).take(FILL_BYTES_V_LEN).collect::<Vec<_>>();
-        ::test::rng().fill_bytes(v.as_mut_slice());
+        ::test::rng().fill_bytes(&mut v);
 
         // Sanity test: if we've gotten here, `fill_bytes` has not infinitely
         // recursed.
index fff28a95c4e13eb8d7e7722baeb3dcdd2fd9ebdc..230fda11ab5ac58c9744787fd73a65826485e35c 100644 (file)
@@ -71,7 +71,7 @@ pub fn with_capacity(n: uint) -> SeekableMemWriter {
     /// No method is exposed for acquiring a mutable reference to the buffer
     /// because it could corrupt the state of this `MemWriter`.
     #[inline]
-    pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
+    pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf }
 
     /// Unwraps this `SeekableMemWriter`, returning the underlying buffer
     #[inline]
@@ -190,7 +190,7 @@ fn do_bench_seekable_mem_writer(b: &mut Bencher, times: uint, len: uint) {
         b.iter(|| {
             let mut wr = SeekableMemWriter::new();
             for _ in 0..times {
-                wr.write(src.as_slice()).unwrap();
+                wr.write(&src).unwrap();
             }
 
             let v = wr.unwrap();
index cf5397de149b7c4029a095160ab89b2e9cd89d93..e204a2a65958f450d6a415ddd582bb17ff700d34 100644 (file)
@@ -1194,7 +1194,7 @@ pub fn vuint_at_A_aligned(b: &mut Bencher) {
         b.iter(|| {
             let mut i = 0;
             while i < data.len() {
-                sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
+                sum += reader::vuint_at(&data, i).unwrap().val;
                 i += 4;
             }
         });
@@ -1212,7 +1212,7 @@ pub fn vuint_at_A_unaligned(b: &mut Bencher) {
         b.iter(|| {
             let mut i = 1;
             while i < data.len() {
-                sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
+                sum += reader::vuint_at(&data, i).unwrap().val;
                 i += 4;
             }
         });
@@ -1231,7 +1231,7 @@ pub fn vuint_at_D_aligned(b: &mut Bencher) {
         b.iter(|| {
             let mut i = 0;
             while i < data.len() {
-                sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
+                sum += reader::vuint_at(&data, i).unwrap().val;
                 i += 4;
             }
         });
@@ -1250,7 +1250,7 @@ pub fn vuint_at_D_unaligned(b: &mut Bencher) {
         b.iter(|| {
             let mut i = 1;
             while i < data.len() {
-                sum += reader::vuint_at(data.as_slice(), i).unwrap().val;
+                sum += reader::vuint_at(&data, i).unwrap().val;
                 i += 4;
             }
         });
index b48df36a6793118c72b1526bd6ed3ad6d02260bc..efcc3715d3e3d97f22e3f0586fc039346b39d402 100644 (file)
@@ -14,9 +14,9 @@
     E0001: r##"
     This error suggests that the expression arm corresponding to the noted pattern
     will never be reached as for all possible values of the expression being matched,
-    one of the preceeding patterns will match.
+    one of the preceding patterns will match.
 
-    This means that perhaps some of the preceeding patterns are too general, this
+    This means that perhaps some of the preceding patterns are too general, this
     one is too specific or the ordering is incorrect.
 "##,
 
     E0312, // lifetime of reference outlives lifetime of borrowed content
     E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
     E0314, // closure outlives stack frame
-    E0315 // cannot invoke closure outside of its lifetime
+    E0315, // cannot invoke closure outside of its lifetime
+    E0316 // nested quantification of lifetimes
 }
 
 __build_diagnostic_array! { DIAGNOSTICS }
index 53054f462c8b6c0cd6eccc16c813a980c97f6638..638ecf4572d5d5404cb3338af5c4d3a56b2c0602 100644 (file)
@@ -699,7 +699,7 @@ fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
 
         if !attr::is_used(attr) {
             cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
-            if CRATE_ATTRS.contains(&attr.name().get()) {
+            if CRATE_ATTRS.contains(&&attr.name()[]) {
                 let msg = match attr.node.style {
                     ast::AttrOuter => "crate-level attribute should be an inner \
                                        attribute: add an exclamation mark: #![foo]",
@@ -801,10 +801,10 @@ fn check_must_use(cx: &Context, attrs: &[ast::Attribute], sp: Span) -> bool {
                         None => {}
                         Some(s) => {
                             msg.push_str(": ");
-                            msg.push_str(s.get());
+                            msg.push_str(&s);
                         }
                     }
-                    cx.span_lint(UNUSED_MUST_USE, sp, &msg[]);
+                    cx.span_lint(UNUSED_MUST_USE, sp, &msg);
                     return true;
                 }
             }
@@ -826,8 +826,8 @@ impl NonCamelCaseTypes {
     fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
         fn is_camel_case(ident: ast::Ident) -> bool {
             let ident = token::get_ident(ident);
-            if ident.get().is_empty() { return true; }
-            let ident = ident.get().trim_matches('_');
+            if ident.is_empty() { return true; }
+            let ident = ident.trim_matches('_');
 
             // start with a non-lowercase letter rather than non-uppercase
             // ones (some scripts don't have a concept of upper/lowercase)
@@ -844,7 +844,7 @@ fn to_camel_case(s: &str) -> String {
         let s = token::get_ident(ident);
 
         if !is_camel_case(ident) {
-            let c = to_camel_case(s.get());
+            let c = to_camel_case(&s);
             let m = if c.is_empty() {
                 format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
             } else {
@@ -949,7 +949,7 @@ impl NonSnakeCase {
     fn to_snake_case(mut str: &str) -> String {
         let mut words = vec![];
         // Preserve leading underscores
-        str = str.trim_left_matches(|&mut: c: char| {
+        str = str.trim_left_matches(|c: char| {
             if c == '_' {
                 words.push(String::new());
                 true
@@ -977,8 +977,8 @@ fn to_snake_case(mut str: &str) -> String {
     fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
         fn is_snake_case(ident: ast::Ident) -> bool {
             let ident = token::get_ident(ident);
-            if ident.get().is_empty() { return true; }
-            let ident = ident.get().trim_left_matches('\'');
+            if ident.is_empty() { return true; }
+            let ident = ident.trim_left_matches('\'');
             let ident = ident.trim_matches('_');
 
             let mut allow_underscore = true;
@@ -996,8 +996,8 @@ fn is_snake_case(ident: ast::Ident) -> bool {
         let s = token::get_ident(ident);
 
         if !is_snake_case(ident) {
-            let sc = NonSnakeCase::to_snake_case(s.get());
-            if sc != s.get() {
+            let sc = NonSnakeCase::to_snake_case(&s);
+            if sc != &s[] {
                 cx.span_lint(NON_SNAKE_CASE, span,
                     &*format!("{} `{}` should have a snake case name such as `{}`",
                             sort, s, sc));
@@ -1077,17 +1077,17 @@ impl NonUpperCaseGlobals {
     fn check_upper_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
         let s = token::get_ident(ident);
 
-        if s.get().chars().any(|c| c.is_lowercase()) {
-            let uc: String = NonSnakeCase::to_snake_case(s.get()).chars()
+        if s.chars().any(|c| c.is_lowercase()) {
+            let uc: String = NonSnakeCase::to_snake_case(&s).chars()
                                            .map(|c| c.to_uppercase()).collect();
-            if uc != s.get() {
+            if uc != &s[] {
                 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
-                    format!("{} `{}` should have an upper case name such as `{}`",
-                            sort, s, uc).as_slice());
+                    &format!("{} `{}` should have an upper case name such as `{}`",
+                             sort, s, uc));
             } else {
                 cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
-                    format!("{} `{}` should have an upper case name",
-                            sort, s).as_slice());
+                    &format!("{} `{}` should have an upper case name",
+                             sort, s));
             }
         }
     }
@@ -1241,7 +1241,7 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
                             match items[0].node {
                                 ast::PathListIdent {ref name, ..} => {
                                     let m = format!("braces around {} is unnecessary",
-                                                    token::get_ident(*name).get());
+                                                    &token::get_ident(*name));
                                     cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
                                                  &m[]);
                                 },
@@ -1358,7 +1358,7 @@ fn check_unused_mut_pat(&self, cx: &Context, pats: &[P<ast::Pat>]) {
             pat_util::pat_bindings(&cx.tcx.def_map, &**p, |mode, id, _, path1| {
                 let ident = path1.node;
                 if let ast::BindByValue(ast::MutMutable) = mode {
-                    if !token::get_ident(ident).get().starts_with("_") {
+                    if !token::get_ident(ident).starts_with("_") {
                         match mutables.entry(ident.name.usize()) {
                             Vacant(entry) => { entry.insert(vec![id]); },
                             Occupied(mut entry) => { entry.get_mut().push(id); },
@@ -2018,6 +2018,12 @@ fn id_refers_to_this_method<'tcx>(tcx: &ty::ctxt<'tcx>,
     "unused or unknown features found in crate-level #[feature] directives"
 }
 
+declare_lint! {
+    pub STABLE_FEATURES,
+    Warn,
+    "stable features found in #[feature] directive"
+}
+
 declare_lint! {
     pub UNKNOWN_CRATE_TYPES,
     Deny,
@@ -2038,7 +2044,7 @@ fn id_refers_to_this_method<'tcx>(tcx: &ty::ctxt<'tcx>,
 
 declare_lint! {
     pub MISSING_COPY_IMPLEMENTATIONS,
-    Warn,
+    Allow,
     "detects potentially-forgotten implementations of `Copy`"
 }
 
@@ -2060,6 +2066,7 @@ fn get_lints(&self) -> LintArray {
             UNREACHABLE_CODE,
             WARNINGS,
             UNUSED_FEATURES,
+            STABLE_FEATURES,
             UNKNOWN_CRATE_TYPES,
             VARIANT_SIZE_DIFFERENCES,
             FAT_PTR_TRANSMUTES
@@ -2084,11 +2091,11 @@ fn get_lints(&self) -> LintArray {
     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
         match it.node {
             ast::ItemFn(..) => {
-                if attr::contains_name(it.attrs.as_slice(), "no_mangle") &&
+                if attr::contains_name(&it.attrs, "no_mangle") &&
                        !cx.exported_items.contains(&it.id) {
                     let msg = format!("function {} is marked #[no_mangle], but not exported",
                                       it.ident);
-                    cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg.as_slice());
+                    cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
                 }
             },
             _ => {},
index 91dba90b0d2e2508d1da2c9e571ca0c7096fd6c1..18628f6903f5deabb57a3e446b5bbdc4ec0610cb 100644 (file)
@@ -341,7 +341,7 @@ pub fn gather_attrs(attrs: &[ast::Attribute])
                     -> Vec<Result<(InternedString, Level, Span), Span>> {
     let mut out = vec!();
     for attr in attrs {
-        let level = match Level::from_str(attr.name().get()) {
+        let level = match Level::from_str(&attr.name()) {
             None => continue,
             Some(lvl) => lvl,
         };
@@ -499,18 +499,18 @@ fn with_lint_attrs<F>(&mut self,
                     continue;
                 }
                 Ok((lint_name, level, span)) => {
-                    match self.lints.find_lint(lint_name.get(), &self.tcx.sess, Some(span)) {
+                    match self.lints.find_lint(&lint_name, &self.tcx.sess, Some(span)) {
                         Some(lint_id) => vec![(lint_id, level, span)],
                         None => {
-                            match self.lints.lint_groups.get(lint_name.get()) {
+                            match self.lints.lint_groups.get(&lint_name[]) {
                                 Some(&(ref v, _)) => v.iter()
                                                       .map(|lint_id: &LintId|
                                                            (*lint_id, level, span))
                                                       .collect(),
                                 None => {
                                     self.span_lint(builtin::UNKNOWN_LINTS, span,
-                                               format!("unknown `{}` attribute: `{}`",
-                                                       level.as_str(), lint_name).as_slice());
+                                                   &format!("unknown `{}` attribute: `{}`",
+                                                            level.as_str(), lint_name));
                                     continue;
                                 }
                             }
@@ -797,8 +797,8 @@ pub fn check_crate(tcx: &ty::ctxt,
     for (id, v) in &*tcx.sess.lints.borrow() {
         for &(lint, span, ref msg) in v {
             tcx.sess.span_bug(span,
-                              format!("unprocessed lint {} at {}: {}",
-                                      lint.as_str(), tcx.map.node_to_string(*id), *msg).as_slice())
+                              &format!("unprocessed lint {} at {}: {}",
+                                       lint.as_str(), tcx.map.node_to_string(*id), *msg))
         }
     }
 
index a787369dc633c35e23b8973dfee31e08222e0838..f6cd0e5add2102577f177f626140fba89e4193fb 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
@@ -26,7 +26,7 @@
 use syntax::abi;
 use syntax::attr;
 use syntax::attr::AttrMetaMethods;
-use syntax::codemap::{COMMAND_LINE_SP, Span, mk_sp};
+use syntax::codemap::{Span, mk_sp};
 use syntax::parse;
 use syntax::parse::token::InternedString;
 use syntax::parse::token;
@@ -72,7 +72,7 @@ struct CrateInfo {
 }
 
 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
-    let err = |&: s: &str| {
+    let err = |s: &str| {
         match (sp, sess) {
             (_, None) => panic!("{}", s),
             (Some(sp), Some(sess)) => sess.span_err(sp, s),
@@ -170,7 +170,7 @@ pub fn read_crates(&mut self, krate: &ast::Crate) {
     fn process_crate(&self, c: &ast::Crate) {
         for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
             match a.value_str() {
-                Some(ref linkarg) => self.sess.cstore.add_used_link_args(linkarg.get()),
+                Some(ref linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
                 None => { /* fallthrough */ }
             }
         }
@@ -184,15 +184,15 @@ fn extract_crate_info(&self, i: &ast::Item) -> Option<CrateInfo> {
                        ident, path_opt);
                 let name = match *path_opt {
                     Some((ref path_str, _)) => {
-                        let name = path_str.get().to_string();
+                        let name = path_str.to_string();
                         validate_crate_name(Some(self.sess), &name[],
                                             Some(i.span));
                         name
                     }
-                    None => ident.get().to_string(),
+                    None => ident.to_string(),
                 };
                 Some(CrateInfo {
-                    ident: ident.get().to_string(),
+                    ident: ident.to_string(),
                     name: name,
                     id: i.id,
                     should_link: should_link(i),
@@ -237,7 +237,7 @@ fn process_item(&mut self, i: &ast::Item) {
                     .collect::<Vec<&ast::Attribute>>();
                 for m in &link_args {
                     match m.value_str() {
-                        Some(linkarg) => self.sess.cstore.add_used_link_args(linkarg.get()),
+                        Some(linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
                         None => { /* fallthrough */ }
                     }
                 }
@@ -289,7 +289,7 @@ fn process_item(&mut self, i: &ast::Item) {
                                 }
                             };
                             register_native_lib(self.sess, Some(m.span),
-                                                n.get().to_string(), kind);
+                                                n.to_string(), kind);
                         }
                         None => {}
                     }
@@ -419,6 +419,7 @@ fn resolve_crate(&mut self,
                     root: root,
                     rejected_via_hash: vec!(),
                     rejected_via_triple: vec!(),
+                    rejected_via_kind: vec!(),
                     should_match_name: true,
                 };
                 let library = load_ctxt.load_library_crate();
@@ -456,13 +457,13 @@ pub fn read_plugin_metadata<'b>(&'b mut self,
             CrateOrString::Krate(c) => {
                 (self.extract_crate_info(c).unwrap(), c.span)
             }
-            CrateOrString::Str(s) => {
+            CrateOrString::Str(sp, s) => {
                 (CrateInfo {
                      name: s.to_string(),
                      ident: s.to_string(),
                      id: ast::DUMMY_NODE_ID,
                      should_link: true,
-                 }, COMMAND_LINE_SP)
+                 }, sp)
             }
         };
         let target_triple = &self.sess.opts.target_triple[];
@@ -483,6 +484,7 @@ pub fn read_plugin_metadata<'b>(&'b mut self,
             root: &None,
             rejected_via_hash: vec!(),
             rejected_via_triple: vec!(),
+            rejected_via_kind: vec!(),
             should_match_name: true,
         };
         let library = match load_ctxt.maybe_load_library_crate() {
@@ -529,7 +531,7 @@ pub fn read_plugin_metadata<'b>(&'b mut self,
 #[derive(Copy)]
 pub enum CrateOrString<'a> {
     Krate(&'a ast::Item),
-    Str(&'a str)
+    Str(Span, &'a str)
 }
 
 impl<'a> PluginMetadata<'a> {
index 619cfc1b52c09b4b96c98684f445b26089be6892..b151856e30941e3eb0dcc68dd2a2d159809481db 100644 (file)
@@ -59,7 +59,7 @@ pub fn each_child_of_item<F>(cstore: &cstore::CStore,
     F: FnMut(decoder::DefLike, ast::Name, ast::Visibility),
 {
     let crate_data = cstore.get_crate_data(def_id.krate);
-    let get_crate_data = |&mut: cnum| {
+    let get_crate_data = |cnum| {
         cstore.get_crate_data(cnum)
     };
     decoder::each_child_of_item(cstore.intr.clone(),
@@ -76,7 +76,7 @@ pub fn each_top_level_item_of_crate<F>(cstore: &cstore::CStore,
     F: FnMut(decoder::DefLike, ast::Name, ast::Visibility),
 {
     let crate_data = cstore.get_crate_data(cnum);
-    let get_crate_data = |&mut: cnum| {
+    let get_crate_data = |cnum| {
         cstore.get_crate_data(cnum)
     };
     decoder::each_top_level_item_of_crate(cstore.intr.clone(),
@@ -93,7 +93,7 @@ pub fn get_item_path(tcx: &ty::ctxt, def: ast::DefId) -> Vec<ast_map::PathElem>
     // FIXME #1920: This path is not always correct if the crate is not linked
     // into the root namespace.
     let mut r = vec![ast_map::PathMod(token::intern(&cdata.name[]))];
-    r.push_all(path.as_slice());
+    r.push_all(&path);
     r
 }
 
@@ -383,7 +383,7 @@ pub fn is_staged_api(cstore: &cstore::CStore, def: ast::DefId) -> bool {
     let cdata = cstore.get_crate_data(def.krate);
     let attrs = decoder::get_crate_attributes(cdata.data());
     for attr in &attrs {
-        if attr.name().get() == "staged_api" {
+        if &attr.name()[] == "staged_api" {
             match attr.node.value.node { ast::MetaWord(_) => return true, _ => (/*pass*/) }
         }
     }
index ccd524a2c03955a950b3929a96dae1659de9fffc..ef0c3fbb252fa4e7f12f56595bc95eddfbd2ec74 100644 (file)
@@ -86,11 +86,11 @@ pub struct EncodeContext<'a, 'tcx: 'a> {
 }
 
 fn encode_name(rbml_w: &mut Encoder, name: ast::Name) {
-    rbml_w.wr_tagged_str(tag_paths_data_name, token::get_name(name).get());
+    rbml_w.wr_tagged_str(tag_paths_data_name, &token::get_name(name));
 }
 
 fn encode_impl_type_basename(rbml_w: &mut Encoder, name: ast::Ident) {
-    rbml_w.wr_tagged_str(tag_item_impl_type_basename, token::get_ident(name).get());
+    rbml_w.wr_tagged_str(tag_item_impl_type_basename, &token::get_ident(name));
 }
 
 pub fn encode_def_id(rbml_w: &mut Encoder, id: DefId) {
@@ -372,7 +372,7 @@ fn encode_path<PI: Iterator<Item=PathElem>>(rbml_w: &mut Encoder, path: PI) {
             ast_map::PathMod(_) => tag_path_elem_mod,
             ast_map::PathName(_) => tag_path_elem_name
         };
-        rbml_w.wr_tagged_str(tag, token::get_name(pe.name()).get());
+        rbml_w.wr_tagged_str(tag, &token::get_name(pe.name()));
     }
     rbml_w.end_tag();
 }
@@ -915,7 +915,7 @@ fn encode_method_argument_names(rbml_w: &mut Encoder,
         rbml_w.start_tag(tag_method_argument_name);
         if let ast::PatIdent(_, ref path1, _) = arg.pat.node {
             let name = token::get_ident(path1.node);
-            rbml_w.writer.write_all(name.get().as_bytes());
+            rbml_w.writer.write_all(name.as_bytes());
         }
         rbml_w.end_tag();
     }
@@ -1044,7 +1044,7 @@ fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
         encode_bounds_and_type(rbml_w, ecx, &lookup_item_type(tcx, def_id));
         encode_name(rbml_w, item.ident.name);
         encode_path(rbml_w, path);
-        encode_attributes(rbml_w, item.attrs.as_slice());
+        encode_attributes(rbml_w, &item.attrs);
         encode_inlined_item(ecx, rbml_w, IIItemRef(item));
         encode_visibility(rbml_w, vis);
         encode_stability(rbml_w, stab);
@@ -1307,7 +1307,7 @@ fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
         let trait_def = ty::lookup_trait_def(tcx, def_id);
         encode_unsafety(rbml_w, trait_def.unsafety);
         encode_paren_sugar(rbml_w, trait_def.paren_sugar);
-        encode_associated_type_names(rbml_w, trait_def.associated_type_names.as_slice());
+        encode_associated_type_names(rbml_w, &trait_def.associated_type_names);
         encode_generics(rbml_w, ecx, &trait_def.generics, tag_item_generics);
         encode_trait_ref(rbml_w, ecx, &*trait_def.trait_ref, tag_item_trait_ref);
         encode_name(rbml_w, item.ident.name);
@@ -1409,7 +1409,7 @@ fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
             encode_parent_sort(rbml_w, 't');
 
             let trait_item = &ms[i];
-            let encode_trait_item = |&: rbml_w: &mut Encoder| {
+            let encode_trait_item = |rbml_w: &mut Encoder| {
                 // If this is a static method, we've already
                 // encoded this.
                 if is_nonstatic_method {
@@ -1466,7 +1466,7 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext,
     encode_def_id(rbml_w, local_def(nitem.id));
     encode_visibility(rbml_w, nitem.vis);
     match nitem.node {
-      ast::ForeignItemFn(..) => {
+      ast::ForeignItemFn(ref fndecl, _) => {
         encode_family(rbml_w, FN_FAMILY);
         encode_bounds_and_type(rbml_w, ecx,
                                &lookup_item_type(ecx.tcx,local_def(nitem.id)));
@@ -1478,6 +1478,7 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext,
         let stab = stability::lookup(ecx.tcx, ast_util::local_def(nitem.id));
         encode_stability(rbml_w, stab);
         encode_symbol(ecx, rbml_w, nitem.id);
+        encode_method_argument_names(rbml_w, &*fndecl);
       }
       ast::ForeignItemStatic(_, mutbl) => {
         if mutbl {
@@ -1636,7 +1637,7 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) {
       ast::MetaWord(ref name) => {
         rbml_w.start_tag(tag_meta_item_word);
         rbml_w.start_tag(tag_meta_item_name);
-        rbml_w.writer.write_all(name.get().as_bytes());
+        rbml_w.writer.write_all(name.as_bytes());
         rbml_w.end_tag();
         rbml_w.end_tag();
       }
@@ -1645,10 +1646,10 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) {
           ast::LitStr(ref value, _) => {
             rbml_w.start_tag(tag_meta_item_name_value);
             rbml_w.start_tag(tag_meta_item_name);
-            rbml_w.writer.write_all(name.get().as_bytes());
+            rbml_w.writer.write_all(name.as_bytes());
             rbml_w.end_tag();
             rbml_w.start_tag(tag_meta_item_value);
-            rbml_w.writer.write_all(value.get().as_bytes());
+            rbml_w.writer.write_all(value.as_bytes());
             rbml_w.end_tag();
             rbml_w.end_tag();
           }
@@ -1658,7 +1659,7 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) {
       ast::MetaList(ref name, ref items) => {
         rbml_w.start_tag(tag_meta_item_list);
         rbml_w.start_tag(tag_meta_item_name);
-        rbml_w.writer.write_all(name.get().as_bytes());
+        rbml_w.writer.write_all(name.as_bytes());
         rbml_w.end_tag();
         for inner_item in items {
             encode_meta_item(rbml_w, &**inner_item);
@@ -1695,7 +1696,7 @@ fn encode_paren_sugar(rbml_w: &mut Encoder, paren_sugar: bool) {
 fn encode_associated_type_names(rbml_w: &mut Encoder, names: &[ast::Name]) {
     rbml_w.start_tag(tag_associated_type_names);
     for &name in names {
-        rbml_w.wr_tagged_str(tag_associated_type_name, token::get_name(name).get());
+        rbml_w.wr_tagged_str(tag_associated_type_name, &token::get_name(name));
     }
     rbml_w.end_tag();
 }
index 2fb5a6b64a6520b244f041346fc643b860fa5636..3158ccd076522f76dc9eec476b9122bc09bbadd4 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
@@ -257,6 +257,7 @@ pub struct Context<'a> {
     pub root: &'a Option<CratePaths>,
     pub rejected_via_hash: Vec<CrateMismatch>,
     pub rejected_via_triple: Vec<CrateMismatch>,
+    pub rejected_via_kind: Vec<CrateMismatch>,
     pub should_match_name: bool,
 }
 
@@ -311,6 +312,8 @@ pub fn report_load_errs(&mut self) {
         } else if self.rejected_via_triple.len() > 0 {
             format!("couldn't find crate `{}` with expected target triple {}",
                     self.ident, self.triple)
+        } else if self.rejected_via_kind.len() > 0 {
+            format!("found staticlib `{}` instead of rlib or dylib", self.ident)
         } else {
             format!("can't find crate for `{}`", self.ident)
         };
@@ -335,8 +338,8 @@ pub fn report_load_errs(&mut self) {
             let mismatches = self.rejected_via_hash.iter();
             for (i, &CrateMismatch{ ref path, .. }) in mismatches.enumerate() {
                 self.sess.fileline_note(self.span,
-                    &format!("crate `{}` path {}{}: {}",
-                            self.ident, "#", i+1, path.display())[]);
+                    &format!("crate `{}` path #{}: {}",
+                            self.ident, i+1, path.display())[]);
             }
             match self.root {
                 &None => {}
@@ -349,6 +352,16 @@ pub fn report_load_errs(&mut self) {
                 }
             }
         }
+        if self.rejected_via_kind.len() > 0 {
+            self.sess.span_help(self.span, "please recompile this crate using \
+                                            --crate-type lib");
+            let mismatches = self.rejected_via_kind.iter();
+            for (i, &CrateMismatch { ref path, .. }) in mismatches.enumerate() {
+                self.sess.fileline_note(self.span,
+                                        &format!("crate `{}` path #{}: {}",
+                                                 self.ident, i+1, path.display())[]);
+            }
+        }
         self.sess.abort_if_errors();
     }
 
@@ -357,9 +370,8 @@ fn find_library_crate(&mut self) -> Option<Library> {
         // must be loaded via -L plus some filtering.
         if self.hash.is_none() {
             self.should_match_name = false;
-            match self.find_commandline_library() {
-                Some(l) => return Some(l),
-                None => {}
+            if let Some(s) = self.sess.opts.externs.get(self.crate_name) {
+                return self.find_commandline_library(s);
             }
             self.should_match_name = true;
         }
@@ -369,8 +381,10 @@ fn find_library_crate(&mut self) -> Option<Library> {
         // want: crate_name.dir_part() + prefix + crate_name.file_part + "-"
         let dylib_prefix = format!("{}{}", dypair.0, self.crate_name);
         let rlib_prefix = format!("lib{}", self.crate_name);
+        let staticlib_prefix = format!("lib{}", self.crate_name);
 
         let mut candidates = HashMap::new();
+        let mut staticlibs = vec!();
 
         // First, find all possible candidate rlibs and dylibs purely based on
         // the name of the files themselves. We're trying to match against an
@@ -391,14 +405,21 @@ fn find_library_crate(&mut self) -> Option<Library> {
                 Some(file) => file,
             };
             let (hash, rlib) = if file.starts_with(&rlib_prefix[]) &&
-                    file.ends_with(".rlib") {
+                                  file.ends_with(".rlib") {
                 (&file[(rlib_prefix.len()) .. (file.len() - ".rlib".len())],
                  true)
-            } else if file.starts_with(dylib_prefix.as_slice()) &&
-                      file.ends_with(dypair.1.as_slice()) {
+            } else if file.starts_with(&dylib_prefix) &&
+                      file.ends_with(&dypair.1) {
                 (&file[(dylib_prefix.len()) .. (file.len() - dypair.1.len())],
                  false)
             } else {
+                if file.starts_with(&staticlib_prefix[]) &&
+                   file.ends_with(".a") {
+                    staticlibs.push(CrateMismatch {
+                        path: path.clone(),
+                        got: "static".to_string()
+                    });
+                }
                 return FileDoesntMatch
             };
             info!("lib candidate: {}", path.display());
@@ -415,6 +436,7 @@ fn find_library_crate(&mut self) -> Option<Library> {
 
             FileMatches
         });
+        self.rejected_via_kind.extend(staticlibs.into_iter());
 
         // We have now collected all known libraries into a set of candidates
         // keyed of the filename hash listed. For each filename, we also have a
@@ -596,12 +618,7 @@ fn dylibname(&self) -> (String, String) {
         (t.options.dll_prefix.clone(), t.options.dll_suffix.clone())
     }
 
-    fn find_commandline_library(&mut self) -> Option<Library> {
-        let locs = match self.sess.opts.externs.get(self.crate_name) {
-            Some(s) => s,
-            None => return None,
-        };
-
+    fn find_commandline_library(&mut self, locs: &[String]) -> Option<Library> {
         // First, filter out all libraries that look suspicious. We only accept
         // files which actually exist that have the correct naming scheme for
         // rlibs/dylibs.
@@ -744,8 +761,8 @@ fn get_metadata_section_imp(is_osx: bool, filename: &Path) -> Result<MetadataBlo
         while llvm::LLVMIsSectionIteratorAtEnd(of.llof, si.llsi) == False {
             let mut name_buf = ptr::null();
             let name_len = llvm::LLVMRustGetSectionName(si.llsi, &mut name_buf);
-            let name = slice::from_raw_buf(&(name_buf as *const u8),
-                                           name_len as uint).to_vec();
+            let name = slice::from_raw_parts(name_buf as *const u8,
+                                             name_len as uint).to_vec();
             let name = String::from_utf8(name).unwrap();
             debug!("get_metadata_section: name {}", name);
             if read_meta_section_name(is_osx) == name {
@@ -756,7 +773,7 @@ fn get_metadata_section_imp(is_osx: bool, filename: &Path) -> Result<MetadataBlo
                 debug!("checking {} bytes of metadata-version stamp",
                        vlen);
                 let minsz = cmp::min(vlen, csz);
-                let buf0 = slice::from_raw_buf(&cvbuf, minsz);
+                let buf0 = slice::from_raw_parts(cvbuf, minsz);
                 let version_ok = buf0 == encoder::metadata_encoding_version;
                 if !version_ok {
                     return Err((format!("incompatible metadata version found: '{}'",
@@ -766,7 +783,7 @@ fn get_metadata_section_imp(is_osx: bool, filename: &Path) -> Result<MetadataBlo
                 let cvbuf1 = cvbuf.offset(vlen as int);
                 debug!("inflating {} bytes of compressed metadata",
                        csz - vlen);
-                let bytes = slice::from_raw_buf(&cvbuf1, csz-vlen);
+                let bytes = slice::from_raw_parts(cvbuf1, csz - vlen);
                 match flate::inflate_bytes(bytes) {
                     Some(inflated) => return Ok(MetadataVec(inflated)),
                     None => {}
index 4c0aefaf83d9721863ba1972379c3047b4b7fc18..7cc7e49b6d251a6f04d36588de4a6baef83eb426 100644 (file)
@@ -555,7 +555,7 @@ fn parse_ty_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, conv: &mut F) -> Ty<'tcx> w
       'P' => {
           assert_eq!(next(st), '[');
           let trait_ref = parse_trait_ref_(st, conv);
-          let name = token::intern(parse_str(st, ']').as_slice());
+          let name = token::intern(&parse_str(st, ']'));
           return ty::mk_projection(tcx, trait_ref, name);
       }
       'e' => {
@@ -781,7 +781,7 @@ fn parse_projection_predicate_<'a,'tcx, F>(
     ty::ProjectionPredicate {
         projection_ty: ty::ProjectionTy {
             trait_ref: parse_trait_ref_(st, conv),
-            item_name: token::str_to_ident(parse_str(st, '|').as_slice()).name,
+            item_name: token::str_to_ident(&parse_str(st, '|')).name,
         },
         ty: parse_ty_(st, conv),
     }
index 4130195ae40d1fc0d133587e717f8ed115a37975..b0fe743b683792dc358211967b8701db22d6ed00 100644 (file)
@@ -1185,7 +1185,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
         rbml_w.tag(c::tag_table_freevars, |rbml_w| {
             rbml_w.id(id);
             rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_from_vec(fv.as_slice(), |rbml_w, fv_entry| {
+                rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
                     Ok(encode_freevar_entry(rbml_w, fv_entry))
                 });
             })
index 925bd5b6395beea35e6a2b718cb4410563c69b61..b558f838a51cba5d86f0caed48ddafe6922459d5 100644 (file)
@@ -138,7 +138,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) {
         ast::ExprBlock(ref block) => {
             // Check all statements in the block
             for stmt in &block.stmts {
-                let block_span_err = |&: span|
+                let block_span_err = |span|
                     span_err!(v.tcx.sess, span, E0016,
                               "blocks in constants are limited to items and \
                                tail expressions");
index 38084d1c2c06fe42aa067491284e23e4a7a5707c..7ac690f02e1b585c7c21391113a760967ffd7f38 100644 (file)
@@ -28,7 +28,7 @@
 use std::num::Float;
 use std::slice;
 use syntax::ast::{self, DUMMY_NODE_ID, NodeId, Pat};
-use syntax::ast_util::walk_pat;
+use syntax::ast_util;
 use syntax::codemap::{Span, Spanned, DUMMY_SP};
 use syntax::fold::{Folder, noop_fold_pat};
 use syntax::print::pprust::pat_to_string;
@@ -36,6 +36,7 @@
 use syntax::ptr::P;
 use syntax::visit::{self, Visitor, FnKind};
 use util::ppaux::ty_to_string;
+use util::nodemap::FnvHashMap;
 
 pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
     id: DUMMY_NODE_ID,
@@ -171,7 +172,7 @@ fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) {
                 }
             }
 
-            let mut static_inliner = StaticInliner::new(cx.tcx);
+            let mut static_inliner = StaticInliner::new(cx.tcx, None);
             let inlined_arms = arms.iter().map(|arm| {
                 (arm.pats.iter().map(|pat| {
                     static_inliner.fold_pat((*pat).clone())
@@ -235,7 +236,7 @@ fn is_expr_const_nan(tcx: &ty::ctxt, expr: &ast::Expr) -> bool {
 }
 
 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
-    walk_pat(pat, |p| {
+    ast_util::walk_pat(pat, |p| {
         match p.node {
             ast::PatIdent(ast::BindByValue(ast::MutImmutable), ident, None) => {
                 let pat_ty = ty::pat_ty(cx.tcx, p);
@@ -249,11 +250,11 @@ fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat)
                             span_warn!(cx.tcx.sess, p.span, E0170,
                                 "pattern binding `{}` is named the same as one \
                                  of the variants of the type `{}`",
-                                token::get_ident(ident.node).get(), ty_to_string(cx.tcx, pat_ty));
+                                &token::get_ident(ident.node), ty_to_string(cx.tcx, pat_ty));
                             span_help!(cx.tcx.sess, p.span,
                                 "if you meant to match on a variant, \
                                  consider making the path in the pattern qualified: `{}::{}`",
-                                ty_to_string(cx.tcx, pat_ty), token::get_ident(ident.node).get());
+                                ty_to_string(cx.tcx, pat_ty), &token::get_ident(ident.node));
                         }
                     }
                 }
@@ -266,7 +267,7 @@ fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat)
 
 // Check that we do not match against a static NaN (#6804)
 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
-    walk_pat(pat, |p| {
+    ast_util::walk_pat(pat, |p| {
         match p.node {
             ast::PatLit(ref expr) if is_expr_const_nan(cx.tcx, &**expr) => {
                 span_warn!(cx.tcx.sess, p.span, E0003,
@@ -399,28 +400,50 @@ fn const_val_to_expr(value: &const_val) -> P<ast::Expr> {
 
 pub struct StaticInliner<'a, 'tcx: 'a> {
     pub tcx: &'a ty::ctxt<'tcx>,
-    pub failed: bool
+    pub failed: bool,
+    pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
 }
 
 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
-    pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>) -> StaticInliner<'b, 'tcx> {
+    pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>,
+                   renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
+                   -> StaticInliner<'b, 'tcx> {
         StaticInliner {
             tcx: tcx,
-            failed: false
+            failed: false,
+            renaming_map: renaming_map
         }
     }
 }
 
+struct RenamingRecorder<'map> {
+    substituted_node_id: NodeId,
+    origin_span: Span,
+    renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
+}
+
+impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> {
+    fn visit_id(&mut self, node_id: NodeId) {
+        let key = (node_id, self.origin_span);
+        self.renaming_map.insert(key, self.substituted_node_id);
+    }
+}
+
 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
     fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
-        match pat.node {
+        return match pat.node {
             ast::PatIdent(..) | ast::PatEnum(..) => {
                 let def = self.tcx.def_map.borrow().get(&pat.id).cloned();
                 match def {
                     Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did) {
                         Some(const_expr) => {
-                            const_expr_to_pat(self.tcx, const_expr).map(|mut new_pat| {
-                                new_pat.span = pat.span;
+                            const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| {
+
+                                if let Some(ref mut renaming_map) = self.renaming_map {
+                                    // Record any renamings we do here
+                                    record_renamings(const_expr, &pat, renaming_map);
+                                }
+
                                 new_pat
                             })
                         }
@@ -435,6 +458,24 @@ fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
                 }
             }
             _ => noop_fold_pat(pat, self)
+        };
+
+        fn record_renamings(const_expr: &ast::Expr,
+                            substituted_pat: &ast::Pat,
+                            renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
+            let mut renaming_recorder = RenamingRecorder {
+                substituted_node_id: substituted_pat.id,
+                origin_span: substituted_pat.span,
+                renaming_map: renaming_map,
+            };
+
+            let mut id_visitor = ast_util::IdVisitor {
+                operation: &mut renaming_recorder,
+                pass_through_items: true,
+                visited_outermost: false,
+            };
+
+            id_visitor.visit_expr(const_expr);
         }
     }
 }
@@ -953,7 +994,7 @@ fn check_local(cx: &mut MatchCheckCtxt, loc: &ast::Local) {
         ast::LocalFor => "`for` loop"
     };
 
-    let mut static_inliner = StaticInliner::new(cx.tcx);
+    let mut static_inliner = StaticInliner::new(cx.tcx, None);
     is_refutable(cx, &*static_inliner.fold_pat(loc.pat.clone()), |pat| {
         span_err!(cx.tcx.sess, loc.pat.span, E0005,
             "refutable pattern in {} binding: `{}` not covered",
@@ -1024,7 +1065,7 @@ fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
         })
     }
 
-    let check_move = |&: p: &Pat, sub: Option<&Pat>| {
+    let check_move = |p: &Pat, sub: Option<&Pat>| {
         // check legality of moving out of the enum
 
         // x @ Foo(..) is legal, but x @ Foo(y) isn't.
@@ -1040,7 +1081,7 @@ fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
     };
 
     for pat in pats {
-        walk_pat(&**pat, |p| {
+        ast_util::walk_pat(&**pat, |p| {
             if pat_is_binding(def_map, &*p) {
                 match p.node {
                     ast::PatIdent(ast::BindByValue(_), _, ref sub) => {
index fa5d5227be535394e135d200740ec5b462011969..a6a647173faa724f40165237a3f841f2af462b31 100644 (file)
@@ -22,6 +22,7 @@
 use util::nodemap::DefIdMap;
 
 use syntax::ast::{self, Expr};
+use syntax::codemap::Span;
 use syntax::parse::token::InternedString;
 use syntax::ptr::P;
 use syntax::visit::{self, Visitor};
@@ -304,10 +305,10 @@ pub enum const_val {
     const_bool(bool)
 }
 
-pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr) -> P<ast::Pat> {
+pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr, span: Span) -> P<ast::Pat> {
     let pat = match expr.node {
         ast::ExprTup(ref exprs) =>
-            ast::PatTup(exprs.iter().map(|expr| const_expr_to_pat(tcx, &**expr)).collect()),
+            ast::PatTup(exprs.iter().map(|expr| const_expr_to_pat(tcx, &**expr, span)).collect()),
 
         ast::ExprCall(ref callee, ref args) => {
             let def = tcx.def_map.borrow()[callee.id].clone();
@@ -319,7 +320,7 @@ pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr) -> P<ast::Pat> {
                 def::DefVariant(_, variant_did, _) => def_to_path(tcx, variant_did),
                 _ => unreachable!()
             };
-            let pats = args.iter().map(|expr| const_expr_to_pat(tcx, &**expr)).collect();
+            let pats = args.iter().map(|expr| const_expr_to_pat(tcx, &**expr, span)).collect();
             ast::PatEnum(path, Some(pats))
         }
 
@@ -328,7 +329,7 @@ pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr) -> P<ast::Pat> {
                 span: codemap::DUMMY_SP,
                 node: ast::FieldPat {
                     ident: field.ident.node,
-                    pat: const_expr_to_pat(tcx, &*field.expr),
+                    pat: const_expr_to_pat(tcx, &*field.expr, span),
                     is_shorthand: false,
                 },
             }).collect();
@@ -336,7 +337,7 @@ pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr) -> P<ast::Pat> {
         }
 
         ast::ExprVec(ref exprs) => {
-            let pats = exprs.iter().map(|expr| const_expr_to_pat(tcx, &**expr)).collect();
+            let pats = exprs.iter().map(|expr| const_expr_to_pat(tcx, &**expr, span)).collect();
             ast::PatVec(pats, None, vec![])
         }
 
@@ -349,7 +350,7 @@ pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr) -> P<ast::Pat> {
                     ast::PatEnum(path.clone(), None),
                 _ => {
                     match lookup_const(tcx, expr) {
-                        Some(actual) => return const_expr_to_pat(tcx, actual),
+                        Some(actual) => return const_expr_to_pat(tcx, actual, span),
                         _ => unreachable!()
                     }
                 }
@@ -358,14 +359,14 @@ pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr) -> P<ast::Pat> {
 
         ast::ExprQPath(_) => {
             match lookup_const(tcx, expr) {
-                Some(actual) => return const_expr_to_pat(tcx, actual),
+                Some(actual) => return const_expr_to_pat(tcx, actual, span),
                 _ => unreachable!()
             }
         }
 
         _ => ast::PatLit(P(expr.clone()))
     };
-    P(ast::Pat { id: expr.id, node: pat, span: expr.span })
+    P(ast::Pat { id: expr.id, node: pat, span: span })
 }
 
 pub fn eval_const_expr(tcx: &ty::ctxt, e: &Expr) -> const_val {
@@ -610,7 +611,7 @@ pub fn lit_to_const(lit: &ast::Lit) -> const_val {
         ast::LitInt(n, ast::UnsignedIntLit(_)) => const_uint(n),
         ast::LitFloat(ref n, _) |
         ast::LitFloatUnsuffixed(ref n) => {
-            const_float(n.get().parse::<f64>().unwrap() as f64)
+            const_float(n.parse::<f64>().unwrap() as f64)
         }
         ast::LitBool(b) => const_bool(b)
     }
index 8f5906db589003dd27aaa7292e796b6c258e6921..7ba83c62496f368cd8bf6dee9f9071faae273c03 100644 (file)
@@ -310,7 +310,7 @@ pub fn each_bit_for_node<F>(&self, e: EntryOrExit, cfgidx: CFGIndex, f: F) -> bo
             Entry => on_entry,
             Exit => {
                 let mut t = on_entry.to_vec();
-                self.apply_gen_kill(cfgidx, t.as_mut_slice());
+                self.apply_gen_kill(cfgidx, &mut t);
                 temp_bits = t;
                 &temp_bits[]
             }
@@ -405,7 +405,7 @@ pub fn add_kills_from_flow_exits(&mut self, cfg: &cfg::CFG) {
                     Some(cfg_idx) => {
                         let (start, end) = self.compute_id_range(cfg_idx);
                         let kills = &self.kills[start.. end];
-                        if bitwise(orig_kills.as_mut_slice(), kills, &Union) {
+                        if bitwise(&mut orig_kills, kills, &Union) {
                             changed = true;
                         }
                     }
@@ -450,8 +450,8 @@ pub fn propagate(&mut self, cfg: &cfg::CFG, blk: &ast::Block) {
             let mut temp: Vec<_> = repeat(0).take(words_per_id).collect();
             while propcx.changed {
                 propcx.changed = false;
-                propcx.reset(temp.as_mut_slice());
-                propcx.walk_cfg(cfg, temp.as_mut_slice());
+                propcx.reset(&mut temp);
+                propcx.walk_cfg(cfg, &mut temp);
             }
         }
 
index 4478e3270874dc43b8642a64b563f260d40afb68..a157d5d712b58759032dc29ab196277c0742fc85 100644 (file)
@@ -287,7 +287,7 @@ fn visit_pat(&mut self, pat: &ast::Pat) {
         let def_map = &self.tcx.def_map;
         match pat.node {
             ast::PatStruct(_, ref fields, _) => {
-                self.handle_field_pattern_match(pat, fields.as_slice());
+                self.handle_field_pattern_match(pat, fields);
             }
             _ if pat_util::pat_is_const(def_map, pat) => {
                 // it might be the only use of a const
@@ -313,7 +313,7 @@ fn visit_item(&mut self, _: &ast::Item) {
 }
 
 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
-    if attr::contains_name(attrs.as_slice(), "lang") {
+    if attr::contains_name(attrs, "lang") {
         return true;
     }
 
@@ -321,7 +321,7 @@ fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
     for attr in lint::gather_attrs(attrs) {
         match attr {
             Ok((ref name, lint::Allow, _))
-                if name.get() == dead_code => return true,
+                if &name[] == dead_code => return true,
             _ => (),
         }
     }
@@ -347,7 +347,7 @@ struct LifeSeeder {
 
 impl<'v> Visitor<'v> for LifeSeeder {
     fn visit_item(&mut self, item: &ast::Item) {
-        let allow_dead_code = has_allow_dead_code_or_lang_attr(item.attrs.as_slice());
+        let allow_dead_code = has_allow_dead_code_or_lang_attr(&item.attrs);
         if allow_dead_code {
             self.worklist.push(item.id);
         }
@@ -376,7 +376,7 @@ fn visit_fn(&mut self, fk: visit::FnKind<'v>,
         // Check for method here because methods are not ast::Item
         match fk {
             visit::FkMethod(_, _, method) => {
-                if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) {
+                if has_allow_dead_code_or_lang_attr(&method.attrs) {
                     self.worklist.push(id);
                 }
             }
@@ -467,12 +467,12 @@ fn should_warn_about_field(&mut self, node: &ast::StructField_) -> bool {
         is_named
             && !self.symbol_is_live(node.id, None)
             && !is_marker_field
-            && !has_allow_dead_code_or_lang_attr(node.attrs.as_slice())
+            && !has_allow_dead_code_or_lang_attr(&node.attrs)
     }
 
     fn should_warn_about_variant(&mut self, variant: &ast::Variant_) -> bool {
         !self.symbol_is_live(variant.id, None)
-            && !has_allow_dead_code_or_lang_attr(variant.attrs.as_slice())
+            && !has_allow_dead_code_or_lang_attr(&variant.attrs)
     }
 
     // id := node id of an item's definition.
index 24073848edf541eb353b03563a231d3be6e613c8..0ce9db1c80f3f21c4741083a46e983a4bb37ea23 100644 (file)
@@ -56,7 +56,7 @@ pub fn find_entry_point(session: &Session, ast_map: &ast_map::Map) {
     }
 
     // If the user wants no main function at all, then stop here.
-    if attr::contains_name(ast_map.krate().attrs.as_slice(), "no_main") {
+    if attr::contains_name(&ast_map.krate().attrs, "no_main") {
         session.entry_type.set(Some(config::EntryNone));
         return
     }
@@ -96,7 +96,7 @@ fn find_item(item: &Item, ctxt: &mut EntryContext) {
                 });
             }
 
-            if attr::contains_name(item.attrs.as_slice(), "main") {
+            if attr::contains_name(&item.attrs, "main") {
                 if ctxt.attr_main_fn.is_none() {
                     ctxt.attr_main_fn = Some((item.id, item.span));
                 } else {
@@ -105,7 +105,7 @@ fn find_item(item: &Item, ctxt: &mut EntryContext) {
                 }
             }
 
-            if attr::contains_name(item.attrs.as_slice(), "start") {
+            if attr::contains_name(&item.attrs, "start") {
                 if ctxt.start_fn.is_none() {
                     ctxt.start_fn = Some((item.id, item.span));
                 } else {
index 44a816eb2f803c330e7ce9661eae3cd6d4d52a81..5cc7502b5128d3e2674769732670dec36c0ea0c1 100644 (file)
@@ -639,8 +639,7 @@ fn walk_callee(&mut self, call: &ast::Expr, callee: &ast::Expr) {
                         None => {
                             self.tcx().sess.span_bug(
                                 callee.span,
-                                format!("unexpected callee type {}",
-                                        callee_ty.repr(self.tcx())).as_slice())
+                                &format!("unexpected callee type {}", callee_ty.repr(self.tcx())))
                         }
                     };
                 match overloaded_call_type {
@@ -1150,7 +1149,7 @@ fn walk_pat(&mut self,
                                 let msg = format!("Pattern has unexpected type: {:?} and type {}",
                                                   def,
                                                   cmt_pat.ty.repr(tcx));
-                                tcx.sess.span_bug(pat.span, msg.as_slice())
+                                tcx.sess.span_bug(pat.span, &msg)
                             }
                         }
 
index aca4b3df453676f7794fff3222cbf8ed707f7d92..989efdd235dffe76fd4cfd545404a46c06618c3d 100644 (file)
@@ -112,14 +112,12 @@ pub fn with_capacity(num_nodes: uint,
 
     #[inline]
     pub fn all_nodes<'a>(&'a self) -> &'a [Node<N>] {
-        let nodes: &'a [Node<N>] = self.nodes.as_slice();
-        nodes
+        &self.nodes
     }
 
     #[inline]
     pub fn all_edges<'a>(&'a self) -> &'a [Edge<E>] {
-        let edges: &'a [Edge<E>] = self.edges.as_slice();
-        edges
+        &self.edges
     }
 
     ///////////////////////////////////////////////////////////////////////////
index 8cb2774f7dff8290ebba032426df06f65eda5b83..daa820f43b57ec186aa67ae79ae2d5d587a14214 100644 (file)
@@ -208,8 +208,8 @@ fn fn_sigs(&self, a: &ty::FnSig<'tcx>, b: &ty::FnSig<'tcx>) -> cres<'tcx, ty::Fn
         }
 
         let inputs = try!(argvecs(self,
-                                  a.inputs.as_slice(),
-                                  b.inputs.as_slice()));
+                                  &a.inputs,
+                                  &b.inputs));
 
         let output = try!(match (a.output, b.output) {
             (ty::FnConverging(a_ty), ty::FnConverging(b_ty)) =>
index 17b62e463dae3d17ec2d3428707e7f9bbdd8fa88..99896535442d81363f00d01d88ea58ce0bd132e6 100644 (file)
@@ -514,7 +514,6 @@ fn report_concrete_failure(&self,
                             lifetime of captured variable `{}`...",
                             ty::local_var_name_str(self.tcx,
                                                    upvar_id.var_id)
-                                .get()
                                 .to_string());
                 note_and_explain_region(
                     self.tcx,
@@ -526,7 +525,6 @@ fn report_concrete_failure(&self,
                     &format!("...but `{}` is only valid for ",
                             ty::local_var_name_str(self.tcx,
                                                    upvar_id.var_id)
-                                .get()
                                 .to_string())[],
                     sup,
                     "");
@@ -570,8 +568,7 @@ fn report_concrete_failure(&self,
                     &format!("captured variable `{}` does not \
                             outlive the enclosing closure",
                             ty::local_var_name_str(self.tcx,
-                                                   id).get()
-                                                      .to_string())[]);
+                                                   id).to_string())[]);
                 note_and_explain_region(
                     self.tcx,
                     "captured variable is valid for ",
@@ -959,7 +956,7 @@ fn pick_lifetime(&self,
             // choice of lifetime name deterministic and thus easier to test.
             let mut names = Vec::new();
             for rn in region_names {
-                let lt_name = token::get_name(*rn).get().to_string();
+                let lt_name = token::get_name(*rn).to_string();
                 names.push(lt_name);
             }
             names.sort();
@@ -1079,7 +1076,8 @@ fn rebuild_ty_param_bounds(&self,
                         trait_ref: ast::TraitRef {
                             path: new_path,
                             ref_id: tr.ref_id,
-                        }
+                        },
+                        span: poly_tr.span,
                     }, modifier)
                 }
             }
@@ -1438,15 +1436,15 @@ fn report_inference_failure(&self,
             }
             infer::EarlyBoundRegion(_, name) => {
                 format!(" for lifetime parameter `{}`",
-                        token::get_name(name).get())
+                        &token::get_name(name))
             }
             infer::BoundRegionInCoherence(name) => {
                 format!(" for lifetime parameter `{}` in coherence check",
-                        token::get_name(name).get())
+                        &token::get_name(name))
             }
             infer::UpvarRegion(ref upvar_id, _) => {
                 format!(" for capture of `{}` by closure",
-                        ty::local_var_name_str(self.tcx, upvar_id.var_id).get().to_string())
+                        ty::local_var_name_str(self.tcx, upvar_id.var_id).to_string())
             }
         };
 
@@ -1527,7 +1525,6 @@ fn note_region_origin(&self, origin: &SubregionOrigin<'tcx>) {
                     &format!(
                         "...so that closure can access `{}`",
                         ty::local_var_name_str(self.tcx, upvar_id.var_id)
-                            .get()
                             .to_string())[])
             }
             infer::InfStackClosure(span) => {
@@ -1553,7 +1550,7 @@ fn note_region_origin(&self, origin: &SubregionOrigin<'tcx>) {
                             does not outlive the enclosing closure",
                             ty::local_var_name_str(
                                 self.tcx,
-                                id).get().to_string())[]);
+                                id).to_string())[]);
             }
             infer::IndexSlice(span) => {
                 self.tcx.sess.span_note(
@@ -1707,7 +1704,7 @@ fn lifetimes_in_scope(tcx: &ty::ctxt,
             Some(node) => match node {
                 ast_map::NodeItem(item) => match item.node {
                     ast::ItemImpl(_, _, ref gen, _, _, _) => {
-                        taken.push_all(gen.lifetimes.as_slice());
+                        taken.push_all(&gen.lifetimes);
                     }
                     _ => ()
                 },
@@ -1730,7 +1727,7 @@ impl LifeGiver {
     fn with_taken(taken: &[ast::LifetimeDef]) -> LifeGiver {
         let mut taken_ = HashSet::new();
         for lt in taken {
-            let lt_name = token::get_name(lt.lifetime.name).get().to_string();
+            let lt_name = token::get_name(lt.lifetime.name).to_string();
             taken_.insert(lt_name);
         }
         LifeGiver {
index 8e9911aaefa0a5d3fc673893912c2973a08317e1..1b7e6c33c0575f723d341ec8373005765a0c5147 100644 (file)
@@ -127,10 +127,10 @@ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
             ty::ty_infer(ty::FreshIntTy(c)) => {
                 if c >= self.freshen_count {
                     self.tcx().sess.bug(
-                        format!("Encountered a freshend type with id {} \
-                                 but our counter is only at {}",
-                                c,
-                                self.freshen_count).as_slice());
+                        &format!("Encountered a freshend type with id {} \
+                                  but our counter is only at {}",
+                                 c,
+                                 self.freshen_count));
                 }
                 t
             }
index e4eecd919c82b8245d6dbf106d65316f82062729..4469e27a5b05af10e8e56825a2af5e1d02899e4c 100644 (file)
@@ -133,7 +133,7 @@ fn higher_ranked_lub<T>(&self, a: &Binder<T>, b: &Binder<T>) -> cres<'tcx, Binde
                     self.tcx(),
                     &result0,
                     |r, debruijn| generalize_region(self.infcx(), span, snapshot, debruijn,
-                                                    new_vars.as_slice(), &a_map, r));
+                                                    &new_vars, &a_map, r));
 
             debug!("lub({},{}) = {}",
                    a.repr(self.tcx()),
@@ -227,8 +227,8 @@ fn higher_ranked_glb<T>(&self, a: &Binder<T>, b: &Binder<T>) -> cres<'tcx, Binde
                     self.tcx(),
                     &result0,
                     |r, debruijn| generalize_region(self.infcx(), span, snapshot, debruijn,
-                                                    new_vars.as_slice(),
-                                                    &a_map, a_vars.as_slice(), b_vars.as_slice(),
+                                                    &new_vars,
+                                                    &a_map, &a_vars, &b_vars,
                                                     r));
 
             debug!("glb({},{}) = {}",
index 87ea5436dab6b545662d33faec5b9a0fed89ed7a..362919755c35d74ab6a3cf2fee8a06ff2ce5be23 100644 (file)
 use graphviz as dot;
 
 use middle::ty;
+use middle::region::CodeExtent;
 use super::Constraint;
 use middle::infer::SubregionOrigin;
 use middle::infer::region_inference::RegionVarBindings;
 use util::nodemap::{FnvHashMap, FnvHashSet};
 use util::ppaux::Repr;
 
+use std::borrow::Cow;
 use std::collections::hash_map::Entry::Vacant;
 use std::old_io::{self, File};
 use std::env;
@@ -71,7 +73,7 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
 
     let output_path = {
         let output_template = match requested_output {
-            Some(ref s) if s.as_slice() == "help" => {
+            Some(ref s) if &**s == "help" => {
                 static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT;
                 if !PRINTED_YET.load(Ordering::SeqCst) {
                     print_help_message();
@@ -92,7 +94,7 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
             let mut new_str = String::new();
             for c in output_template.chars() {
                 if c == '%' {
-                    new_str.push_str(subject_node.to_string().as_slice());
+                    new_str.push_str(&subject_node.to_string());
                 } else {
                     new_str.push(c);
                 }
@@ -104,11 +106,11 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
     };
 
     let constraints = &*region_vars.constraints.borrow();
-    match dump_region_constraints_to(tcx, constraints, output_path.as_slice()) {
+    match dump_region_constraints_to(tcx, constraints, &output_path) {
         Ok(()) => {}
         Err(e) => {
             let msg = format!("io error dumping region constraints: {}", e);
-            region_vars.tcx.sess.err(msg.as_slice())
+            region_vars.tcx.sess.err(&msg)
         }
     }
 }
@@ -120,13 +122,18 @@ struct ConstraintGraph<'a, 'tcx: 'a> {
     node_ids: FnvHashMap<Node, uint>,
 }
 
-#[derive(Clone, Hash, PartialEq, Eq, Debug)]
+#[derive(Clone, Hash, PartialEq, Eq, Debug, Copy)]
 enum Node {
     RegionVid(ty::RegionVid),
     Region(ty::Region),
 }
 
-type Edge = Constraint;
+// type Edge = Constraint;
+#[derive(Clone, PartialEq, Eq, Debug, Copy)]
+enum Edge {
+    Constraint(Constraint),
+    EnclScope(CodeExtent, CodeExtent),
+}
 
 impl<'a, 'tcx> ConstraintGraph<'a, 'tcx> {
     fn new(tcx: &'a ty::ctxt<'tcx>,
@@ -135,7 +142,7 @@ fn new(tcx: &'a ty::ctxt<'tcx>,
         let mut i = 0;
         let mut node_ids = FnvHashMap();
         {
-            let mut add_node = |&mut : node| {
+            let mut add_node = |node| {
                 if let Vacant(e) = node_ids.entry(node) {
                     e.insert(i);
                     i += 1;
@@ -146,6 +153,11 @@ fn new(tcx: &'a ty::ctxt<'tcx>,
                 add_node(n1);
                 add_node(n2);
             }
+
+            tcx.region_maps.each_encl_scope(|sub, sup| {
+                add_node(Node::Region(ty::ReScope(*sub)));
+                add_node(Node::Region(ty::ReScope(*sup)));
+            });
         }
 
         ConstraintGraph { tcx: tcx,
@@ -157,10 +169,20 @@ fn new(tcx: &'a ty::ctxt<'tcx>,
 
 impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> {
     fn graph_id(&self) -> dot::Id {
-        dot::Id::new(self.graph_name.as_slice()).ok().unwrap()
+        dot::Id::new(&*self.graph_name).ok().unwrap()
     }
     fn node_id(&self, n: &Node) -> dot::Id {
-        dot::Id::new(format!("node_{}", self.node_ids.get(n).unwrap())).ok().unwrap()
+        let node_id = match self.node_ids.get(n) {
+            Some(node_id) => node_id,
+            None => panic!("no node_id found for node: {:?}", n),
+        };
+        let name = || format!("node_{}", node_id);
+        match dot::Id::new(name()) {
+            Ok(id) => id,
+            Err(_) => {
+                panic!("failed to create graphviz node identified by {}", name());
+            }
+        }
     }
     fn node_label(&self, n: &Node) -> dot::LabelText {
         match *n {
@@ -171,7 +193,12 @@ fn node_label(&self, n: &Node) -> dot::LabelText {
         }
     }
     fn edge_label(&self, e: &Edge) -> dot::LabelText {
-        dot::LabelText::label(format!("{}", self.map.get(e).unwrap().repr(self.tcx)))
+        match *e {
+            Edge::Constraint(ref c) =>
+                dot::LabelText::label(format!("{}", self.map.get(c).unwrap().repr(self.tcx))),
+            Edge::EnclScope(..) =>
+                dot::LabelText::label(format!("(enclosed)")),
+        }
     }
 }
 
@@ -186,28 +213,40 @@ fn constraint_to_nodes(c: &Constraint) -> (Node, Node) {
     }
 }
 
+fn edge_to_nodes(e: &Edge) -> (Node, Node) {
+    match *e {
+        Edge::Constraint(ref c) => constraint_to_nodes(c),
+        Edge::EnclScope(sub, sup) => {
+            (Node::Region(ty::ReScope(sub)), Node::Region(ty::ReScope(sup)))
+        }
+    }
+}
+
 impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> {
     fn nodes(&self) -> dot::Nodes<Node> {
         let mut set = FnvHashSet();
-        for constraint in self.map.keys() {
-            let (n1, n2) = constraint_to_nodes(constraint);
-            set.insert(n1);
-            set.insert(n2);
+        for node in self.node_ids.keys() {
+            set.insert(*node);
         }
         debug!("constraint graph has {} nodes", set.len());
         set.into_iter().collect()
     }
     fn edges(&self) -> dot::Edges<Edge> {
         debug!("constraint graph has {} edges", self.map.len());
-        self.map.keys().map(|e|*e).collect()
+        let mut v : Vec<_> = self.map.keys().map(|e| Edge::Constraint(*e)).collect();
+        self.tcx.region_maps.each_encl_scope(|sub, sup| {
+            v.push(Edge::EnclScope(*sub, *sup))
+        });
+        debug!("region graph has {} edges", v.len());
+        Cow::Owned(v)
     }
     fn source(&self, edge: &Edge) -> Node {
-        let (n1, _) = constraint_to_nodes(edge);
+        let (n1, _) = edge_to_nodes(edge);
         debug!("edge {:?} has source {:?}", edge, n1);
         n1
     }
     fn target(&self, edge: &Edge) -> Node {
-        let (_, n2) = constraint_to_nodes(edge);
+        let (_, n2) = edge_to_nodes(edge);
         debug!("edge {:?} has target {:?}", edge, n2);
         n2
     }
index 919ea0a25202c5ed5a4f1246e2d2f4e1e07f1b4c..1a7308a4f1885e9165ec7589822c02bc93a0976f 100644 (file)
@@ -224,7 +224,6 @@ pub struct RegionVarBindings<'a, 'tcx: 'a> {
 }
 
 #[derive(Debug)]
-#[allow(missing_copy_implementations)]
 pub struct RegionSnapshot {
     length: uint,
     skolemization_count: u32,
@@ -973,8 +972,8 @@ fn infer_variable_values(&self,
         debug!("----() End constraint listing {:?}---", self.dump_constraints());
         graphviz::maybe_print_constraints_for(self, subject);
 
-        self.expansion(var_data.as_mut_slice());
-        self.contraction(var_data.as_mut_slice());
+        self.expansion(&mut var_data);
+        self.contraction(&mut var_data);
         let values =
             self.extract_values_and_collect_conflicts(&var_data[],
                                                       errors);
@@ -1303,12 +1302,12 @@ fn extract_values_and_collect_conflicts(
                     match var_data[idx].classification {
                         Expanding => {
                             self.collect_error_for_expanding_node(
-                                graph, var_data, dup_vec.as_mut_slice(),
+                                graph, var_data, &mut dup_vec,
                                 node_vid, errors);
                         }
                         Contracting => {
                             self.collect_error_for_contracting_node(
-                                graph, var_data, dup_vec.as_mut_slice(),
+                                graph, var_data, &mut dup_vec,
                                 node_vid, errors);
                         }
                     }
index d9b90c1935a396058540d43958e475542b5300d7..05969d4ea4398564863a576851fa188ebb58684c 100644 (file)
@@ -147,9 +147,9 @@ struct LanguageItemCollector<'a> {
 
 impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
     fn visit_item(&mut self, item: &ast::Item) {
-        match extract(item.attrs.as_slice()) {
+        match extract(&item.attrs) {
             Some(value) => {
-                let item_index = self.item_refs.get(value.get()).map(|x| *x);
+                let item_index = self.item_refs.get(&value[]).map(|x| *x);
 
                 match item_index {
                     Some(item_index) => {
index c0fabb2a3481d7c622145e6ec939388e7f49ee40..fcc5d70a7a564b327203e6cf03966d308ad7d2ea 100644 (file)
@@ -333,7 +333,7 @@ fn variable(&self, node_id: NodeId, span: Span) -> Variable {
     fn variable_name(&self, var: Variable) -> String {
         match self.var_kinds[var.get()] {
             Local(LocalInfo { ident: nm, .. }) | Arg(_, nm) => {
-                token::get_ident(nm).get().to_string()
+                token::get_ident(nm).to_string()
             },
             ImplicitRet => "<implicit-ret>".to_string(),
             CleanExit => "<clean-exit>".to_string()
index 156ff43e2bab3c690e1e491c6d33ace9dfef276f..58492c817fd0b7ba000882a9a9aa64942dd6ab46 100644 (file)
@@ -128,7 +128,7 @@ pub enum PointerKind {
 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
 pub enum InteriorKind {
     InteriorField(FieldName),
-    InteriorElement(ElementKind),
+    InteriorElement(InteriorOffsetKind, ElementKind),
 }
 
 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
@@ -137,6 +137,12 @@ pub enum FieldName {
     PositionalField(uint)
 }
 
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub enum InteriorOffsetKind {
+    Index,            // e.g. `array_expr[index_expr]`
+    Pattern,          // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
+}
+
 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
 pub enum ElementKind {
     VecElement,
@@ -196,10 +202,12 @@ pub enum deref_kind {
     deref_interior(InteriorKind),
 }
 
+type DerefKindContext = Option<InteriorOffsetKind>;
+
 // Categorizes a derefable type.  Note that we include vectors and strings as
 // derefable (we model an index as the combination of a deref and then a
 // pointer adjustment).
-pub fn deref_kind(t: Ty) -> McResult<deref_kind> {
+fn deref_kind(t: Ty, context: DerefKindContext) -> McResult<deref_kind> {
     match t.sty {
         ty::ty_uniq(_) => {
             Ok(deref_ptr(Unique))
@@ -220,7 +228,12 @@ pub fn deref_kind(t: Ty) -> McResult<deref_kind> {
         }
 
         ty::ty_vec(_, _) | ty::ty_str => {
-            Ok(deref_interior(InteriorElement(element_kind(t))))
+            // no deref of indexed content without supplying InteriorOffsetKind
+            if let Some(context) = context {
+                Ok(deref_interior(InteriorElement(context, element_kind(t))))
+            } else {
+                Err(())
+            }
         }
 
         _ => Err(()),
@@ -455,7 +468,7 @@ pub fn cat_expr_autoderefd(&self,
                autoderefs,
                cmt.repr(self.tcx()));
         for deref in 1..autoderefs + 1 {
-            cmt = try!(self.cat_deref(expr, cmt, deref));
+            cmt = try!(self.cat_deref(expr, cmt, deref, None));
         }
         return Ok(cmt);
     }
@@ -467,7 +480,7 @@ pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
         match expr.node {
           ast::ExprUnary(ast::UnDeref, ref e_base) => {
             let base_cmt = try!(self.cat_expr(&**e_base));
-            self.cat_deref(expr, base_cmt, 0)
+            self.cat_deref(expr, base_cmt, 0, None)
           }
 
           ast::ExprField(ref base, f_name) => {
@@ -486,6 +499,7 @@ pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
 
           ast::ExprIndex(ref base, _) => {
             let method_call = ty::MethodCall::expr(expr.id());
+            let context = InteriorOffsetKind::Index;
             match self.typer.node_method_ty(method_call) {
                 Some(method_ty) => {
                     // If this is an index implemented by a method call, then it
@@ -507,10 +521,10 @@ pub fn cat_expr_unadjusted(&self, expr: &ast::Expr) -> McResult<cmt<'tcx>> {
                     // is an rvalue. That is what we will be
                     // dereferencing.
                     let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty);
-                    self.cat_deref_common(expr, base_cmt, 1, elem_ty, true)
+                    self.cat_deref_common(expr, base_cmt, 1, elem_ty, Some(context), true)
                 }
                 None => {
-                    self.cat_index(expr, try!(self.cat_expr(&**base)))
+                    self.cat_index(expr, try!(self.cat_expr(&**base)), context)
                 }
             }
           }
@@ -854,7 +868,8 @@ pub fn cat_tup_field<N:ast_node>(&self,
     fn cat_deref<N:ast_node>(&self,
                              node: &N,
                              base_cmt: cmt<'tcx>,
-                             deref_cnt: uint)
+                             deref_cnt: uint,
+                             deref_context: DerefKindContext)
                              -> McResult<cmt<'tcx>> {
         let adjustment = match self.typer.adjustments().borrow().get(&node.id()) {
             Some(adj) if ty::adjust_is_object(adj) => ty::AutoObject,
@@ -882,7 +897,9 @@ fn cat_deref<N:ast_node>(&self,
         };
         let base_cmt_ty = base_cmt.ty;
         match ty::deref(base_cmt_ty, true) {
-            Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty,
+            Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt,
+                                              mt.ty,
+                                              deref_context,
                                               /* implicit: */ false),
             None => {
                 debug!("Explicit deref of non-derefable type: {}",
@@ -897,10 +914,11 @@ fn cat_deref_common<N:ast_node>(&self,
                                     base_cmt: cmt<'tcx>,
                                     deref_cnt: uint,
                                     deref_ty: Ty<'tcx>,
+                                    deref_context: DerefKindContext,
                                     implicit: bool)
                                     -> McResult<cmt<'tcx>>
     {
-        let (m, cat) = match try!(deref_kind(base_cmt.ty)) {
+        let (m, cat) = match try!(deref_kind(base_cmt.ty, deref_context)) {
             deref_ptr(ptr) => {
                 let ptr = if implicit {
                     match ptr {
@@ -932,7 +950,8 @@ fn cat_deref_common<N:ast_node>(&self,
 
     pub fn cat_index<N:ast_node>(&self,
                                  elt: &N,
-                                 mut base_cmt: cmt<'tcx>)
+                                 mut base_cmt: cmt<'tcx>,
+                                 context: InteriorOffsetKind)
                                  -> McResult<cmt<'tcx>> {
         //! Creates a cmt for an indexing operation (`[]`).
         //!
@@ -974,18 +993,21 @@ pub fn cat_index<N:ast_node>(&self,
         };
 
         let m = base_cmt.mutbl.inherit();
-        return Ok(interior(elt, base_cmt.clone(), base_cmt.ty, m, element_ty));
+        return Ok(interior(elt, base_cmt.clone(), base_cmt.ty,
+                           m, context, element_ty));
 
         fn interior<'tcx, N: ast_node>(elt: &N,
                                        of_cmt: cmt<'tcx>,
                                        vec_ty: Ty<'tcx>,
                                        mutbl: MutabilityCategory,
+                                       context: InteriorOffsetKind,
                                        element_ty: Ty<'tcx>) -> cmt<'tcx>
         {
+            let interior_elem = InteriorElement(context, element_kind(vec_ty));
             Rc::new(cmt_ {
                 id:elt.id(),
                 span:elt.span(),
-                cat:cat_interior(of_cmt, InteriorElement(element_kind(vec_ty))),
+                cat:cat_interior(of_cmt, interior_elem),
                 mutbl:mutbl,
                 ty:element_ty,
                 note: NoteNone
@@ -997,10 +1019,11 @@ fn interior<'tcx, N: ast_node>(elt: &N,
     // underlying vec.
     fn deref_vec<N:ast_node>(&self,
                              elt: &N,
-                             base_cmt: cmt<'tcx>)
+                             base_cmt: cmt<'tcx>,
+                             context: InteriorOffsetKind)
                              -> McResult<cmt<'tcx>>
     {
-        match try!(deref_kind(base_cmt.ty)) {
+        match try!(deref_kind(base_cmt.ty, Some(context))) {
             deref_ptr(ptr) => {
                 // for unique ptrs, we inherit mutability from the
                 // owning reference.
@@ -1041,7 +1064,9 @@ pub fn cat_slice_pattern(&self,
         let (slice_mutbl, slice_r) = vec_slice_info(self.tcx(),
                                                     slice_pat,
                                                     slice_ty);
-        let cmt_slice = try!(self.cat_index(slice_pat, try!(self.deref_vec(slice_pat, vec_cmt))));
+        let context = InteriorOffsetKind::Pattern;
+        let cmt_vec = try!(self.deref_vec(slice_pat, vec_cmt, context));
+        let cmt_slice = try!(self.cat_index(slice_pat, cmt_vec, context));
         return Ok((cmt_slice, slice_mutbl, slice_r));
 
         /// In a pattern like [a, b, ..c], normally `c` has slice type, but if you have [a, b,
@@ -1253,12 +1278,14 @@ fn cat_pattern_<F>(&self, cmt: cmt<'tcx>, pat: &ast::Pat, op: &mut F)
             // box p1, &p1, &mut p1.  we can ignore the mutability of
             // PatRegion since that information is already contained
             // in the type.
-            let subcmt = try!(self.cat_deref(pat, cmt, 0));
+            let subcmt = try!(self.cat_deref(pat, cmt, 0, None));
               try!(self.cat_pattern_(subcmt, &**subpat, op));
           }
 
           ast::PatVec(ref before, ref slice, ref after) => {
-              let elt_cmt = try!(self.cat_index(pat, try!(self.deref_vec(pat, cmt))));
+              let context = InteriorOffsetKind::Pattern;
+              let vec_cmt = try!(self.deref_vec(pat, cmt, context));
+              let elt_cmt = try!(self.cat_index(pat, vec_cmt, context));
               for before_pat in before {
                   try!(self.cat_pattern_(elt_cmt.clone(), &**before_pat, op));
               }
@@ -1455,10 +1482,18 @@ pub fn descriptive_string(&self, tcx: &ty::ctxt) -> String {
             cat_interior(_, InteriorField(PositionalField(_))) => {
                 "anonymous field".to_string()
             }
-            cat_interior(_, InteriorElement(VecElement)) |
-            cat_interior(_, InteriorElement(OtherElement)) => {
+            cat_interior(_, InteriorElement(InteriorOffsetKind::Index,
+                                            VecElement)) |
+            cat_interior(_, InteriorElement(InteriorOffsetKind::Index,
+                                            OtherElement)) => {
                 "indexed content".to_string()
             }
+            cat_interior(_, InteriorElement(InteriorOffsetKind::Pattern,
+                                            VecElement)) |
+            cat_interior(_, InteriorElement(InteriorOffsetKind::Pattern,
+                                            OtherElement)) => {
+                "pattern-bound indexed content".to_string()
+            }
             cat_upvar(ref var) => {
                 var.user_string(tcx)
             }
@@ -1543,10 +1578,10 @@ impl<'tcx> Repr<'tcx> for InteriorKind {
     fn repr(&self, _tcx: &ty::ctxt) -> String {
         match *self {
             InteriorField(NamedField(fld)) => {
-                token::get_name(fld).get().to_string()
+                token::get_name(fld).to_string()
             }
             InteriorField(PositionalField(i)) => format!("#{}", i),
-            InteriorElement(_) => "[]".to_string(),
+            InteriorElement(..) => "[]".to_string(),
         }
     }
 }
index 87d386d94c97270c3fc4a75af0a6d60f2c469a2d..037b1c31a17207fa9ec3153d6845af95f568755c 100644 (file)
@@ -260,6 +260,34 @@ struct RegionResolutionVisitor<'a> {
 
 
 impl RegionMaps {
+    pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
+        for (child, parent) in self.scope_map.borrow().iter() {
+            e(child, parent)
+        }
+    }
+    pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
+        for (child, parent) in self.var_map.borrow().iter() {
+            e(child, parent)
+        }
+    }
+    pub fn each_encl_free_region<E>(&self, mut e:E) where E: FnMut(&FreeRegion, &FreeRegion) {
+        for (child, parents) in self.free_region_map.borrow().iter() {
+            for parent in parents.iter() {
+                e(child, parent)
+            }
+        }
+    }
+    pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
+        for (child, parent) in self.rvalue_scopes.borrow().iter() {
+            e(child, parent)
+        }
+    }
+    pub fn each_terminating_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent) {
+        for scope in self.terminating_scopes.borrow().iter() {
+            e(scope)
+        }
+    }
+
     pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
         match self.free_region_map.borrow_mut().get_mut(&sub) {
             Some(sups) => {
@@ -666,7 +694,7 @@ fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
 
     {
         let region_maps = &mut visitor.region_maps;
-        let terminating = |&: id| {
+        let terminating = |id| {
             let scope = CodeExtent::from_node_id(id);
             region_maps.mark_as_terminating_scope(scope)
         };
index 365355c4a2a0b3db38fd2594d0742d208c445cac..6f38dc81064209b997752ae332c8ef5fbcc6c258 100644 (file)
@@ -45,8 +45,8 @@ pub enum DefRegion {
                   /* lifetime decl */ ast::NodeId),
 }
 
-// maps the id of each lifetime reference to the lifetime decl
-// that it corresponds to
+// Maps the id of each lifetime reference to the lifetime decl
+// that it corresponds to.
 pub type NamedRegionMap = NodeMap<DefRegion>;
 
 struct LifetimeContext<'a> {
@@ -54,6 +54,22 @@ struct LifetimeContext<'a> {
     named_region_map: &'a mut NamedRegionMap,
     scope: Scope<'a>,
     def_map: &'a DefMap,
+    // Deep breath. Our representation for poly trait refs contains a single
+    // binder and thus we only allow a single level of quantification. However,
+    // the syntax of Rust permits quantification in two places, e.g., `T: for <'a> Foo<'a>`
+    // and `for <'a, 'b> &'b T: Foo<'a>`. In order to get the de Bruijn indices
+    // correct when representing these constraints, we should only introduce one
+    // scope. However, we want to support both locations for the quantifier and
+    // during lifetime resolution we want precise information (so we can't
+    // desugar in an earlier phase).
+
+    // SO, if we encounter a quantifier at the outer scope, we set
+    // trait_ref_hack to true (and introduce a scope), and then if we encounter
+    // a quantifier at the inner scope, we error. If trait_ref_hack is false,
+    // then we introduce the scope at the inner quantifier.
+
+    // I'm sorry.
+    trait_ref_hack: bool,
 }
 
 enum ScopeChain<'a> {
@@ -80,6 +96,7 @@ pub fn krate(sess: &Session, krate: &ast::Crate, def_map: &DefMap) -> NamedRegio
         named_region_map: &mut named_region_map,
         scope: &ROOT_SCOPE,
         def_map: def_map,
+        trait_ref_hack: false,
     }, krate);
     sess.abort_if_errors();
     named_region_map
@@ -198,9 +215,22 @@ fn visit_generics(&mut self, generics: &ast::Generics) {
             match predicate {
                 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ ref bounded_ty,
                                                                                ref bounds,
+                                                                               ref bound_lifetimes,
                                                                                .. }) => {
-                    self.visit_ty(&**bounded_ty);
-                    visit::walk_ty_param_bounds_helper(self, bounds);
+                    if bound_lifetimes.len() > 0 {
+                        self.trait_ref_hack = true;
+                        let result = self.with(LateScope(bound_lifetimes, self.scope),
+                                               |old_scope, this| {
+                            this.check_lifetime_defs(old_scope, bound_lifetimes);
+                            this.visit_ty(&**bounded_ty);
+                            visit::walk_ty_param_bounds_helper(this, bounds);
+                        });
+                        self.trait_ref_hack = false;
+                        result
+                    } else {
+                        self.visit_ty(&**bounded_ty);
+                        visit::walk_ty_param_bounds_helper(self, bounds);
+                    }
                 }
                 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
                                                                                 ref bounds,
@@ -222,18 +252,27 @@ 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| {
-            this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes);
-            for lifetime in &trait_ref.bound_lifetimes {
-                this.visit_lifetime_def(lifetime);
+        if !self.trait_ref_hack || trait_ref.bound_lifetimes.len() > 0 {
+            if self.trait_ref_hack {
+                println!("{:?}", trait_ref.span);
+                span_err!(self.sess, trait_ref.span, E0316,
+                          "nested quantification of lifetimes");
             }
-            this.visit_trait_ref(&trait_ref.trait_ref)
-        })
+            self.with(LateScope(&trait_ref.bound_lifetimes, self.scope), |old_scope, this| {
+                this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes);
+                for lifetime in &trait_ref.bound_lifetimes {
+                    this.visit_lifetime_def(lifetime);
+                }
+                this.visit_trait_ref(&trait_ref.trait_ref)
+            })
+        } else {
+            self.visit_trait_ref(&trait_ref.trait_ref)
+        }
     }
 
     fn visit_trait_ref(&mut self, trait_ref: &ast::TraitRef) {
@@ -251,6 +290,7 @@ fn with<F>(&mut self, wrap_scope: ScopeChain, f: F) where
             named_region_map: *named_region_map,
             scope: &wrap_scope,
             def_map: self.def_map,
+            trait_ref_hack: self.trait_ref_hack,
         };
         debug!("entering scope {:?}", this.scope);
         f(self.scope, &mut this);
@@ -456,13 +496,13 @@ fn check_lifetime_def_for_shadowing(&self,
                     if let Some((_, lifetime_def)) = search_lifetimes(lifetimes, lifetime) {
                         self.sess.span_warn(
                             lifetime.span,
-                            format!("lifetime name `{}` shadows another \
-                                    lifetime name that is already in scope",
-                                    token::get_name(lifetime.name)).as_slice());
+                            &format!("lifetime name `{}` shadows another \
+                                     lifetime name that is already in scope",
+                                     token::get_name(lifetime.name)));
                         self.sess.span_note(
                             lifetime_def.span,
-                            format!("shadowed lifetime `{}` declared here",
-                                    token::get_name(lifetime.name)).as_slice());
+                            &format!("shadowed lifetime `{}` declared here",
+                                     token::get_name(lifetime.name)));
                         self.sess.span_note(
                             lifetime.span,
                             "shadowed lifetimes are deprecated \
index 3304bd4ae2952226f0fd3f0769280562e7a18300..0ed672baf56e6656dfe0613dba898f791ca6305d 100644 (file)
@@ -57,7 +57,7 @@ fn annotate<F>(&mut self, id: NodeId, use_parent: bool,
                    attrs: &Vec<Attribute>, item_sp: Span, f: F, required: bool) where
         F: FnOnce(&mut Annotator),
     {
-        match attr::find_stability(self.sess.diagnostic(), attrs.as_slice(), item_sp) {
+        match attr::find_stability(self.sess.diagnostic(), attrs, item_sp) {
             Some(stab) => {
                 self.index.local.insert(id, stab.clone());
 
@@ -180,7 +180,7 @@ pub fn build(&mut self, sess: &Session, krate: &Crate, export_map: &PublicItems)
     pub fn new(krate: &Crate) -> Index {
         let mut staged_api = false;
         for attr in &krate.attrs {
-            if attr.name().get() == "staged_api" {
+            if &attr.name()[] == "staged_api" {
                 match attr.node.value.node {
                     ast::MetaWord(_) => {
                         attr::mark_used(attr);
@@ -201,8 +201,9 @@ pub fn new(krate: &Crate) -> Index {
 /// Cross-references the feature names of unstable APIs with enabled
 /// features and possibly prints errors. Returns a list of all
 /// features used.
-pub fn check_unstable_api_usage(tcx: &ty::ctxt) -> FnvHashSet<InternedString> {
-    let ref active_lib_features = tcx.sess.features.borrow().lib_features;
+pub fn check_unstable_api_usage(tcx: &ty::ctxt)
+                                -> FnvHashMap<InternedString, attr::StabilityLevel> {
+    let ref active_lib_features = tcx.sess.features.borrow().declared_lib_features;
 
     // Put the active features into a map for quick lookup
     let active_features = active_lib_features.iter().map(|&(ref s, _)| s.clone()).collect();
@@ -210,7 +211,7 @@ pub fn check_unstable_api_usage(tcx: &ty::ctxt) -> FnvHashSet<InternedString> {
     let mut checker = Checker {
         tcx: tcx,
         active_features: active_features,
-        used_features: FnvHashSet()
+        used_features: FnvHashMap()
     };
 
     let krate = tcx.map.krate();
@@ -223,7 +224,7 @@ pub fn check_unstable_api_usage(tcx: &ty::ctxt) -> FnvHashSet<InternedString> {
 struct Checker<'a, 'tcx: 'a> {
     tcx: &'a ty::ctxt<'tcx>,
     active_features: FnvHashSet<InternedString>,
-    used_features: FnvHashSet<InternedString>
+    used_features: FnvHashMap<InternedString, attr::StabilityLevel>
 }
 
 impl<'a, 'tcx> Checker<'a, 'tcx> {
@@ -234,20 +235,22 @@ fn check(&mut self, id: ast::DefId, span: Span, stab: &Option<Stability>) {
 
         match *stab {
             Some(Stability { level: attr::Unstable, ref feature, ref reason, .. }) => {
-                self.used_features.insert(feature.clone());
+                self.used_features.insert(feature.clone(), attr::Unstable);
 
                 if !self.active_features.contains(feature) {
                     let msg = match *reason {
                         Some(ref r) => format!("use of unstable library feature '{}': {}",
-                                               feature.get(), r.get()),
-                        None => format!("use of unstable library feature '{}'", feature.get())
+                                               &feature, &r),
+                        None => format!("use of unstable library feature '{}'", &feature)
                     };
 
                     emit_feature_warn(&self.tcx.sess.parse_sess.span_diagnostic,
-                                      feature.get(), span, &msg[]);
+                                      &feature, span, &msg);
                 }
             }
-            Some(..) => {
+            Some(Stability { level, ref feature, .. }) => {
+                self.used_features.insert(feature.clone(), level);
+
                 // Stable APIs are always ok to call and deprecated APIs are
                 // handled by a lint.
             }
@@ -433,17 +436,37 @@ pub fn lookup(tcx: &ty::ctxt, id: DefId) -> Option<Stability> {
 /// Given the list of enabled features that were not language features (i.e. that
 /// were expected to be library features), and the list of features used from
 /// libraries, identify activated features that don't exist and error about them.
-pub fn check_unused_features(sess: &Session,
-                             used_lib_features: &FnvHashSet<InternedString>) {
-    let ref lib_features = sess.features.borrow().lib_features;
-    let mut active_lib_features: FnvHashMap<InternedString, Span>
-        = lib_features.clone().into_iter().collect();
-
-    for used_feature in used_lib_features {
-        active_lib_features.remove(used_feature);
+pub fn check_unused_or_stable_features(sess: &Session,
+                                       lib_features_used: &FnvHashMap<InternedString,
+                                                                      attr::StabilityLevel>) {
+    let ref declared_lib_features = sess.features.borrow().declared_lib_features;
+    let mut remaining_lib_features: FnvHashMap<InternedString, Span>
+        = declared_lib_features.clone().into_iter().collect();
+
+    let stable_msg = "this feature is stable. attribute no longer needed";
+
+    for &span in sess.features.borrow().declared_stable_lang_features.iter() {
+        sess.add_lint(lint::builtin::STABLE_FEATURES,
+                      ast::CRATE_NODE_ID,
+                      span,
+                      stable_msg.to_string());
+    }
+
+    for (used_lib_feature, level) in lib_features_used.iter() {
+        match remaining_lib_features.remove(used_lib_feature) {
+            Some(span) => {
+                if *level == attr::Stable {
+                    sess.add_lint(lint::builtin::STABLE_FEATURES,
+                                  ast::CRATE_NODE_ID,
+                                  span,
+                                  stable_msg.to_string());
+                }
+            }
+            None => ( /* used but undeclared, handled during the previous ast visit */ )
+        }
     }
 
-    for (_, &span) in &active_lib_features {
+    for (_, &span) in remaining_lib_features.iter() {
         sess.add_lint(lint::builtin::UNUSED_FEATURES,
                       ast::CRATE_NODE_ID,
                       span,
index eb6bc4c38353a43e05d8107cc83c4892ef524df0..8cb0447e732477343128db81a7878b185687031c 100644 (file)
@@ -406,7 +406,7 @@ pub fn iter_enumerated<'a>(&'a self) -> EnumeratedItems<'a,T> {
     }
 
     pub fn as_slice(&self) -> &[T] {
-        self.content.as_slice()
+        &self.content
     }
 
     pub fn into_vec(self) -> Vec<T> {
index 44cd17caaecbb026445e71b5582038ae9de37dde..3a7522cafee90f283354aa24e520dd40c52211ca 100644 (file)
@@ -59,7 +59,6 @@ pub fn impl_can_satisfy(infcx: &InferCtxt,
             |o| selcx.evaluate_obligation(o))
 }
 
-#[allow(missing_copy_implementations)]
 pub enum OrphanCheckErr<'tcx> {
     NoLocalInputType,
     UncoveredTy(Ty<'tcx>),
index 8ce4e38896ecd2502726d577516e088af7052623..7af046401ad60f09bfa3a33bd22202b2b68b6ed1 100644 (file)
@@ -24,7 +24,7 @@ fn clone_slice<T:Clone>(x: &[T]) -> Vec<T> { ... }
 
 and then a call to that function:
 
-    let v: Vec<int> = clone_slice([1, 2, 3].as_slice())
+    let v: Vec<int> = clone_slice([1, 2, 3])
 
 it is the job of trait resolution to figure out (in which case)
 whether there exists an impl of `int : Clone`
@@ -434,87 +434,11 @@ impl Foo<int> for uint { ... } // Impl #22
 to the `tcx`. We use the local cache whenever the result might depend
 on the where clauses that are in scope. The determination of which
 cache to use is done by the method `pick_candidate_cache` in
-`select.rs`.
-
-There are two cases where we currently use the local cache. The
-current rules are probably more conservative than necessary.
-
-### Trait references that involve parameter types
-
-The most obvious case where you need the local environment is
-when the trait reference includes parameter types. For example,
-consider the following function:
-
-    impl<T> Vec<T> {
-        fn foo(x: T)
-            where T : Foo
-        { ... }
-
-        fn bar(x: T)
-        { ... }
-    }
-
-If there is an obligation `T : Foo`, or `int : Bar<T>`, or whatever,
-clearly the results from `foo` and `bar` are potentially different,
-since the set of where clauses in scope are different.
-
-### Trait references with unbound variables when where clauses are in scope
-
-There is another less obvious interaction which involves unbound variables
-where *only* where clauses are in scope (no impls). This manifested as
-issue #18209 (`run-pass/trait-cache-issue-18209.rs`). Consider
-this snippet:
-
-```
-pub trait Foo {
-    fn load_from() -> Box<Self>;
-    fn load() -> Box<Self> {
-        Foo::load_from()
-    }
-}
-```
-
-The default method will incur an obligation `$0 : Foo` from the call
-to `load_from`. If there are no impls, this can be eagerly resolved to
-`VtableParam(Self : Foo)` and cached. Because the trait reference
-doesn't involve any parameters types (only the resolution does), this
-result was stored in the global cache, causing later calls to
-`Foo::load_from()` to get nonsense.
-
-To fix this, we always use the local cache if there are unbound
-variables and where clauses in scope. This is more conservative than
-necessary as far as I can tell. However, it still seems to be a simple
-rule and I observe ~99% hit rate on rustc, so it doesn't seem to hurt
-us in particular.
-
-Here is an example of the kind of subtle case that I would be worried
-about with a more complex rule (although this particular case works
-out ok). Imagine the trait reference doesn't directly reference a
-where clause, but the where clause plays a role in the winnowing
-phase. Something like this:
-
-```
-pub trait Foo<T> { ... }
-pub trait Bar { ... }
-impl<U,T:Bar> Foo<U> for T { ... } // Impl A
-impl Foo<char> for uint { ... }    // Impl B
-```
-
-Now, in some function, we have no where clauses in scope, and we have
-an obligation `$1 : Foo<$0>`. We might then conclude that `$0=char`
-and `$1=uint`: this is because for impl A to apply, `uint:Bar` would
-have to hold, and we know it does not or else the coherence check
-would have failed.  So we might enter into our global cache: `$1 :
-Foo<$0> => Impl B`.  Then we come along in a different scope, where a
-generic type `A` is around with the bound `A:Bar`. Now suddenly the
-impl is viable.
-
-The flaw in this imaginary DOOMSDAY SCENARIO is that we would not
-currently conclude that `$1 : Foo<$0>` implies that `$0 == uint` and
-`$1 == char`, even though it is true that (absent type parameters)
-there is no other type the user could enter. However, it is not
-*completely* implausible that we *could* draw this conclusion in the
-future; we wouldn't have to guess types, in particular, we could be
-led by the impls.
+`select.rs`. At the moment, we use a very simple, conservative rule:
+if there are any where-clauses in scope, then we use the local cache.
+We used to try and draw finer-grained distinctions, but that led to a
+serious of annoying and weird bugs like #22019 and #18290. This simple
+rule seems to be pretty clearly safe and also still retains a very
+high hit rate (~95% when compiling rustc).
 
 */
index b8886fa65baa8c8db2e1d45be14068d364a30d9f..2197cbeb85db4afb7ead1629b4cc500a468ea140 100644 (file)
@@ -86,14 +86,14 @@ fn report_on_unimplemented<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
                                               }).collect::<HashMap<String, String>>();
                 generic_map.insert("Self".to_string(),
                                    trait_ref.self_ty().user_string(infcx.tcx));
-                let parser = Parser::new(istring.get());
+                let parser = Parser::new(&istring);
                 let mut errored = false;
                 let err: String = parser.filter_map(|p| {
                     match p {
                         Piece::String(s) => Some(s),
                         Piece::NextArgument(a) => match a.position {
                             Position::ArgumentNamed(s) => match generic_map.get(s) {
-                                Some(val) => Some(val.as_slice()),
+                                Some(val) => Some(val),
                                 None => {
                                     span_err!(infcx.tcx.sess, err_sp, E0272,
                                                    "the #[rustc_on_unimplemented] \
@@ -181,7 +181,7 @@ pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
                                                                           obligation.cause.span);
                                 if let Some(s) = custom_note {
                                     infcx.tcx.sess.span_note(obligation.cause.span,
-                                                             s.as_slice());
+                                                             &s);
                                 }
                             }
                         }
@@ -289,12 +289,12 @@ pub fn maybe_report_ambiguity<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
                 // Ambiguity. Coherence should have reported an error.
                 infcx.tcx.sess.span_bug(
                     obligation.cause.span,
-                    format!(
+                    &format!(
                         "coherence failed to report ambiguity: \
                          cannot locate the impl of the trait `{}` for \
                          the type `{}`",
                         trait_ref.user_string(infcx.tcx),
-                        self_ty.user_string(infcx.tcx)).as_slice());
+                        self_ty.user_string(infcx.tcx)));
             }
         }
 
@@ -330,14 +330,14 @@ fn note_obligation_cause_code<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
             let item_name = ty::item_path_str(tcx, item_def_id);
             tcx.sess.span_note(
                 cause_span,
-                format!("required by `{}`", item_name).as_slice());
+                &format!("required by `{}`", item_name));
         }
         ObligationCauseCode::ObjectCastObligation(object_ty) => {
             tcx.sess.span_note(
                 cause_span,
-                format!(
+                &format!(
                     "required for the cast to the object type `{}`",
-                    infcx.ty_to_string(object_ty)).as_slice());
+                    infcx.ty_to_string(object_ty)));
         }
         ObligationCauseCode::RepeatVec => {
             tcx.sess.span_note(
index 8adcd256ccebcccc825e70aa72fa7dee0b608918..07c7453783d9561ccef45ca8d3f12612968b9629 100644 (file)
@@ -180,7 +180,7 @@ pub fn region_obligations(&self,
     {
         match self.region_obligations.get(&body_id) {
             None => Default::default(),
-            Some(vec) => vec.as_slice(),
+            Some(vec) => vec,
         }
     }
 
index c2a451b405bb5008018d635a94662460178a746c..9d3ad28e6138b574e69149333b64f552b7c9a81a 100644 (file)
@@ -605,8 +605,8 @@ fn assemble_candidates_from_object_type<'cx,'tcx>(
         _ => {
             selcx.tcx().sess.span_bug(
                 obligation.cause.span,
-                format!("assemble_candidates_from_object_type called with non-object: {}",
-                        object_ty.repr(selcx.tcx())).as_slice());
+                &format!("assemble_candidates_from_object_type called with non-object: {}",
+                         object_ty.repr(selcx.tcx())));
         }
     };
     let projection_bounds = data.projection_bounds_with_self_ty(selcx.tcx(), object_ty);
@@ -693,8 +693,8 @@ fn assemble_candidates_from_impls<'cx,'tcx>(
             // These traits have no associated types.
             selcx.tcx().sess.span_bug(
                 obligation.cause.span,
-                format!("Cannot project an associated type from `{}`",
-                        vtable.repr(selcx.tcx())).as_slice());
+                &format!("Cannot project an associated type from `{}`",
+                         vtable.repr(selcx.tcx())));
         }
     }
 
@@ -813,10 +813,10 @@ fn confirm_param_env_candidate<'cx,'tcx>(
         Err(e) => {
             selcx.tcx().sess.span_bug(
                 obligation.cause.span,
-                format!("Failed to unify `{}` and `{}` in projection: {}",
-                        obligation.repr(selcx.tcx()),
-                        projection.repr(selcx.tcx()),
-                        ty::type_err_to_str(selcx.tcx(), &e)).as_slice());
+                &format!("Failed to unify `{}` and `{}` in projection: {}",
+                         obligation.repr(selcx.tcx()),
+                         projection.repr(selcx.tcx()),
+                         ty::type_err_to_str(selcx.tcx(), &e)));
         }
     }
 
index 2fe07df1709f8aaada8b5aa34fc437baf367c369..5323a32243642cf7c5a6fe434763d9fc680253d4 100644 (file)
@@ -705,14 +705,17 @@ fn candidate_from_obligation_no_cache<'o>(&mut self,
         Ok(Some(candidate))
     }
 
-    fn pick_candidate_cache(&self,
-                            cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
-                            -> &SelectionCache<'tcx>
-    {
-        // High-level idea: we have to decide whether to consult the
-        // cache that is specific to this scope, or to consult the
-        // global cache. We want the cache that is specific to this
-        // scope whenever where clauses might affect the result.
+    fn pick_candidate_cache(&self) -> &SelectionCache<'tcx> {
+        // If there are any where-clauses in scope, then we always use
+        // a cache local to this particular scope. Otherwise, we
+        // switch to a global cache. We used to try and draw
+        // finer-grained distinctions, but that led to a serious of
+        // annoying and weird bugs like #22019 and #18290. This simple
+        // rule seems to be pretty clearly safe and also still retains
+        // a very high hit rate (~95% when compiling rustc).
+        if !self.param_env().caller_bounds.is_empty() {
+            return &self.param_env().selection_cache;
+        }
 
         // Avoid using the master cache during coherence and just rely
         // on the local cache. This effectively disables caching
@@ -725,28 +728,6 @@ fn pick_candidate_cache(&self,
             return &self.param_env().selection_cache;
         }
 
-        // If the trait refers to any parameters in scope, then use
-        // the cache of the param-environment.
-        if
-            cache_fresh_trait_pred.0.input_types().iter().any(
-                |&t| ty::type_has_self(t) || ty::type_has_params(t))
-        {
-            return &self.param_env().selection_cache;
-        }
-
-        // If the trait refers to unbound type variables, and there
-        // are where clauses in scope, then use the local environment.
-        // If there are no where clauses in scope, which is a very
-        // common case, then we can use the global environment.
-        // See the discussion in doc.rs for more details.
-        if
-            !self.param_env().caller_bounds.is_empty() &&
-            cache_fresh_trait_pred.0.input_types().iter().any(
-                |&t| ty::type_has_ty_infer(t))
-        {
-            return &self.param_env().selection_cache;
-        }
-
         // Otherwise, we can use the global cache.
         &self.tcx().selection_cache
     }
@@ -755,7 +736,7 @@ fn check_candidate_cache(&mut self,
                              cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
                              -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
     {
-        let cache = self.pick_candidate_cache(cache_fresh_trait_pred);
+        let cache = self.pick_candidate_cache();
         let hashmap = cache.hashmap.borrow();
         hashmap.get(&cache_fresh_trait_pred.0.trait_ref).map(|c| (*c).clone())
     }
@@ -764,7 +745,7 @@ fn insert_candidate_cache(&mut self,
                               cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
                               candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
     {
-        let cache = self.pick_candidate_cache(&cache_fresh_trait_pred);
+        let cache = self.pick_candidate_cache();
         let mut hashmap = cache.hashmap.borrow_mut();
         hashmap.insert(cache_fresh_trait_pred.0.trait_ref.clone(), candidate);
     }
@@ -775,7 +756,7 @@ fn should_update_candidate_cache(&mut self,
                                      -> bool
     {
         // In general, it's a good idea to cache results, even
-        // ambigious ones, to save us some trouble later. But we have
+        // ambiguous ones, to save us some trouble later. But we have
         // to be careful not to cache results that could be
         // invalidated later by advances in inference. Normally, this
         // is not an issue, because any inference variables whose
@@ -933,9 +914,9 @@ fn match_projection_obligation_against_bounds_from_trait(
             _ => {
                 self.tcx().sess.span_bug(
                     obligation.cause.span,
-                    format!("match_projection_obligation_against_bounds_from_trait() called \
-                             but self-ty not a projection: {}",
-                            skol_trait_predicate.trait_ref.self_ty().repr(self.tcx())).as_slice());
+                    &format!("match_projection_obligation_against_bounds_from_trait() called \
+                              but self-ty not a projection: {}",
+                             skol_trait_predicate.trait_ref.self_ty().repr(self.tcx())));
             }
         };
         debug!("match_projection_obligation_against_bounds_from_trait: \
@@ -1273,7 +1254,7 @@ fn winnow_selection<'o>(&mut self,
     ///
     /// - The impl is conditional, in which case we may not have winnowed it out
     ///   because we don't know if the conditions apply, but the where clause is basically
-    ///   telling us taht there is some impl, though not necessarily the one we see.
+    ///   telling us that there is some impl, though not necessarily the one we see.
     ///
     /// In both cases we prefer to take the where clause, which is
     /// essentially harmless.  See issue #18453 for more details of
@@ -1335,25 +1316,6 @@ fn candidate_should_be_dropped_in_favor_of<'o>(&mut self,
                 // the where clauses are in scope.
                 true
             }
-            (&ParamCandidate(ref bound1), &ParamCandidate(ref bound2)) => {
-                self.infcx.probe(|_| {
-                    let bound1 =
-                        project::normalize_with_depth(self,
-                                                      stack.obligation.cause.clone(),
-                                                      stack.obligation.recursion_depth+1,
-                                                      bound1);
-                    let bound2 =
-                        project::normalize_with_depth(self,
-                                                      stack.obligation.cause.clone(),
-                                                      stack.obligation.recursion_depth+1,
-                                                      bound2);
-                    let origin =
-                        infer::RelateOutputImplTypes(stack.obligation.cause.span);
-                    self.infcx
-                        .sub_poly_trait_refs(false, origin, bound1.value, bound2.value)
-                        .is_ok()
-                })
-            }
             _ => {
                 false
             }
@@ -1795,9 +1757,9 @@ fn confirm_param_candidate(&mut self,
             Ok(obligations) => obligations,
             Err(()) => {
                 self.tcx().sess.bug(
-                    format!("Where clause `{}` was applicable to `{}` but now is not",
-                            param.repr(self.tcx()),
-                            obligation.repr(self.tcx())).as_slice());
+                    &format!("Where clause `{}` was applicable to `{}` but now is not",
+                             param.repr(self.tcx()),
+                             obligation.repr(self.tcx())));
             }
         }
     }
@@ -1961,9 +1923,9 @@ fn confirm_object_candidate(&mut self,
             Some(r) => r,
             None => {
                 self.tcx().sess.span_bug(obligation.cause.span,
-                                         format!("unable to upcast from {} to {}",
-                                                 poly_trait_ref.repr(self.tcx()),
-                                                 obligation_def_id.repr(self.tcx())).as_slice());
+                                         &format!("unable to upcast from {} to {}",
+                                                  poly_trait_ref.repr(self.tcx()),
+                                                  obligation_def_id.repr(self.tcx())));
             }
         };
 
index 45ce692bb076354e7bbb86bc891bc36d77fb4a05..573efa727569ec915629143df38a9524917c98b7 100644 (file)
 use middle::subst::{Substs, VecPerParamSpace};
 use middle::infer::InferCtxt;
 use middle::ty::{self, Ty, AsPredicate, ToPolyTraitRef};
-use std::collections::HashSet;
 use std::fmt;
 use std::rc::Rc;
 use syntax::ast;
 use syntax::codemap::Span;
 use util::common::ErrorReported;
+use util::nodemap::FnvHashSet;
 use util::ppaux::Repr;
 
 use super::{Obligation, ObligationCause, PredicateObligation,
             VtableImpl, VtableParam, VtableImplData};
 
+struct PredicateSet<'a,'tcx:'a> {
+    tcx: &'a ty::ctxt<'tcx>,
+    set: FnvHashSet<ty::Predicate<'tcx>>,
+}
+
+impl<'a,'tcx> PredicateSet<'a,'tcx> {
+    fn new(tcx: &'a ty::ctxt<'tcx>) -> PredicateSet<'a,'tcx> {
+        PredicateSet { tcx: tcx, set: FnvHashSet() }
+    }
+
+    fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {
+        // We have to be careful here because we want
+        //
+        //    for<'a> Foo<&'a int>
+        //
+        // and
+        //
+        //    for<'b> Foo<&'b int>
+        //
+        // to be considered equivalent. So normalize all late-bound
+        // regions before we throw things into the underlying set.
+        let normalized_pred = match *pred {
+            ty::Predicate::Trait(ref data) =>
+                ty::Predicate::Trait(ty::anonymize_late_bound_regions(self.tcx, data)),
+
+            ty::Predicate::Equate(ref data) =>
+                ty::Predicate::Equate(ty::anonymize_late_bound_regions(self.tcx, data)),
+
+            ty::Predicate::RegionOutlives(ref data) =>
+                ty::Predicate::RegionOutlives(ty::anonymize_late_bound_regions(self.tcx, data)),
+
+            ty::Predicate::TypeOutlives(ref data) =>
+                ty::Predicate::TypeOutlives(ty::anonymize_late_bound_regions(self.tcx, data)),
+
+            ty::Predicate::Projection(ref data) =>
+                ty::Predicate::Projection(ty::anonymize_late_bound_regions(self.tcx, data)),
+        };
+        self.set.insert(normalized_pred)
+    }
+}
+
 ///////////////////////////////////////////////////////////////////////////
 // `Elaboration` iterator
 ///////////////////////////////////////////////////////////////////////////
@@ -36,7 +77,7 @@
 pub struct Elaborator<'cx, 'tcx:'cx> {
     tcx: &'cx ty::ctxt<'tcx>,
     stack: Vec<StackEntry<'tcx>>,
-    visited: HashSet<ty::Predicate<'tcx>>,
+    visited: PredicateSet<'cx,'tcx>,
 }
 
 struct StackEntry<'tcx> {
@@ -65,14 +106,11 @@ pub fn elaborate_trait_refs<'cx, 'tcx>(
 
 pub fn elaborate_predicates<'cx, 'tcx>(
     tcx: &'cx ty::ctxt<'tcx>,
-    predicates: Vec<ty::Predicate<'tcx>>)
+    mut predicates: Vec<ty::Predicate<'tcx>>)
     -> Elaborator<'cx, 'tcx>
 {
-    let visited: HashSet<ty::Predicate<'tcx>> =
-        predicates.iter()
-                  .map(|b| (*b).clone())
-                  .collect();
-
+    let mut visited = PredicateSet::new(tcx);
+    predicates.retain(|pred| visited.insert(pred));
     let entry = StackEntry { position: 0, predicates: predicates };
     Elaborator { tcx: tcx, stack: vec![entry], visited: visited }
 }
@@ -94,7 +132,7 @@ fn push(&mut self, predicate: &ty::Predicate<'tcx>) {
                 // recursion in some cases.  One common case is when
                 // people define `trait Sized: Sized { }` rather than `trait
                 // Sized { }`.
-                predicates.retain(|r| self.visited.insert(r.clone()));
+                predicates.retain(|r| self.visited.insert(r));
 
                 self.stack.push(StackEntry { position: 0,
                                              predicates: predicates });
@@ -279,7 +317,7 @@ pub fn trait_ref_for_builtin_bound<'tcx>(
             }))
         }
         Err(e) => {
-            tcx.sess.err(e.as_slice());
+            tcx.sess.err(&e);
             Err(ErrorReported)
         }
     }
index a772555d8fcb6eabb9821a8ab9d8239254e5eec0..95f7ff58524402f37655c6dc68c6a64d8b33c1ed 100644 (file)
@@ -1478,7 +1478,7 @@ pub fn to_poly_trait_predicate(&self) -> PolyTraitPredicate<'tcx> {
 /// compiler's representation for things like `for<'a> Fn(&'a int)`
 /// (which would be represented by the type `PolyTraitRef ==
 /// Binder<TraitRef>`). Note that when we skolemize, instantiate,
-/// erase, or otherwise "discharge" these bound reons, we change the
+/// erase, or otherwise "discharge" these bound regions, we change the
 /// type from `Binder<T>` to just `T` (see
 /// e.g. `liberate_late_bound_regions`).
 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
@@ -1591,10 +1591,10 @@ pub fn region_existential_bound<'tcx>(r: ty::Region) -> ExistentialBounds<'tcx>
 }
 
 impl CLike for BuiltinBound {
-    fn to_uint(&self) -> uint {
+    fn to_usize(&self) -> uint {
         *self as uint
     }
-    fn from_uint(v: uint) -> BuiltinBound {
+    fn from_usize(v: uint) -> BuiltinBound {
         unsafe { mem::transmute(v) }
     }
 }
@@ -2520,7 +2520,7 @@ fn add_depth(&mut self, depth: u32) {
     fn add_bound_computation(&mut self, computation: &FlagComputation) {
         self.add_flags(computation.flags);
 
-        // The types that contributed to `computation` occured within
+        // The types that contributed to `computation` occurred within
         // a region binder, so subtract one from the region depth
         // within when adding the depth to `self`.
         let depth = computation.depth;
@@ -2793,7 +2793,7 @@ pub fn mk_trait<'tcx>(cx: &ctxt<'tcx>,
                       bounds: ExistentialBounds<'tcx>)
                       -> Ty<'tcx>
 {
-    assert!(bound_list_is_sorted(bounds.projection_bounds.as_slice()));
+    assert!(bound_list_is_sorted(&bounds.projection_bounds));
 
     let inner = box TyTrait {
         principal: principal,
@@ -3406,8 +3406,8 @@ fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
                 // FIXME(#14449): `borrowed_contents` below assumes `&mut` closure.
                 let param_env = ty::empty_parameter_environment(cx);
                 let upvars = closure_upvars(&param_env, did, substs).unwrap();
-                TypeContents::union(upvars.as_slice(),
-                                    |f| tc_ty(cx, f.ty, cache))
+                TypeContents::union(&upvars,
+                                    |f| tc_ty(cx, &f.ty, cache))
                     | borrowed_contents(*r, MutMutable)
             }
 
@@ -3672,8 +3672,7 @@ fn subtypes_require<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec<DefId>,
             ty_closure(..) => {
                 // this check is run on type definitions, so we don't expect to see
                 // inference by-products or closure types
-                cx.sess.bug(format!("requires check invoked on inapplicable type: {:?}",
-                                    ty).as_slice())
+                cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
             }
 
             ty_tup(ref ts) => {
@@ -3766,8 +3765,7 @@ fn are_inner_types_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span,
             ty_closure(..) => {
                 // this check is run on type definitions, so we don't expect
                 // to see closure types
-                cx.sess.bug(format!("requires check invoked on inapplicable type: {:?}",
-                                    ty).as_slice())
+                cx.sess.bug(&format!("requires check invoked on inapplicable type: {:?}", ty))
             }
             _ => Representable,
         }
@@ -4646,7 +4644,7 @@ pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
         "no field named `{}` found in the list of fields `{:?}`",
         token::get_name(name),
         fields.iter()
-              .map(|f| token::get_name(f.name).get().to_string())
+              .map(|f| token::get_name(f.name).to_string())
               .collect::<Vec<String>>())[]);
 }
 
@@ -6087,7 +6085,7 @@ fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh,
         macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } }
         macro_rules! hash { ($e:expr) => { $e.hash(state) }  }
 
-        let region = |&: state: &mut SipHasher, r: Region| {
+        let region = |state: &mut SipHasher, r: Region| {
             match r {
                 ReStatic => {}
                 ReLateBound(db, BrAnon(i)) => {
@@ -6104,7 +6102,7 @@ macro_rules! hash { ($e:expr) => { $e.hash(state) }  }
                 }
             }
         };
-        let did = |&: state: &mut SipHasher, did: DefId| {
+        let did = |state: &mut SipHasher, did: DefId| {
             let h = if ast_util::is_local(did) {
                 svh.clone()
             } else {
@@ -6113,10 +6111,10 @@ macro_rules! hash { ($e:expr) => { $e.hash(state) }  }
             h.as_str().hash(state);
             did.node.hash(state);
         };
-        let mt = |&: state: &mut SipHasher, mt: mt| {
+        let mt = |state: &mut SipHasher, mt: mt| {
             mt.mutbl.hash(state);
         };
-        let fn_sig = |&: state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
+        let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
             let sig = anonymize_late_bound_regions(tcx, sig).0;
             for a in &sig.inputs { helper(tcx, *a, svh, state); }
             if let ty::FnConverging(output) = sig.output {
@@ -6365,9 +6363,9 @@ fn record_region_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, predicates: &[ty::Predicate<
                         _ => {
                             // All named regions are instantiated with free regions.
                             tcx.sess.bug(
-                                format!("record_region_bounds: non free region: {} / {}",
-                                        r_a.repr(tcx),
-                                        r_b.repr(tcx)).as_slice());
+                                &format!("record_region_bounds: non free region: {} / {}",
+                                         r_a.repr(tcx),
+                                         r_b.repr(tcx)));
                         }
                     }
                 }
index a9121951460f54c30ad48196e201b24d347e30e7..40dfd479364a6c18c76f960518bef48a3e87777b 100644 (file)
@@ -39,9 +39,9 @@ fn push_subtypes(&mut self, parent_ty: Ty<'tcx>) {
             }
             ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
                 self.push_reversed(principal.substs().types.as_slice());
-                self.push_reversed(bounds.projection_bounds.iter().map(|pred| {
+                self.push_reversed(&bounds.projection_bounds.iter().map(|pred| {
                     pred.0.ty
-                }).collect::<Vec<_>>().as_slice());
+                }).collect::<Vec<_>>());
             }
             ty::ty_enum(_, ref substs) |
             ty::ty_struct(_, ref substs) |
@@ -49,7 +49,7 @@ fn push_subtypes(&mut self, parent_ty: Ty<'tcx>) {
                 self.push_reversed(substs.types.as_slice());
             }
             ty::ty_tup(ref ts) => {
-                self.push_reversed(ts.as_slice());
+                self.push_reversed(ts);
             }
             ty::ty_bare_fn(_, ref ft) => {
                 self.push_sig_subtypes(&ft.sig);
@@ -62,7 +62,7 @@ fn push_sig_subtypes(&mut self, sig: &ty::PolyFnSig<'tcx>) {
             ty::FnConverging(output) => { self.stack.push(output); }
             ty::FnDiverging => { }
         }
-        self.push_reversed(sig.0.inputs.as_slice());
+        self.push_reversed(&sig.0.inputs);
     }
 
     fn push_reversed(&mut self, tys: &[Ty<'tcx>]) {
index 425c9a4c9f7748dd8c01406559d1727e34da3658..ee3fd681a005223af9a6df5537ce566c1b99f1bc 100644 (file)
@@ -55,7 +55,7 @@ pub fn check_crate(krate: &ast::Crate,
 
 pub fn link_name(attrs: &[ast::Attribute]) -> Option<InternedString> {
     lang_items::extract(attrs).and_then(|name| {
-        $(if name.get() == stringify!($name) {
+        $(if &name[] == stringify!($name) {
             Some(InternedString::new(stringify!($sym)))
         } else)* {
             None
@@ -85,8 +85,8 @@ fn verify(sess: &Session, items: &lang_items::LanguageItems) {
 
     $(
         if missing.contains(&lang_items::$item) && items.$name().is_none() {
-            sess.err(format!("language item required, but not found: `{}`",
-                             stringify!($name)).as_slice());
+            sess.err(&format!("language item required, but not found: `{}`",
+                              stringify!($name)));
 
         }
     )*
@@ -108,9 +108,9 @@ fn register(&mut self, name: &str, span: Span) {
 
 impl<'a, 'v> Visitor<'v> for Context<'a> {
     fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
-        match lang_items::extract(i.attrs.as_slice()) {
+        match lang_items::extract(&i.attrs) {
             None => {}
-            Some(lang_item) => self.register(lang_item.get(), i.span),
+            Some(lang_item) => self.register(&lang_item, i.span),
         }
         visit::walk_foreign_item(self, i)
     }
index 110e672b70f87888484a02c1d07f4cc81c6e73a5..818af33c34d142a4e4650dc57ddf8c961e5d7da8 100644 (file)
@@ -24,7 +24,7 @@ struct RegistrarFinder {
 impl<'v> Visitor<'v> for RegistrarFinder {
     fn visit_item(&mut self, item: &ast::Item) {
         if let ast::ItemFn(..) = item.node {
-            if attr::contains_name(item.attrs.as_slice(),
+            if attr::contains_name(&item.attrs,
                                    "plugin_registrar") {
                 self.registrars.push((item.id, item.span));
             }
index dd0b0a63ced9de64a3b63eddf14ace3d25b26bc6..a2ce474eda84088597cf6c467f07fd0de48bcb40 100644 (file)
 use std::env;
 use std::dynamic_lib::DynamicLibrary;
 use std::collections::HashSet;
+use std::borrow::ToOwned;
 use syntax::ast;
 use syntax::attr;
-use syntax::codemap::Span;
+use syntax::codemap::{Span, COMMAND_LINE_SP};
 use syntax::parse::token;
 use syntax::ptr::P;
 use syntax::visit;
@@ -33,7 +34,7 @@
 
 pub struct PluginRegistrar {
     pub fun: PluginRegistrarFun,
-    pub args: P<ast::MetaItem>,
+    pub args: Vec<P<ast::MetaItem>>,
 }
 
 /// Information about loaded plugins.
@@ -81,10 +82,34 @@ pub fn load_plugins(sess: &Session, krate: &ast::Crate,
 
     visit::walk_crate(&mut loader, krate);
 
+    for attr in &krate.attrs {
+        if !attr.check_name("plugin") {
+            continue;
+        }
+
+        let plugins = match attr.meta_item_list() {
+            Some(xs) => xs,
+            None => {
+                sess.span_err(attr.span, "malformed plugin attribute");
+                continue;
+            }
+        };
+
+        for plugin in plugins {
+            if plugin.value_str().is_some() {
+                sess.span_err(attr.span, "malformed plugin attribute");
+                continue;
+            }
+
+            let args = plugin.meta_item_list().map(ToOwned::to_owned).unwrap_or_default();
+            loader.load_plugin(CrateOrString::Str(plugin.span, &*plugin.name()),
+                               args);
+        }
+    }
+
     if let Some(plugins) = addl_plugins {
-        for plugin in &plugins {
-            loader.load_plugin(CrateOrString::Str(plugin.as_slice()),
-                                                  None, None, None)
+        for plugin in plugins {
+            loader.load_plugin(CrateOrString::Str(COMMAND_LINE_SP, &plugin), vec![]);
         }
     }
 
@@ -104,21 +129,19 @@ fn visit_item(&mut self, item: &ast::Item) {
         }
 
         // Parse the attributes relating to macro / plugin loading.
-        let mut plugin_attr = None;
         let mut macro_selection = Some(HashSet::new());  // None => load all
         let mut reexport = HashSet::new();
         for attr in &item.attrs {
             let mut used = true;
-            match attr.name().get() {
+            match &attr.name()[] {
                 "phase" => {
-                    self.sess.span_err(attr.span, "#[phase] is deprecated; use \
-                                       #[macro_use], #[plugin], and/or #[no_link]");
+                    self.sess.span_err(attr.span, "#[phase] is deprecated");
                 }
                 "plugin" => {
-                    if plugin_attr.is_some() {
-                        self.sess.span_err(attr.span, "#[plugin] specified multiple times");
-                    }
-                    plugin_attr = Some(attr.node.value.clone());
+                    self.sess.span_err(attr.span, "#[plugin] on `extern crate` is deprecated");
+                    self.sess.span_help(attr.span, &format!("use a crate attribute instead, \
+                                                            i.e. #![plugin({})]",
+                                                            item.ident.as_str())[]);
                 }
                 "macro_use" => {
                     let names = attr.meta_item_list();
@@ -160,10 +183,7 @@ fn visit_item(&mut self, item: &ast::Item) {
             }
         }
 
-        self.load_plugin(CrateOrString::Krate(item),
-                         plugin_attr,
-                         macro_selection,
-                         Some(reexport))
+        self.load_macros(item, macro_selection, Some(reexport))
     }
 
     fn visit_mac(&mut self, _: &ast::Mac) {
@@ -173,38 +193,25 @@ fn visit_mac(&mut self, _: &ast::Mac) {
 }
 
 impl<'a> PluginLoader<'a> {
-    pub fn load_plugin<'b>(&mut self,
-                           c: CrateOrString<'b>,
-                           plugin_attr: Option<P<ast::MetaItem>>,
+    pub fn load_macros<'b>(&mut self,
+                           vi: &ast::Item,
                            macro_selection: Option<HashSet<token::InternedString>>,
                            reexport: Option<HashSet<token::InternedString>>) {
-        let mut macros = vec![];
-        let mut registrar = None;
-
-        let load_macros = match (macro_selection.as_ref(), reexport.as_ref()) {
-            (Some(sel), Some(re)) => sel.len() != 0 || re.len() != 0,
-            _ => true,
-        };
-        let load_registrar = plugin_attr.is_some();
-
-        if let CrateOrString::Krate(vi) = c {
-            if load_macros && !self.span_whitelist.contains(&vi.span) {
-                self.sess.span_err(vi.span, "an `extern crate` loading macros must be at \
-                                             the crate root");
+        if let (Some(sel), Some(re)) = (macro_selection.as_ref(), reexport.as_ref()) {
+            if sel.is_empty() && re.is_empty() {
+                return;
             }
-       }
+        }
 
-        if load_macros || load_registrar {
-            let pmd = self.reader.read_plugin_metadata(c);
-            if load_macros {
-                macros = pmd.exported_macros();
-            }
-            if load_registrar {
-                registrar = pmd.plugin_registrar();
-            }
+        if !self.span_whitelist.contains(&vi.span) {
+            self.sess.span_err(vi.span, "an `extern crate` loading macros must be at \
+                                         the crate root");
+            return;
         }
 
-        for mut def in macros {
+        let pmd = self.reader.read_plugin_metadata(CrateOrString::Krate(vi));
+
+        for mut def in pmd.exported_macros() {
             let name = token::get_ident(def.ident);
             def.use_locally = match macro_selection.as_ref() {
                 None => true,
@@ -217,12 +224,21 @@ pub fn load_plugin<'b>(&mut self,
             };
             self.plugins.macros.push(def);
         }
+    }
+
+    pub fn load_plugin<'b>(&mut self,
+                           c: CrateOrString<'b>,
+                           args: Vec<P<ast::MetaItem>>) {
+        let registrar = {
+            let pmd = self.reader.read_plugin_metadata(c);
+            pmd.plugin_registrar()
+        };
 
         if let Some((lib, symbol)) = registrar {
             let fun = self.dylink_registrar(c, lib, symbol);
             self.plugins.registrars.push(PluginRegistrar {
                 fun: fun,
-                args: plugin_attr.unwrap(),
+                args: args,
             });
         }
     }
index fd8873454b4d983fe21831454c17fe083744075e..711ed43fe06062eec3590fa6b52ceeebeaaf398c 100644 (file)
 //!
 //! ```rust
 //! #![feature(plugin)]
-//!
-//! #[plugin]
-//! extern crate myplugin;
+//! #![plugin(myplugin)]
 //! ```
 //!
-//! If you don't need the plugin crate available at runtime, use
-//! `#[no_link]` as well.
-//!
 //! See [the compiler plugin guide](../../guide-plugin.html)
 //! for more examples.
 
index f6fb1c2d41928ad57cabd02a69f56cf9842474ff..12634204f8b12f2bd31c02dc36d8ccf8b973c8c1 100644 (file)
@@ -37,7 +37,7 @@ pub struct Registry<'a> {
     pub sess: &'a Session,
 
     #[doc(hidden)]
-    pub args_hidden: Option<P<ast::MetaItem>>,
+    pub args_hidden: Option<Vec<P<ast::MetaItem>>>,
 
     #[doc(hidden)]
     pub krate_span: Span,
@@ -65,11 +65,14 @@ pub fn new(sess: &'a Session, krate: &ast::Crate) -> Registry<'a> {
         }
     }
 
-    /// Get the `#[plugin]` attribute used to load this plugin.
+    /// Get the plugin's arguments, if any.
     ///
-    /// This gives access to arguments passed via `#[plugin=...]` or
-    /// `#[plugin(...)]`.
-    pub fn args<'b>(&'b self) -> &'b P<ast::MetaItem> {
+    /// These are specified inside the `plugin` crate attribute as
+    ///
+    /// ```no_run
+    /// #![plugin(my_plugin_name(... args ...))]
+    /// ```
+    pub fn args<'b>(&'b self) -> &'b Vec<P<ast::MetaItem>> {
         self.args_hidden.as_ref().expect("args not set")
     }
 
index 88f6dc673cf18f8e4b8ab2aaf97e92b03c840272..cd664b7388cd877c9bdb7e0e500ccef519963c8d 100644 (file)
 use syntax::parse;
 use syntax::parse::token::InternedString;
 
+use getopts;
 use std::collections::HashMap;
 use std::collections::hash_map::Entry::{Occupied, Vacant};
-use getopts;
+use std::env;
 use std::fmt;
 
 use llvm;
@@ -132,7 +133,6 @@ pub enum UnstableFeatures {
 }
 
 #[derive(Clone, PartialEq, Eq)]
-#[allow(missing_copy_implementations)]
 pub enum PrintRequest {
     FileNames,
     Sysroot,
@@ -290,7 +290,6 @@ macro_rules! options {
      $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
 (
     #[derive(Clone)]
-    #[allow(missing_copy_implementations)]
     pub struct $struct_name { $(pub $opt: $t),* }
 
     pub fn $defaultfn() -> $struct_name {
@@ -638,7 +637,7 @@ pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
     let target = match Target::search(&opts.target_triple[]) {
         Ok(t) => t,
         Err(e) => {
-            sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice());
+            sp.handler().fatal(&format!("Error loading target specification: {}", e));
     }
     };
 
@@ -738,7 +737,8 @@ pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
     vec![
         opt::flag("h", "help", "Display this message"),
         opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
-        opt::multi("L", "",   "Add a directory to the library search path", "PATH"),
+        opt::multi("L", "",   "Add a directory to the library search path",
+                   "[KIND=]PATH"),
         opt::multi("l", "",   "Link the generated crate(s) to the specified native
                              library NAME. The optional KIND can be one of,
                              static, dylib, or framework. If omitted, dylib is
@@ -822,7 +822,6 @@ pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
 }
 
 pub fn build_session_options(matches: &getopts::Matches) -> Options {
-
     let unparsed_crate_types = matches.opt_strs("crate-type");
     let crate_types = parse_crate_types_from_list(unparsed_crate_types)
         .unwrap_or_else(|e| early_error(&e[]));
@@ -855,7 +854,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
         let unparsed_output_types = matches.opt_strs("emit");
         for unparsed_output_type in &unparsed_output_types {
             for part in unparsed_output_type.split(',') {
-                let output_type = match part.as_slice() {
+                let output_type = match part {
                     "asm" => OutputTypeAssembly,
                     "llvm-ir" => OutputTypeLlvmAssembly,
                     "llvm-bc" => OutputTypeBitcode,
@@ -896,9 +895,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
                 Some(2) => Default,
                 Some(3) => Aggressive,
                 Some(arg) => {
-                    early_error(format!("optimization level needs to be \
-                                         between 0-3 (instead was `{}`)",
-                                        arg).as_slice());
+                    early_error(&format!("optimization level needs to be \
+                                          between 0-3 (instead was `{}`)",
+                                         arg));
                 }
             }
         }
@@ -915,9 +914,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
             Some(1) => LimitedDebugInfo,
             Some(2) => FullDebugInfo,
             Some(arg) => {
-                early_error(format!("debug info level needs to be between \
-                                     0-2 (instead was `{}`)",
-                                    arg).as_slice());
+                early_error(&format!("debug info level needs to be between \
+                                      0-2 (instead was `{}`)",
+                                     arg));
             }
         }
     };
@@ -936,9 +935,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
                 "framework" => cstore::NativeFramework,
                 "static" => cstore::NativeStatic,
                 s => {
-                    early_error(format!("unknown library kind `{}`, expected \
-                                         one of dylib, framework, or static",
-                                        s).as_slice());
+                    early_error(&format!("unknown library kind `{}`, expected \
+                                          one of dylib, framework, or static",
+                                         s));
                 }
             };
             return (name.to_string(), kind)
@@ -967,12 +966,12 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
     let write_dependency_info = (output_types.contains(&OutputTypeDepInfo), None);
 
     let prints = matches.opt_strs("print").into_iter().map(|s| {
-        match s.as_slice() {
+        match &*s {
             "crate-name" => PrintRequest::CrateName,
             "file-names" => PrintRequest::FileNames,
             "sysroot" => PrintRequest::Sysroot,
             req => {
-                early_error(format!("unknown print request `{}`", req).as_slice())
+                early_error(&format!("unknown print request `{}`", req))
             }
         }
     }).collect::<Vec<_>>();
@@ -1042,7 +1041,22 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
         crate_name: crate_name,
         alt_std_name: None,
         libs: libs,
-        unstable_features: UnstableFeatures::Disallow
+        unstable_features: get_unstable_features_setting(),
+    }
+}
+
+pub fn get_unstable_features_setting() -> UnstableFeatures {
+    // Whether this is a feature-staged build, i.e. on the beta or stable channel
+    let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
+    // The secret key needed to get through the rustc build itself by
+    // subverting the unstable features lints
+    let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
+    // The matching key to the above, only known by the build system
+    let bootstrap_provided_key = env::var_string("RUSTC_BOOTSTRAP_KEY").ok();
+    match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
+        (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
+        (true, _, _) => UnstableFeatures::Disallow,
+        (false, _, _) => UnstableFeatures::Default
     }
 }
 
index 07fbecbdebcfc26aff93e7f6a69ab460d8d3ced6..bd44dbe78f5438d8a86cbcad98df0732895df8e1 100644 (file)
@@ -332,7 +332,7 @@ pub fn build_session_(sopts: config::Options,
         Ok(t) => t,
         Err(e) => {
             span_diagnostic.handler()
-                .fatal((format!("Error loading host specification: {}", e)).as_slice());
+                .fatal(&format!("Error loading host specification: {}", e));
     }
     };
     let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
index c6436d47c73c86421747e29deb855d1f74b648df..c314a999f246119cf1ca7d340b5c8586f0a245e3 100644 (file)
@@ -25,6 +25,7 @@ pub enum PathKind {
     Native,
     Crate,
     Dependency,
+    Framework,
     ExternFlag,
     All,
 }
@@ -41,6 +42,8 @@ pub fn add_path(&mut self, path: &str) {
             (PathKind::Crate, &path["crate=".len()..])
         } else if path.starts_with("dependency=") {
             (PathKind::Dependency, &path["dependency=".len()..])
+        } else if path.starts_with("framework=") {
+            (PathKind::Framework, &path["framework=".len()..])
         } else if path.starts_with("all=") {
             (PathKind::All, &path["all=".len()..])
         } else {
index b77a70f1f5d5a6467378f6262760eee94573d963..d3d0f56c3ce904b7836f4f51ea80c4d4e39d2267 100644 (file)
@@ -187,8 +187,8 @@ pub fn can_reach<T, S>(edges_map: &HashMap<T, Vec<T>, S>, source: T,
 /// ```
 /// pub fn memoized<T: Clone, U: Clone, M: MutableMap<T, U>>(
 ///    cache: &RefCell<M>,
-///    f: &|&: T| -> U
-/// ) -> impl |&: T| -> U {
+///    f: &|T| -> U
+/// ) -> impl |T| -> U {
 /// ```
 /// but currently it is not possible.
 ///
index 8da06e63daefcf07ee3d07d7d876d3447e442ea8..f8e3defe19d632ac9c6b40ec63edc804f384ed1f 100644 (file)
@@ -46,7 +46,6 @@ pub fn DefIdSet() -> DefIdSet { FnvHashSet() }
 ///
 /// This uses FNV hashing, as described here:
 /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
-#[allow(missing_copy_implementations)]
 pub struct FnvHasher(u64);
 
 impl Default for FnvHasher {
index 458701f2dd7626c2746206c5bccacfb5fa5641bd..c72b7fdf7ad4d63c04fbd526f62571365abc4bf1 100644 (file)
@@ -86,7 +86,7 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
     return match region {
       ReScope(scope) => {
         let new_string;
-        let on_unknown_scope = |&:| {
+        let on_unknown_scope = || {
           (format!("unknown scope: {:?}.  Please report a bug.", scope), None)
         };
         let span = match scope.span(&cx.map) {
@@ -116,7 +116,7 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region)
             region::CodeExtent::Remainder(r) => {
                 new_string = format!("block suffix following statement {}",
                                      r.first_statement_index);
-                new_string.as_slice()
+                &*new_string
             }
         };
         explain_span(cx, scope_decorated_tag, span)
@@ -217,7 +217,7 @@ pub fn region_to_string(cx: &ctxt, prefix: &str, space: bool, region: Region) ->
     match region {
         ty::ReScope(_) => prefix.to_string(),
         ty::ReEarlyBound(_, _, _, name) => {
-            token::get_name(name).get().to_string()
+            token::get_name(name).to_string()
         }
         ty::ReLateBound(_, br) => bound_region_to_string(cx, prefix, space, br),
         ty::ReFree(ref fr) => bound_region_to_string(cx, prefix, space, fr.bound_region),
@@ -263,7 +263,7 @@ fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>,
         match unsafety {
             ast::Unsafety::Normal => {}
             ast::Unsafety::Unsafe => {
-                s.push_str(unsafety.to_string().as_slice());
+                s.push_str(&unsafety.to_string());
                 s.push(' ');
             }
         };
@@ -277,7 +277,7 @@ fn bare_fn_to_string<'tcx>(cx: &ctxt<'tcx>,
         match ident {
             Some(i) => {
                 s.push(' ');
-                s.push_str(token::get_ident(i).get());
+                s.push_str(&token::get_ident(i));
             }
             _ => { }
         }
@@ -315,7 +315,7 @@ fn push_sig_to_string<'tcx>(cx: &ctxt<'tcx>,
             .iter()
             .map(|a| ty_to_string(cx, *a))
             .collect::<Vec<_>>();
-        s.push_str(strs.connect(", ").as_slice());
+        s.push_str(&strs.connect(", "));
         if sig.0.variadic {
             s.push_str(", ...");
         }
@@ -392,7 +392,7 @@ fn infer_ty_to_string(cx: &ctxt, ty: ty::InferTy) -> String {
         ty_enum(did, substs) | ty_struct(did, substs) => {
             let base = ty::item_path_str(cx, did);
             let generics = ty::lookup_item_type(cx, did).generics;
-            parameterized(cx, base.as_slice(), substs, &generics, did, &[])
+            parameterized(cx, &base, substs, &generics, did, &[])
         }
         ty_trait(ref data) => {
             data.user_string(cx)
@@ -643,7 +643,7 @@ fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
         let base = ty::item_path_str(tcx, trait_ref.def_id);
         let trait_def = ty::lookup_trait_def(tcx, trait_ref.def_id);
         parameterized(tcx,
-                      base.as_slice(),
+                      &base,
                       trait_ref.substs,
                       &trait_def.generics,
                       trait_ref.def_id,
@@ -780,7 +780,7 @@ fn repr(&self, tcx: &ctxt<'tcx>) -> String {
         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
         format!("TraitRef({}, {})",
                 self.substs.self_ty().repr(tcx),
-                parameterized(tcx, base.as_slice(), self.substs,
+                parameterized(tcx, &base, self.substs,
                               &trait_def.generics, self.def_id, &[]))
     }
 }
@@ -1020,19 +1020,19 @@ fn repr(&self, tcx: &ctxt<'tcx>) -> String {
 
 impl<'tcx> Repr<'tcx> for ast::Name {
     fn repr(&self, _tcx: &ctxt) -> String {
-        token::get_name(*self).get().to_string()
+        token::get_name(*self).to_string()
     }
 }
 
 impl<'tcx> UserString<'tcx> for ast::Name {
     fn user_string(&self, _tcx: &ctxt) -> String {
-        token::get_name(*self).get().to_string()
+        token::get_name(*self).to_string()
     }
 }
 
 impl<'tcx> Repr<'tcx> for ast::Ident {
     fn repr(&self, _tcx: &ctxt) -> String {
-        token::get_ident(*self).get().to_string()
+        token::get_ident(*self).to_string()
     }
 }
 
@@ -1220,7 +1220,7 @@ fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
                 }
             })
         });
-        let names: Vec<_> = names.iter().map(|s| s.get()).collect();
+        let names: Vec<_> = names.iter().map(|s| &s[]).collect();
 
         let value_str = unbound_value.user_string(tcx);
         if names.len() == 0 {
@@ -1235,7 +1235,7 @@ impl<'tcx> UserString<'tcx> for ty::TraitRef<'tcx> {
     fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
         let path_str = ty::item_path_str(tcx, self.def_id);
         let trait_def = ty::lookup_trait_def(tcx, self.def_id);
-        parameterized(tcx, path_str.as_slice(), self.substs,
+        parameterized(tcx, &path_str, self.substs,
                       &trait_def.generics, self.def_id, &[])
     }
 }
@@ -1248,7 +1248,7 @@ fn user_string(&self, tcx: &ctxt<'tcx>) -> String {
 
 impl<'tcx> UserString<'tcx> for ast::Ident {
     fn user_string(&self, _tcx: &ctxt) -> String {
-        token::get_name(self.name).get().to_string()
+        token::get_name(self.name).to_string()
     }
 }
 
index 151173b3a40850b55df8a3a8b686cd27ee1a8e70..8fbc682246f470078c18e5f6025ccbfc2e61b4d7 100644 (file)
@@ -46,7 +46,6 @@ pub struct SnapshotVec<D:SnapshotVecDelegate> {
 }
 
 // Snapshots are tokens that should be created/consumed linearly.
-#[allow(missing_copy_implementations)]
 pub struct Snapshot {
     // Length of the undo log at the time the snapshot was taken.
     length: uint,
index 286a3936314a5540500550f99dd8087432f2bf8c..6654a46f7c31b51cdaee38add94af4f904eb793e 100644 (file)
@@ -259,7 +259,7 @@ fn input_str(&mut self, input: &str) {
     /// newly allocated vec of bytes.
     fn result_bytes(&mut self) -> Vec<u8> {
         let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
-        self.result(buf.as_mut_slice());
+        self.result(&mut buf);
         buf
     }
 
@@ -560,7 +560,7 @@ fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
         // Test that it works when accepting the message all at once
         for t in tests {
             sh.reset();
-            sh.input_str(t.input.as_slice());
+            sh.input_str(&t.input);
             let out_str = sh.result_str();
             assert!(out_str == t.output_str);
         }
@@ -606,7 +606,7 @@ fn test_sha256() {
 
         let mut sh = box Sha256::new();
 
-        test_hash(&mut *sh, tests.as_slice());
+        test_hash(&mut *sh, &tests);
     }
 
     /// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is
@@ -630,7 +630,7 @@ fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, expec
         let result_str = digest.result_str();
         let result_bytes = digest.result_bytes();
 
-        assert_eq!(expected, result_str.as_slice());
+        assert_eq!(expected, result_str);
 
         let expected_vec: Vec<u8> = expected.from_hex()
                                             .unwrap()
index 2823b2e9d74c3a30cc032938702bf50d2207fe92..c33d10bfbab39aaef7a08149d03304f76cfe0230 100644 (file)
@@ -329,7 +329,7 @@ fn visit_mac(&mut self, mac: &Mac) {
             // macro invocations, namely macro_rules definitions,
             // *can* appear as items, even in the expanded crate AST.
 
-            if macro_name(mac).get() == "macro_rules" {
+            if &macro_name(mac)[] == "macro_rules" {
                 // Pretty-printing definition to a string strips out
                 // surface artifacts (currently), such as the span
                 // information, yielding a content-based hash.
index bffee9d49334da43c3bedcb1d7743a7e66523f1b..afb5c948f188542b20cb63c72c03b15d38d9be0e 100644 (file)
@@ -227,7 +227,7 @@ pub fn from_json(obj: Json) -> Target {
 
         let handler = diagnostic::default_handler(diagnostic::Auto, None, true);
 
-        let get_req_field = |&: name: &str| {
+        let get_req_field = |name: &str| {
             match obj.find(name)
                      .map(|s| s.as_string())
                      .and_then(|os| os.map(|s| s.to_string())) {
index 031607728797ed29cd35716e2e776f20490c3a5c..370a5d48decaec85298da73575468e6a98efb5f0 100644 (file)
@@ -12,6 +12,7 @@
 #![feature(staged_api)]
 #![staged_api]
 #![crate_type = "rlib"]
+#![feature(no_std)]
 #![no_std]
 #![unstable(feature = "rustc_private")]
 
@@ -281,6 +282,13 @@ fn not(self) -> $BitFlags {
     };
 }
 
+// This is a no_std crate. So the test code's invocation of #[derive] etc, via
+// bitflags!, will use names from the underlying crates.
+#[cfg(test)]
+mod core {
+    pub use std::{fmt, hash, clone, cmp, marker, option};
+}
+
 #[cfg(test)]
 #[allow(non_upper_case_globals)]
 mod tests {
index b8d736ab9ca677fcf9e97fd555357b69c67479f6..91f1121deaab17e4486c8475a0cb30f6c119dc99 100644 (file)
@@ -19,6 +19,7 @@
 use self::UseError::*;
 
 use borrowck::*;
+use borrowck::InteriorKind::{InteriorElement, InteriorField};
 use rustc::middle::expr_use_visitor as euv;
 use rustc::middle::mem_categorization as mc;
 use rustc::middle::region;
@@ -743,15 +744,16 @@ fn check_if_assigned_path_is_moved(&self,
                 self.check_if_assigned_path_is_moved(id, span,
                                                      use_kind, lp_base);
             }
-            LpExtend(ref lp_base, _, LpInterior(_)) => {
+            LpExtend(ref lp_base, _, LpInterior(InteriorField(_))) => {
                 // assigning to `P.f` is ok if assigning to `P` is ok
                 self.check_if_assigned_path_is_moved(id, span,
                                                      use_kind, lp_base);
             }
+            LpExtend(ref lp_base, _, LpInterior(InteriorElement(..))) |
             LpExtend(ref lp_base, _, LpDeref(_)) => {
-                // assigning to `(*P)` requires that `P` be initialized
-                self.check_if_path_is_moved(id, span,
-                                            use_kind, lp_base);
+                // assigning to `P[i]` requires `P` is initialized
+                // assigning to `(*P)` requires `P` is initialized
+                self.check_if_path_is_moved(id, span, use_kind, lp_base);
             }
         }
     }
index 2100d5a9bc307cec26d3283c165b59b68b626291..682a5f2f5ace6d28232772f48d0bca01baac3f2a 100644 (file)
 //! which contains an empty set of actions, still has a purpose---it
 //! prevents moves from `LV`. I chose not to make `MOVE` a fourth kind of
 //! action because that would imply that sometimes moves are permitted
-//! from restrictived values, which is not the case.
+//! from restricted values, which is not the case.
 //!
 //! #### Example
 //!
index 6f51ba3118278836f7822b13b9c4673300975b20..bee1ada28e31465dafee3e741f02b7c3a58e72a4 100644 (file)
@@ -14,6 +14,7 @@
 
 use self::Fragment::*;
 
+use borrowck::InteriorKind::{InteriorField, InteriorElement};
 use borrowck::{LoanPath};
 use borrowck::LoanPathKind::{LpVar, LpUpvar, LpDowncast, LpExtend};
 use borrowck::LoanPathElem::{LpDeref, LpInterior};
@@ -43,7 +44,7 @@ enum Fragment {
 
 impl Fragment {
     fn loan_path_repr<'tcx>(&self, move_data: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) -> String {
-        let repr = |&: mpi| move_data.path_loan_path(mpi).repr(tcx);
+        let repr = |mpi| move_data.path_loan_path(mpi).repr(tcx);
         match *self {
             Just(mpi) => repr(mpi),
             AllButOneFrom(mpi) => format!("$(allbutone {})", repr(mpi)),
@@ -53,7 +54,7 @@ fn loan_path_repr<'tcx>(&self, move_data: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>)
     fn loan_path_user_string<'tcx>(&self,
                                    move_data: &MoveData<'tcx>,
                                    tcx: &ty::ctxt<'tcx>) -> String {
-        let user_string = |&: mpi| move_data.path_loan_path(mpi).user_string(tcx);
+        let user_string = |mpi| move_data.path_loan_path(mpi).user_string(tcx);
         match *self {
             Just(mpi) => user_string(mpi),
             AllButOneFrom(mpi) => format!("$(allbutone {})", user_string(mpi)),
@@ -139,9 +140,9 @@ pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>,
 
     if !span_err && !print { return; }
 
-    let instrument_all_paths = |&: kind, vec_rc: &Vec<MovePathIndex>| {
+    let instrument_all_paths = |kind, vec_rc: &Vec<MovePathIndex>| {
         for (i, mpi) in vec_rc.iter().enumerate() {
-            let render = |&:| this.path_loan_path(*mpi).user_string(tcx);
+            let render = || this.path_loan_path(*mpi).user_string(tcx);
             if span_err {
                 tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render())[]);
             }
@@ -151,9 +152,9 @@ pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>,
         }
     };
 
-    let instrument_all_fragments = |&: kind, vec_rc: &Vec<Fragment>| {
+    let instrument_all_fragments = |kind, vec_rc: &Vec<Fragment>| {
         for (i, f) in vec_rc.iter().enumerate() {
-            let render = |&:| f.loan_path_user_string(this, tcx);
+            let render = || f.loan_path_user_string(this, tcx);
             if span_err {
                 tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render())[]);
             }
@@ -186,11 +187,11 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) {
     let mut moved = mem::replace(&mut fragments.moved_leaf_paths, vec![]);
     let mut assigned = mem::replace(&mut fragments.assigned_leaf_paths, vec![]);
 
-    let path_lps = |&: mpis: &[MovePathIndex]| -> Vec<String> {
+    let path_lps = |mpis: &[MovePathIndex]| -> Vec<String> {
         mpis.iter().map(|mpi| this.path_loan_path(*mpi).repr(tcx)).collect()
     };
 
-    let frag_lps = |&: fs: &[Fragment]| -> Vec<String> {
+    let frag_lps = |fs: &[Fragment]| -> Vec<String> {
         fs.iter().map(|f| f.loan_path_repr(this, tcx)).collect()
     };
 
@@ -300,12 +301,16 @@ fn add_fragment_siblings<'tcx>(this: &MoveData<'tcx>,
         LpExtend(_, _, LpDeref(mc::Implicit(..)))    |
         LpExtend(_, _, LpDeref(mc::BorrowedPtr(..))) => {}
 
-        // FIXME(pnkfelix): LV[j] should be tracked, at least in the
+        // FIXME (pnkfelix): LV[j] should be tracked, at least in the
         // sense of we will track the remaining drop obligation of the
         // rest of the array.
         //
-        // LV[j] is not tracked precisely
-        LpExtend(_, _, LpInterior(mc::InteriorElement(_))) => {
+        // Well, either that or LV[j] should be made illegal.
+        // But even then, we will need to deal with destructuring
+        // bind.
+        //
+        // Anyway, for now: LV[j] is not tracked precisely
+        LpExtend(_, _, LpInterior(InteriorElement(..))) => {
             let mp = this.move_path(tcx, lp.clone());
             gathered_fragments.push(AllButOneFrom(mp));
         }
@@ -313,7 +318,7 @@ fn add_fragment_siblings<'tcx>(this: &MoveData<'tcx>,
         // field access LV.x and tuple access LV#k are the cases
         // we are interested in
         LpExtend(ref loan_parent, mc,
-                 LpInterior(mc::InteriorField(ref field_name))) => {
+                 LpInterior(InteriorField(ref field_name))) => {
             let enum_variant_info = match loan_parent.kind {
                 LpDowncast(ref loan_parent_2, variant_def_id) =>
                     Some((variant_def_id, loan_parent_2.clone())),
@@ -343,7 +348,7 @@ fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>,
                                                                         Rc<LoanPath<'tcx>>)>) {
     let parent_ty = parent_lp.to_type();
 
-    let mut add_fragment_sibling_local = |&mut : field_name, variant_did| {
+    let mut add_fragment_sibling_local = |field_name, variant_did| {
         add_fragment_sibling_core(
             this, tcx, gathered_fragments, parent_lp.clone(), mc, field_name, origin_lp,
             variant_did);
@@ -452,7 +457,7 @@ fn add_fragment_sibling_core<'tcx>(this: &MoveData<'tcx>,
         LpVar(..) | LpUpvar(..) | LpExtend(..) => enum_variant_did,
     };
 
-    let loan_path_elem = LpInterior(mc::InteriorField(new_field_name));
+    let loan_path_elem = LpInterior(InteriorField(new_field_name));
     let new_lp_type = match new_field_name {
         mc::NamedField(ast_name) =>
             ty::named_element_ty(tcx, parent.to_type(), ast_name, opt_variant_did),
index ca1fba53de42aa11f6fa1c39929017abaa371e91..da53e9fac11875e6974092c8e9c4b73605f31f99 100644 (file)
@@ -16,6 +16,8 @@
 use borrowck::move_data::*;
 use rustc::middle::expr_use_visitor as euv;
 use rustc::middle::mem_categorization as mc;
+use rustc::middle::mem_categorization::Typer;
+use rustc::middle::mem_categorization::InteriorOffsetKind as Kind;
 use rustc::middle::ty;
 use rustc::util::ppaux::Repr;
 use std::rc::Rc;
@@ -156,6 +158,7 @@ pub fn gather_assignment<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
                              mode);
 }
 
+// (keep in sync with move_error::report_cannot_move_out_of )
 fn check_and_get_illegal_move_origin<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
                                                cmt: &mc::cmt<'tcx>)
                                                -> Option<mc::cmt<'tcx>> {
@@ -174,7 +177,8 @@ fn check_and_get_illegal_move_origin<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
         }
 
         mc::cat_downcast(ref b, _) |
-        mc::cat_interior(ref b, _) => {
+        mc::cat_interior(ref b, mc::InteriorField(_)) |
+        mc::cat_interior(ref b, mc::InteriorElement(Kind::Pattern, _)) => {
             match b.ty.sty {
                 ty::ty_struct(did, _) | ty::ty_enum(did, _) => {
                     if ty::has_dtor(bccx.tcx, did) {
@@ -189,6 +193,11 @@ fn check_and_get_illegal_move_origin<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
             }
         }
 
+        mc::cat_interior(_, mc::InteriorElement(Kind::Index, _)) => {
+            // Forbid move of arr[i] for arr: [T; 3]; see RFC 533.
+            Some(cmt.clone())
+        }
+
         mc::cat_deref(ref b, _, mc::Unique) => {
             check_and_get_illegal_move_origin(bccx, b)
         }
index d9e86bd4b6d68d466c0a8cf147efb16405b0577a..b00973c82bd97d83586df77c79069aff58e72788 100644 (file)
@@ -10,6 +10,8 @@
 
 use borrowck::BorrowckCtxt;
 use rustc::middle::mem_categorization as mc;
+use rustc::middle::mem_categorization::Typer;
+use rustc::middle::mem_categorization::InteriorOffsetKind as Kind;
 use rustc::middle::ty;
 use rustc::util::ppaux::UserString;
 use std::cell::RefCell;
@@ -110,6 +112,7 @@ fn append_to_grouped_errors<'tcx>(grouped_errors: &mut Vec<GroupedMoveErrors<'tc
     }
 }
 
+// (keep in sync with gather_moves::check_and_get_illegal_move_origin )
 fn report_cannot_move_out_of<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
                                        move_from: mc::cmt<'tcx>) {
     match move_from.cat {
@@ -121,8 +124,18 @@ fn report_cannot_move_out_of<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
                                   move_from.descriptive_string(bccx.tcx))[]);
         }
 
+        mc::cat_interior(ref b, mc::InteriorElement(Kind::Index, _)) => {
+            let expr = bccx.tcx.map.expect_expr(move_from.id);
+            if let ast::ExprIndex(..) = expr.node {
+                bccx.span_err(move_from.span,
+                              &format!("cannot move out of type `{}`, \
+                                        a non-copy fixed-size array",
+                                       b.ty.user_string(bccx.tcx))[]);
+            }
+        }
+
         mc::cat_downcast(ref b, _) |
-        mc::cat_interior(ref b, _) => {
+        mc::cat_interior(ref b, mc::InteriorField(_)) => {
             match b.ty.sty {
                 ty::ty_struct(did, _) |
                 ty::ty_enum(did, _) if ty::has_dtor(bccx.tcx, did) => {
index 311229717da1ca23f51a281a71c1e879ec1bc459..7078b2b5f1797c5ccd2d98c26ed0ba014445ce28 100644 (file)
@@ -19,6 +19,8 @@
 use rustc::util::ppaux::Repr;
 use syntax::codemap::Span;
 
+use borrowck::ToInteriorKind;
+
 use std::rc::Rc;
 
 #[derive(Debug)]
@@ -58,7 +60,7 @@ fn restrict(&self,
                 cmt: mc::cmt<'tcx>) -> RestrictionResult<'tcx> {
         debug!("restrict(cmt={})", cmt.repr(self.bccx.tcx));
 
-        let new_lp = |&: v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
+        let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
 
         match cmt.cat.clone() {
             mc::cat_rvalue(..) => {
@@ -96,7 +98,7 @@ fn restrict(&self,
                 // the memory, so no additional restrictions are
                 // needed.
                 let result = self.restrict(cmt_base);
-                self.extend(result, &cmt, LpInterior(i))
+                self.extend(result, &cmt, LpInterior(i.cleaned()))
             }
 
             mc::cat_static_item(..) => {
index b9d2b9ec263ab450480bf3fa02db5c5505a6dd28..0bad55948822f96ff01a55eb645ff889d4fabe8b 100644 (file)
@@ -18,6 +18,8 @@
 pub use self::AliasableViolationKind::*;
 pub use self::MovedValueUseKind::*;
 
+use self::InteriorKind::*;
+
 use rustc::middle::cfg;
 use rustc::middle::dataflow::DataFlowContext;
 use rustc::middle::dataflow::BitwiseOperator;
@@ -314,10 +316,30 @@ fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
 //     b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
 static DOWNCAST_PRINTED_OPERATOR : &'static str = " as ";
 
+// A local, "cleaned" version of `mc::InteriorKind` that drops
+// information that is not relevant to loan-path analysis. (In
+// particular, the distinction between how precisely a array-element
+// is tracked is irrelevant here.)
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub enum InteriorKind {
+    InteriorField(mc::FieldName),
+    InteriorElement(mc::ElementKind),
+}
+
+trait ToInteriorKind { fn cleaned(self) -> InteriorKind; }
+impl ToInteriorKind for mc::InteriorKind {
+    fn cleaned(self) -> InteriorKind {
+        match self {
+            mc::InteriorField(name) => InteriorField(name),
+            mc::InteriorElement(_, elem_kind) => InteriorElement(elem_kind),
+        }
+    }
+}
+
 #[derive(Copy, PartialEq, Eq, Hash, Debug)]
 pub enum LoanPathElem {
     LpDeref(mc::PointerKind),    // `*LV` in doc.rs
-    LpInterior(mc::InteriorKind) // `LV.f` in doc.rs
+    LpInterior(InteriorKind),    // `LV.f` in doc.rs
 }
 
 pub fn closure_to_block(closure_id: ast::NodeId,
@@ -422,7 +444,7 @@ pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
     //! which allows it to share common loan path pieces as it
     //! traverses the CMT.
 
-    let new_lp = |&: v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
+    let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
 
     match cmt.cat {
         mc::cat_rvalue(..) |
@@ -446,7 +468,7 @@ pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
 
         mc::cat_interior(ref cmt_base, ik) => {
             opt_loan_path(cmt_base).map(|lp| {
-                new_lp(LpExtend(lp, cmt.mutbl, LpInterior(ik)))
+                new_lp(LpExtend(lp, cmt.mutbl, LpInterior(ik.cleaned())))
             })
         }
 
@@ -464,7 +486,6 @@ pub fn opt_loan_path<'tcx>(cmt: &mc::cmt<'tcx>) -> Option<Rc<LoanPath<'tcx>>> {
 
 // Errors that can occur
 #[derive(PartialEq)]
-#[allow(missing_copy_implementations)]
 pub enum bckerr_code {
     err_mutbl,
     err_out_of_scope(ty::Region, ty::Region), // superscope, subscope
@@ -798,8 +819,8 @@ pub fn report_aliasability_violation(&self,
             }
             mc::AliasableClosure(id) => {
                 self.tcx.sess.span_err(span,
-                                       format!("{} in a captured outer \
-                                               variable in an `Fn` closure", prefix).as_slice());
+                                       &format!("{} in a captured outer \
+                                                variable in an `Fn` closure", prefix));
                 if let BorrowViolation(euv::ClosureCapture(_)) = kind {
                     // The aliasability violation with closure captures can
                     // happen for nested closures, so we know the enclosing
@@ -907,7 +928,7 @@ pub fn append_loan_path_to_string(&self,
         match loan_path.kind {
             LpUpvar(ty::UpvarId{ var_id: id, closure_expr_id: _ }) |
             LpVar(id) => {
-                out.push_str(ty::local_var_name_str(self.tcx, id).get());
+                out.push_str(&ty::local_var_name_str(self.tcx, id));
             }
 
             LpDowncast(ref lp_base, variant_def_id) => {
@@ -919,12 +940,12 @@ pub fn append_loan_path_to_string(&self,
             }
 
 
-            LpExtend(ref lp_base, _, LpInterior(mc::InteriorField(fname))) => {
+            LpExtend(ref lp_base, _, LpInterior(InteriorField(fname))) => {
                 self.append_autoderefd_loan_path_to_string(&**lp_base, out);
                 match fname {
                     mc::NamedField(fname) => {
                         out.push('.');
-                        out.push_str(token::get_name(fname).get());
+                        out.push_str(&token::get_name(fname));
                     }
                     mc::PositionalField(idx) => {
                         out.push('.');
@@ -933,7 +954,7 @@ pub fn append_loan_path_to_string(&self,
                 }
             }
 
-            LpExtend(ref lp_base, _, LpInterior(mc::InteriorElement(_))) => {
+            LpExtend(ref lp_base, _, LpInterior(InteriorElement(..))) => {
                 self.append_autoderefd_loan_path_to_string(&**lp_base, out);
                 out.push_str("[..]");
             }
@@ -1007,6 +1028,17 @@ fn initial_value(&self) -> bool {
     }
 }
 
+impl<'tcx> Repr<'tcx> for InteriorKind {
+    fn repr(&self, _tcx: &ty::ctxt<'tcx>) -> String {
+        match *self {
+            InteriorField(mc::NamedField(fld)) =>
+                format!("{}", token::get_name(fld)),
+            InteriorField(mc::PositionalField(i)) => format!("#{}", i),
+            InteriorElement(..) => "[]".to_string(),
+        }
+    }
+}
+
 impl<'tcx> Repr<'tcx> for Loan<'tcx> {
     fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
         format!("Loan_{}({}, {:?}, {:?}-{:?}, {})",
index 76c431fa4c58f477bdd3ae971193f36989357da5..6607b5cac9c1dde95227d1c0600576770fdb8440 100644 (file)
@@ -19,7 +19,6 @@
 use rustc::middle::dataflow::BitwiseOperator;
 use rustc::middle::dataflow::DataFlowOperator;
 use rustc::middle::expr_use_visitor as euv;
-use rustc::middle::mem_categorization as mc;
 use rustc::middle::ty;
 use rustc::util::nodemap::{FnvHashMap, NodeSet};
 use rustc::util::ppaux::Repr;
@@ -193,9 +192,13 @@ fn loan_path_is_precise(loan_path: &LoanPath) -> bool {
         LpVar(_) | LpUpvar(_) => {
             true
         }
-        LpExtend(_, _, LpInterior(mc::InteriorElement(_))) => {
-            // Paths involving element accesses do not refer to a unique
+        LpExtend(_, _, LpInterior(InteriorKind::InteriorElement(..))) => {
+            // Paths involving element accesses a[i] do not refer to a unique
             // location, as there is no accurate tracking of the indices.
+            //
+            // (Paths involving element accesses via slice pattern bindings
+            // can in principle be tracked precisely, but that is future
+            // work. For now, continue claiming that they are imprecise.)
             false
         }
         LpDowncast(ref lp_base, _) |
index 8b1b156691af7379ae852699a52e19c51eb9450b..56bf3ae7fd5a30ad536bf4d537c8465b93727a68 100644 (file)
@@ -99,7 +99,7 @@ fn build_set<O:DataFlowOperator, F>(&self,
 
     fn dataflow_loans_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
         let dfcx = &self.analysis_data.loans;
-        let loan_index_to_path = |&mut: loan_index| {
+        let loan_index_to_path = |loan_index| {
             let all_loans = &self.analysis_data.all_loans;
             let l: &borrowck::Loan = &all_loans[loan_index];
             l.loan_path()
@@ -109,7 +109,7 @@ fn dataflow_loans_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
 
     fn dataflow_moves_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
         let dfcx = &self.analysis_data.move_data.dfcx_moves;
-        let move_index_to_path = |&mut: move_index| {
+        let move_index_to_path = |move_index| {
             let move_data = &self.analysis_data.move_data.move_data;
             let moves = move_data.moves.borrow();
             let the_move: &borrowck::move_data::Move = &(*moves)[move_index];
@@ -120,7 +120,7 @@ fn dataflow_moves_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
 
     fn dataflow_assigns_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
         let dfcx = &self.analysis_data.move_data.dfcx_assign;
-        let assign_index_to_path = |&mut: assign_index| {
+        let assign_index_to_path = |assign_index| {
             let move_data = &self.analysis_data.move_data.move_data;
             let assignments = move_data.var_assignments.borrow();
             let assignment: &borrowck::move_data::Assignment = &(*assignments)[assign_index];
index 8ede037594a007557d57fae70632df52507d9313..d82c160fdee9b543fc65d58fa75960c7631daf86 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
@@ -27,6 +27,7 @@
 use rustc_trans::trans;
 use rustc_typeck as typeck;
 use rustc_privacy;
+use super::Compilation;
 
 use serialize::json;
 
@@ -55,7 +56,7 @@ macro_rules! controller_entry_point{($point: ident, $make_state: expr) => ({
             let state = $make_state;
             (control.$point.callback)(state);
         }
-        if control.$point.stop {
+        if control.$point.stop == Compilation::Stop {
             return;
         }
     })}
@@ -171,7 +172,7 @@ pub fn source_name(input: &Input) -> String {
 /// CompileController is used to customise compilation, it allows compilation to
 /// be stopped and/or to call arbitrary code at various points in compilation.
 /// It also allows for various flags to be set to influence what information gets
-/// colelcted during compilation.
+/// collected during compilation.
 ///
 /// This is a somewhat higher level controller than a Session - the Session
 /// controls what happens in each phase, whereas the CompileController controls
@@ -206,15 +207,15 @@ pub fn basic() -> CompileController<'a> {
 }
 
 pub struct PhaseController<'a> {
-    pub stop: bool,
+    pub stop: Compilation,
     pub callback: Box<Fn(CompileState) -> () + 'a>,
 }
 
 impl<'a> PhaseController<'a> {
     pub fn basic() -> PhaseController<'a> {
         PhaseController {
-            stop: false,
-            callback: box |&: _| {},
+            stop: Compilation::Continue,
+            callback: box |_| {},
         }
     }
 }
@@ -350,7 +351,7 @@ pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
     }
 
     if let Some(ref s) = sess.opts.show_span {
-        syntax::show_span::run(sess.diagnostic(), s.as_slice(), &krate);
+        syntax::show_span::run(sess.diagnostic(), s, &krate);
     }
 
     krate
@@ -668,8 +669,8 @@ pub fn phase_3_run_analysis_passes<'tcx>(sess: Session,
         time(time_passes, "stability checking", (), |_|
              stability::check_unstable_api_usage(&ty_cx));
 
-    time(time_passes, "unused feature checking", (), |_|
-         stability::check_unused_features(
+    time(time_passes, "unused lib feature checking", (), |_|
+         stability::check_unused_or_stable_features(
              &ty_cx.sess, lib_features_used));
 
     time(time_passes, "lint checking", (), |_|
@@ -794,7 +795,7 @@ fn write_out_deps(sess: &Session,
         _ => return,
     };
 
-    let result = (|&:| -> old_io::IoResult<()> {
+    let result = (|| -> old_io::IoResult<()> {
         // Build a list of files used to compile the output and
         // write Makefile-compatible dependency rules
         let files: Vec<String> = sess.codemap().files.borrow()
@@ -914,7 +915,7 @@ pub fn build_output_filenames(input: &Input,
 
             // If a crate name is present, we use it as the link name
             let stem = sess.opts.crate_name.clone().or_else(|| {
-                attr::find_crate_name(attrs).map(|n| n.get().to_string())
+                attr::find_crate_name(attrs).map(|n| n.to_string())
             }).unwrap_or(input.filestem());
 
             OutputFilenames {
index 4fe037d852f49c715adf497772a746db53f146dd..ef6e84d3a7641dc77c9c89e470fd9c76756b919a 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
 pub use syntax::diagnostic;
 
 use driver::CompileController;
+use pretty::{PpMode, UserIdentifiedItem};
 
 use rustc_resolve as resolve;
 use rustc_trans::back::link;
 use rustc_trans::save;
 use rustc::session::{config, Session, build_session};
-use rustc::session::config::{Input, PrintRequest, UnstableFeatures};
+use rustc::session::config::{Input, PrintRequest};
 use rustc::lint::Lint;
 use rustc::lint;
 use rustc::metadata;
-use rustc::metadata::creader::CrateOrString::Str;
 use rustc::util::common::time;
 
 use std::cmp::Ordering::Equal;
 pub mod driver;
 pub mod pretty;
 
+
+static BUG_REPORT_URL: &'static str =
+    "http://doc.rust-lang.org/complement-bugreport.html";
+
+
 pub fn run(args: Vec<String>) -> int {
-    monitor(move |:| run_compiler(args.as_slice()));
+    monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
     0
 }
 
-static BUG_REPORT_URL: &'static str =
-    "http://doc.rust-lang.org/complement-bugreport.html";
+// Parse args and run the compiler. This is the primary entry point for rustc.
+// See comments on CompilerCalls below for details about the callbacks argument.
+pub fn run_compiler<'a>(args: &[String],
+                        callbacks: &mut CompilerCalls<'a>) {
+    macro_rules! do_or_return {($expr: expr) => {
+        match $expr {
+            Compilation::Stop => return,
+            Compilation::Continue => {}
+        }
+    }}
 
-fn run_compiler(args: &[String]) {
     let matches = match handle_options(args.to_vec()) {
         Some(matches) => matches,
         None => return
     };
 
     let descriptions = diagnostics_registry();
-    match matches.opt_str("explain") {
-        Some(ref code) => {
-            match descriptions.find_description(&code[]) {
-                Some(ref description) => {
-                    println!("{}", description);
-                }
-                None => {
-                    early_error(&format!("no extended information for {}", code)[]);
-                }
-            }
-            return;
-        },
-        None => ()
-    }
+
+    do_or_return!(callbacks.early_callback(&matches, &descriptions));
 
     let sopts = config::build_session_options(&matches);
-    let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
-    let ofile = matches.opt_str("o").map(|o| Path::new(o));
-    let (input, input_file_path) = match matches.free.len() {
-        0 => {
-            if sopts.describe_lints {
-                let mut ls = lint::LintStore::new();
-                ls.register_builtin(None);
-                describe_lints(&ls, false);
-                return;
-            }
-            let sess = build_session(sopts, None, descriptions);
-            if print_crate_info(&sess, None, &odir, &ofile) {
-                return;
-            }
-            early_error("no input filename given");
-        }
-        1 => {
-            let ifile = &matches.free[0][];
-            if ifile == "-" {
-                let contents = old_io::stdin().read_to_end().unwrap();
-                let src = String::from_utf8(contents).unwrap();
-                (Input::Str(src), None)
-            } else {
-                (Input::File(Path::new(ifile)), Some(Path::new(ifile)))
-            }
+
+    let (odir, ofile) = make_output(&matches);
+    let (input, input_file_path) = match make_input(&matches.free[]) {
+        Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
+        None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
+            Some((input, input_file_path)) => (input, input_file_path),
+            None => return
         }
-        _ => early_error("multiple input filenames provided")
     };
 
-    let mut sopts = sopts;
-    sopts.unstable_features = get_unstable_features_setting();
-
     let mut sess = build_session(sopts, input_file_path, descriptions);
-
-    let cfg = config::build_configuration(&sess);
-    if print_crate_info(&sess, Some(&input), &odir, &ofile) {
-        return
+    if sess.unstable_options() {
+        sess.opts.show_span = matches.opt_str("show-span");
     }
+    let cfg = config::build_configuration(&sess);
 
-    let pretty = if sess.opts.debugging_opts.unstable_options {
-        matches.opt_default("pretty", "normal").map(|a| {
-            // stable pretty-print variants only
-            pretty::parse_pretty(&sess, a.as_slice(), false)
-        })
-    } else {
-        None
-    };
-    let pretty = if pretty.is_none() &&
-        sess.unstable_options() {
-            matches.opt_str("xpretty").map(|a| {
-                // extended with unstable pretty-print variants
-                pretty::parse_pretty(&sess, a.as_slice(), true)
-            })
-        } else {
-            pretty
-        };
+    do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
 
-    match pretty.into_iter().next() {
+    // It is somewhat unfortunate that this is hardwired in - this is forced by
+    // the fact that pretty_print_input requires the session by value.
+    let pretty = callbacks.parse_pretty(&sess, &matches);
+    match pretty {
         Some((ppm, opt_uii)) => {
             pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
             return;
@@ -188,76 +152,313 @@ fn run_compiler(args: &[String]) {
         None => {/* continue */ }
     }
 
-    if sess.unstable_options() {
-        sess.opts.show_span = matches.opt_str("show-span");
-    }
+    let plugins = sess.opts.debugging_opts.extra_plugins.clone();
+    let control = callbacks.build_controller(&sess);
+    driver::compile_input(sess, cfg, &input, &odir, &ofile, Some(plugins), control);
+}
 
-    let r = matches.opt_strs("Z");
-    if r.contains(&("ls".to_string())) {
-        match input {
-            Input::File(ref ifile) => {
-                let mut stdout = old_io::stdout();
-                list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
-            }
-            Input::Str(_) => {
-                early_error("cannot list metadata for stdin");
-            }
+// Extract output directory and file from matches.
+fn make_output(matches: &getopts::Matches) -> (Option<Path>, Option<Path>) {
+    let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
+    let ofile = matches.opt_str("o").map(|o| Path::new(o));
+    (odir, ofile)
+}
+
+// Extract input (string or file and optional path) from matches.
+fn make_input(free_matches: &[String]) -> Option<(Input, Option<Path>)> {
+    if free_matches.len() == 1 {
+        let ifile = &free_matches[0][];
+        if ifile == "-" {
+            let contents = old_io::stdin().read_to_end().unwrap();
+            let src = String::from_utf8(contents).unwrap();
+            Some((Input::Str(src), None))
+        } else {
+            Some((Input::File(Path::new(ifile)), Some(Path::new(ifile))))
         }
-        return;
+    } else {
+        None
     }
+}
 
-    let plugins = sess.opts.debugging_opts.extra_plugins.clone();
-    let control = build_controller(&sess);
-    driver::compile_input(sess, cfg, &input, &odir, &ofile, Some(plugins), control);
+// Whether to stop or continue compilation.
+#[derive(Copy, Debug, Eq, PartialEq)]
+pub enum Compilation {
+    Stop,
+    Continue,
 }
 
-fn build_controller<'a>(sess: &Session) -> CompileController<'a> {
-    let mut control = CompileController::basic();
+impl Compilation {
+    pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
+        match self {
+            Compilation::Stop => Compilation::Stop,
+            Compilation::Continue => next()
+        }
+    }
+}
 
-    if sess.opts.parse_only ||
-       sess.opts.show_span.is_some() ||
-       sess.opts.debugging_opts.ast_json_noexpand {
-        control.after_parse.stop = true;
+// A trait for customising the compilation process. Offers a number of hooks for
+// executing custom code or customising input.
+pub trait CompilerCalls<'a> {
+    // Hook for a callback early in the process of handling arguments. This will
+    // be called straight after options have been parsed but before anything
+    // else (e.g., selecting input and output).
+    fn early_callback(&mut self,
+                      &getopts::Matches,
+                      &diagnostics::registry::Registry)
+                      -> Compilation;
+
+    // Hook for a callback late in the process of handling arguments. This will
+    // be called just before actual compilation starts (and before build_controller
+    // is called), after all arguments etc. have been completely handled.
+    fn late_callback(&mut self,
+                     &getopts::Matches,
+                     &Session,
+                     &Input,
+                     &Option<Path>,
+                     &Option<Path>)
+                     -> Compilation;
+
+    // Called after we extract the input from the arguments. Gives the implementer
+    // an opportunity to change the inputs or to add some custom input handling.
+    // The default behaviour is to simply pass through the inputs.
+    fn some_input(&mut self, input: Input, input_path: Option<Path>) -> (Input, Option<Path>) {
+        (input, input_path)
     }
 
-    if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
-        control.after_write_deps.stop = true;
+    // Called after we extract the input from the arguments if there is no valid
+    // input. Gives the implementer an opportunity to supply alternate input (by
+    // returning a Some value) or to add custom behaviour for this error such as
+    // emitting error messages. Returning None will cause compilation to stop
+    // at this point.
+    fn no_input(&mut self,
+                &getopts::Matches,
+                &config::Options,
+                &Option<Path>,
+                &Option<Path>,
+                &diagnostics::registry::Registry)
+                -> Option<(Input, Option<Path>)>;
+
+    // Parse pretty printing information from the arguments. The implementer can
+    // choose to ignore this (the default will return None) which will skip pretty
+    // printing. If you do want to pretty print, it is recommended to use the
+    // implementation of this method from RustcDefaultCalls.
+    // FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
+    // should be done as part of the framework and the implementor should customise
+    // handling of it. However, that is not possible atm because pretty printing
+    // essentially goes off and takes another path through the compiler which
+    // means the session is either moved or not depending on what parse_pretty
+    // returns (we could fix this by cloning, but it's another hack). The proper
+    // solution is to handle pretty printing as if it were a compiler extension,
+    // extending CompileController to make this work (see for example the treatment
+    // of save-analysis in RustcDefaultCalls::build_controller).
+    fn parse_pretty(&mut self,
+                    _sess: &Session,
+                    _matches: &getopts::Matches)
+                    -> Option<(PpMode, Option<UserIdentifiedItem>)> {
+        None
     }
 
-    if sess.opts.no_trans {
-        control.after_analysis.stop = true;
+    // Create a CompilController struct for controlling the behaviour of compilation.
+    fn build_controller(&mut self, &Session) -> CompileController<'a>;
+}
+
+// CompilerCalls instance for a regular rustc build.
+#[derive(Copy)]
+pub struct RustcDefaultCalls;
+
+impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
+    fn early_callback(&mut self,
+                      matches: &getopts::Matches,
+                      descriptions: &diagnostics::registry::Registry)
+                      -> Compilation {
+        match matches.opt_str("explain") {
+            Some(ref code) => {
+                match descriptions.find_description(&code[]) {
+                    Some(ref description) => {
+                        println!("{}", description);
+                    }
+                    None => {
+                        early_error(&format!("no extended information for {}", code)[]);
+                    }
+                }
+                return Compilation::Stop;
+            },
+            None => ()
+        }
+
+        return Compilation::Continue;
     }
 
-    if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
-        control.after_llvm.stop = true;
+    fn no_input(&mut self,
+                matches: &getopts::Matches,
+                sopts: &config::Options,
+                odir: &Option<Path>,
+                ofile: &Option<Path>,
+                descriptions: &diagnostics::registry::Registry)
+                -> Option<(Input, Option<Path>)> {
+        match matches.free.len() {
+            0 => {
+                if sopts.describe_lints {
+                    let mut ls = lint::LintStore::new();
+                    ls.register_builtin(None);
+                    describe_lints(&ls, false);
+                    return None;
+                }
+                let sess = build_session(sopts.clone(), None, descriptions.clone());
+                let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
+                if should_stop == Compilation::Stop {
+                    return None;
+                }
+                early_error("no input filename given");
+            }
+            1 => panic!("make_input should have provided valid inputs"),
+            _ => early_error("multiple input filenames provided")
+        }
+
+        None
     }
 
-    if sess.opts.debugging_opts.save_analysis {
-        control.after_analysis.callback = box |state| {
-            time(state.session.time_passes(), "save analysis", state.krate.unwrap(), |krate|
-                 save::process_crate(state.session,
-                                     krate,
-                                     state.analysis.unwrap(),
-                                     state.out_dir));
+    fn parse_pretty(&mut self,
+                    sess: &Session,
+                    matches: &getopts::Matches)
+                    -> Option<(PpMode, Option<UserIdentifiedItem>)> {
+        let pretty = if sess.opts.debugging_opts.unstable_options {
+            matches.opt_default("pretty", "normal").map(|a| {
+                // stable pretty-print variants only
+                pretty::parse_pretty(sess, &a, false)
+            })
+        } else {
+            None
         };
-        control.make_glob_map = resolve::MakeGlobMap::Yes;
+        if pretty.is_none() && sess.unstable_options() {
+            matches.opt_str("xpretty").map(|a| {
+                // extended with unstable pretty-print variants
+                pretty::parse_pretty(sess, &a, true)
+            })
+        } else {
+            pretty
+        }
+    }
+
+    fn late_callback(&mut self,
+                     matches: &getopts::Matches,
+                     sess: &Session,
+                     input: &Input,
+                     odir: &Option<Path>,
+                     ofile: &Option<Path>)
+                     -> Compilation {
+        RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile).and_then(
+            || RustcDefaultCalls::list_metadata(sess, matches, input))
     }
 
-    control
+    fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
+        let mut control = CompileController::basic();
+
+        if sess.opts.parse_only ||
+           sess.opts.show_span.is_some() ||
+           sess.opts.debugging_opts.ast_json_noexpand {
+            control.after_parse.stop = Compilation::Stop;
+        }
+
+        if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
+            control.after_write_deps.stop = Compilation::Stop;
+        }
+
+        if sess.opts.no_trans {
+            control.after_analysis.stop = Compilation::Stop;
+        }
+
+        if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
+            control.after_llvm.stop = Compilation::Stop;
+        }
+
+        if sess.opts.debugging_opts.save_analysis {
+            control.after_analysis.callback = box |state| {
+                time(state.session.time_passes(), "save analysis", state.krate.unwrap(), |krate|
+                     save::process_crate(state.session,
+                                         krate,
+                                         state.analysis.unwrap(),
+                                         state.out_dir));
+            };
+            control.make_glob_map = resolve::MakeGlobMap::Yes;
+        }
+
+        control
+    }
 }
 
-pub fn get_unstable_features_setting() -> UnstableFeatures {
-    // Whether this is a feature-staged build, i.e. on the beta or stable channel
-    let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
-    // The secret key needed to get through the rustc build itself by
-    // subverting the unstable features lints
-    let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
-    // The matching key to the above, only known by the build system
-    let bootstrap_provided_key = env::var_string("RUSTC_BOOTSTRAP_KEY").ok();
-    match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
-        (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
-        (true, _, _) => UnstableFeatures::Disallow,
-        (false, _, _) => UnstableFeatures::Default
+impl RustcDefaultCalls {
+    pub fn list_metadata(sess: &Session,
+                         matches: &getopts::Matches,
+                         input: &Input)
+                         -> Compilation {
+        let r = matches.opt_strs("Z");
+        if r.contains(&("ls".to_string())) {
+            match input {
+                &Input::File(ref ifile) => {
+                    let mut stdout = old_io::stdout();
+                    let path = &(*ifile);
+                    metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx,
+                                                         path,
+                                                         &mut stdout).unwrap();
+                }
+                &Input::Str(_) => {
+                    early_error("cannot list metadata for stdin");
+                }
+            }
+            return Compilation::Stop;
+        }
+
+        return Compilation::Continue;
+    }
+
+
+    fn print_crate_info(sess: &Session,
+                        input: Option<&Input>,
+                        odir: &Option<Path>,
+                        ofile: &Option<Path>)
+                        -> Compilation {
+        if sess.opts.prints.len() == 0 {
+            return Compilation::Continue;
+        }
+
+        let attrs = input.map(|input| parse_crate_attrs(sess, input));
+        for req in &sess.opts.prints {
+            match *req {
+                PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
+                PrintRequest::FileNames |
+                PrintRequest::CrateName => {
+                    let input = match input {
+                        Some(input) => input,
+                        None => early_error("no input file provided"),
+                    };
+                    let attrs = attrs.as_ref().unwrap();
+                    let t_outputs = driver::build_output_filenames(input,
+                                                                   odir,
+                                                                   ofile,
+                                                                   attrs,
+                                                                   sess);
+                    let id = link::find_crate_name(Some(sess),
+                                                   attrs,
+                                                   input);
+                    if *req == PrintRequest::CrateName {
+                        println!("{}", id);
+                        continue
+                    }
+                    let crate_types = driver::collect_crate_types(sess, attrs);
+                    let metadata = driver::collect_crate_metadata(sess, attrs);
+                    *sess.crate_metadata.borrow_mut() = metadata;
+                    for &style in &crate_types {
+                        let fname = link::filename_for_input(sess,
+                                                             style,
+                                                             &id,
+                                                             &t_outputs.with_extension(""));
+                        println!("{}", fname.filename_display());
+                    }
+                }
+            }
+        }
+        return Compilation::Stop;
     }
 }
 
@@ -313,7 +514,7 @@ fn usage(verbose: bool, include_unstable_options: bool) {
     -C help             Print codegen options
     -W help             Print 'lint' options and default settings
     -Z help             Print internal options for debugging rustc{}\n",
-              getopts::usage(message.as_slice(), groups.as_slice()),
+              getopts::usage(&message, &groups),
               extra_help);
 }
 
@@ -362,7 +563,7 @@ fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
     let max_name_len = plugin.iter().chain(builtin.iter())
         .map(|&s| s.name.width(true))
         .max().unwrap_or(0);
-    let padded = |&: x: &str| {
+    let padded = |x: &str| {
         let mut s = repeat(" ").take(max_name_len - x.chars().count())
                                .collect::<String>();
         s.push_str(x);
@@ -373,7 +574,7 @@ fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
 
-    let print_lints = |&: lints: Vec<&Lint>| {
+    let print_lints = |lints: Vec<&Lint>| {
         for lint in lints {
             let name = lint.name_lower().replace("_", "-");
             println!("    {}  {:7.7}  {}",
@@ -389,7 +590,7 @@ fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
     let max_name_len = plugin_groups.iter().chain(builtin_groups.iter())
         .map(|&(s, _)| s.width(true))
         .max().unwrap_or(0);
-    let padded = |&: x: &str| {
+    let padded = |x: &str| {
         let mut s = repeat(" ").take(max_name_len - x.chars().count())
                                .collect::<String>();
         s.push_str(x);
@@ -400,7 +601,7 @@ fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
     println!("    {}  {}", padded("name"), "sub-lints");
     println!("    {}  {}", padded("----"), "---------");
 
-    let print_lint_groups = |&: lints: Vec<(&'static str, Vec<lint::LintId>)>| {
+    let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
         for (name, to) in lints {
             let name = name.chars().map(|x| x.to_lowercase())
                            .collect::<String>().replace("_", "-");
@@ -481,20 +682,20 @@ pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
                 // unstable ones.
                 let all_groups : Vec<getopts::OptGroup>
                     = config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
-                match getopts::getopts(args.as_slice(), all_groups.as_slice()) {
+                match getopts::getopts(&args, &all_groups) {
                     Ok(m_unstable) => {
                         let r = m_unstable.opt_strs("Z");
                         let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
                         if include_unstable_options {
                             m_unstable
                         } else {
-                            early_error(f_stable_attempt.to_string().as_slice());
+                            early_error(&f_stable_attempt.to_string());
                         }
                     }
                     Err(_) => {
                         // ignore the error from the unstable attempt; just
                         // pass the error we got from the first try.
-                        early_error(f_stable_attempt.to_string().as_slice());
+                        early_error(&f_stable_attempt.to_string());
                     }
                 }
             }
@@ -535,50 +736,6 @@ pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
     Some(matches)
 }
 
-fn print_crate_info(sess: &Session,
-                    input: Option<&Input>,
-                    odir: &Option<Path>,
-                    ofile: &Option<Path>)
-                    -> bool {
-    if sess.opts.prints.len() == 0 { return false }
-
-    let attrs = input.map(|input| parse_crate_attrs(sess, input));
-    for req in &sess.opts.prints {
-        match *req {
-            PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
-            PrintRequest::FileNames |
-            PrintRequest::CrateName => {
-                let input = match input {
-                    Some(input) => input,
-                    None => early_error("no input file provided"),
-                };
-                let attrs = attrs.as_ref().unwrap().as_slice();
-                let t_outputs = driver::build_output_filenames(input,
-                                                               odir,
-                                                               ofile,
-                                                               attrs,
-                                                               sess);
-                let id = link::find_crate_name(Some(sess), attrs.as_slice(),
-                                               input);
-                if *req == PrintRequest::CrateName {
-                    println!("{}", id);
-                    continue
-                }
-                let crate_types = driver::collect_crate_types(sess, attrs);
-                let metadata = driver::collect_crate_metadata(sess, attrs);
-                *sess.crate_metadata.borrow_mut() = metadata;
-                for &style in &crate_types {
-                    let fname = link::filename_for_input(sess, style,
-                                                         id.as_slice(),
-                                                         &t_outputs.with_extension(""));
-                    println!("{}", fname.filename_display());
-                }
-            }
-        }
-    }
-    return true;
-}
-
 fn parse_crate_attrs(sess: &Session, input: &Input) ->
                      Vec<ast::Attribute> {
     let result = match *input {
@@ -598,11 +755,6 @@ fn parse_crate_attrs(sess: &Session, input: &Input) ->
     result.into_iter().collect()
 }
 
-pub fn list_metadata(sess: &Session, path: &Path,
-                     out: &mut old_io::Writer) -> old_io::IoResult<()> {
-    metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx, path, out)
-}
-
 /// Run a procedure which will detect panics in the compiler and print nicer
 /// error messages rather than just failing the test.
 ///
index ea7e59560cda9bb75dd22f7a2f607af10a03c6cb..5dfef6c775e1e892a9980815aa21bd888e8b28ea 100644 (file)
@@ -87,15 +87,15 @@ pub fn parse_pretty(sess: &Session,
         ("flowgraph,unlabelled", true)    => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
         _ => {
             if extended {
-                sess.fatal(format!(
+                sess.fatal(&format!(
                     "argument to `xpretty` must be one of `normal`, \
                      `expanded`, `flowgraph[,unlabelled]=<nodeid>`, `typed`, `identified`, \
-                     `expanded,identified`, or `everybody_loops`; got {}", name).as_slice());
+                     `expanded,identified`, or `everybody_loops`; got {}", name));
             } else {
-                sess.fatal(format!(
+                sess.fatal(&format!(
                     "argument to `pretty` must be one of `normal`, \
                      `expanded`, `typed`, `identified`, \
-                     or `expanded,identified`; got {}", name).as_slice());
+                     or `expanded,identified`; got {}", name));
             }
         }
     };
@@ -388,7 +388,7 @@ fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
     }
 
     fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
-        let fail_because = |&: is_wrong_because| -> ast::NodeId {
+        let fail_because = |is_wrong_because| -> ast::NodeId {
             let message =
                 format!("{} needs NodeId (int) or unique \
                          path suffix (b::c::d); got {}, which {}",
@@ -517,7 +517,7 @@ pub fn pretty_print_input(sess: Session,
         krate
     };
 
-    let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input);
+    let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
 
     let is_expanded = needs_expansion(&ppm);
     let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
index 7dc0d9be53924f9103e1872dc4cf023bbc723dea..9df9025846201b4b2172a2a2ab908580fd12c9cb 100644 (file)
@@ -43,7 +43,7 @@ struct RH<'a> {
     sub: &'a [RH<'a>]
 }
 
-static EMPTY_SOURCE_STR: &'static str = "#![no_std]";
+static EMPTY_SOURCE_STR: &'static str = "#![feature(no_std)] #![no_std]";
 
 struct ExpectErrorEmitter {
     messages: Vec<String>
@@ -56,7 +56,7 @@ fn remove_message(e: &mut ExpectErrorEmitter, msg: &str, lvl: Level) {
     }
 
     debug!("Error: {}", msg);
-    match e.messages.iter().position(|m| msg.contains(m.as_slice())) {
+    match e.messages.iter().position(|m| msg.contains(m)) {
         Some(i) => {
             e.messages.remove(i);
         }
index 26af9c9622ffe785b79c1f9c456b5bcfd388772e..878070e98e7e8b7072a189681027f92b20f2aa94 100644 (file)
@@ -436,73 +436,50 @@ pub enum DiagnosticKind {
 }
 
 // Opaque pointer types
-#[allow(missing_copy_implementations)]
 pub enum Module_opaque {}
 pub type ModuleRef = *mut Module_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Context_opaque {}
 pub type ContextRef = *mut Context_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Type_opaque {}
 pub type TypeRef = *mut Type_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Value_opaque {}
 pub type ValueRef = *mut Value_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Metadata_opaque {}
 pub type MetadataRef = *mut Metadata_opaque;
-#[allow(missing_copy_implementations)]
 pub enum BasicBlock_opaque {}
 pub type BasicBlockRef = *mut BasicBlock_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Builder_opaque {}
 pub type BuilderRef = *mut Builder_opaque;
-#[allow(missing_copy_implementations)]
 pub enum ExecutionEngine_opaque {}
 pub type ExecutionEngineRef = *mut ExecutionEngine_opaque;
-#[allow(missing_copy_implementations)]
 pub enum RustJITMemoryManager_opaque {}
 pub type RustJITMemoryManagerRef = *mut RustJITMemoryManager_opaque;
-#[allow(missing_copy_implementations)]
 pub enum MemoryBuffer_opaque {}
 pub type MemoryBufferRef = *mut MemoryBuffer_opaque;
-#[allow(missing_copy_implementations)]
 pub enum PassManager_opaque {}
 pub type PassManagerRef = *mut PassManager_opaque;
-#[allow(missing_copy_implementations)]
 pub enum PassManagerBuilder_opaque {}
 pub type PassManagerBuilderRef = *mut PassManagerBuilder_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Use_opaque {}
 pub type UseRef = *mut Use_opaque;
-#[allow(missing_copy_implementations)]
 pub enum TargetData_opaque {}
 pub type TargetDataRef = *mut TargetData_opaque;
-#[allow(missing_copy_implementations)]
 pub enum ObjectFile_opaque {}
 pub type ObjectFileRef = *mut ObjectFile_opaque;
-#[allow(missing_copy_implementations)]
 pub enum SectionIterator_opaque {}
 pub type SectionIteratorRef = *mut SectionIterator_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Pass_opaque {}
 pub type PassRef = *mut Pass_opaque;
-#[allow(missing_copy_implementations)]
 pub enum TargetMachine_opaque {}
 pub type TargetMachineRef = *mut TargetMachine_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Archive_opaque {}
 pub type ArchiveRef = *mut Archive_opaque;
-#[allow(missing_copy_implementations)]
 pub enum Twine_opaque {}
 pub type TwineRef = *mut Twine_opaque;
-#[allow(missing_copy_implementations)]
 pub enum DiagnosticInfo_opaque {}
 pub type DiagnosticInfoRef = *mut DiagnosticInfo_opaque;
-#[allow(missing_copy_implementations)]
 pub enum DebugLoc_opaque {}
 pub type DebugLocRef = *mut DebugLoc_opaque;
-#[allow(missing_copy_implementations)]
 pub enum SMDiagnostic_opaque {}
 pub type SMDiagnosticRef = *mut SMDiagnostic_opaque;
 
@@ -513,7 +490,6 @@ pub mod debuginfo {
     pub use self::DIDescriptorFlags::*;
     use super::{MetadataRef};
 
-    #[allow(missing_copy_implementations)]
     pub enum DIBuilder_opaque {}
     pub type DIBuilderRef = *mut DIBuilder_opaque;
 
@@ -2215,7 +2191,6 @@ pub fn get_param(llfn: ValueRef, index: c_uint) -> ValueRef {
     }
 }
 
-#[allow(missing_copy_implementations)]
 pub enum RustString_opaque {}
 pub type RustStringRef = *mut RustString_opaque;
 type RustStringRepr = *mut RefCell<Vec<u8>>;
index c398ff72f504a351a6326e6b4372a8141993ea0c..aa9b6c479bb78f9b56e57dd5f5339a9f8c04c9f8 100644 (file)
@@ -719,8 +719,8 @@ fn check_static_method(&mut self,
     fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) {
         debug!("privacy - path {}", self.nodestr(path_id));
         let orig_def = self.tcx.def_map.borrow()[path_id].clone();
-        let ck = |&: tyname: &str| {
-            let ck_public = |&: def: ast::DefId| {
+        let ck = |tyname: &str| {
+            let ck_public = |def: ast::DefId| {
                 debug!("privacy - ck_public {:?}", def);
                 let name = token::get_ident(path.segments.last().unwrap().identifier);
                 let origdid = orig_def.def_id();
@@ -924,7 +924,7 @@ struct type?!"),
                 }
             }
             ast::ExprPath(_) | ast::ExprQPath(_) => {
-                let guard = |&: did: ast::DefId| {
+                let guard = |did: ast::DefId| {
                     let fields = ty::lookup_struct_fields(self.tcx, did);
                     let any_priv = fields.iter().any(|f| {
                         f.vis != ast::Public && (
@@ -1076,7 +1076,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
     /// later on down the road...
     fn check_sane_privacy(&self, item: &ast::Item) {
         let tcx = self.tcx;
-        let check_inherited = |&: sp: Span, vis: ast::Visibility, note: &str| {
+        let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
             if vis != ast::Inherited {
                 tcx.sess.span_err(sp, "unnecessary visibility qualifier");
                 if note.len() > 0 {
@@ -1156,7 +1156,7 @@ fn check_inherited(tcx: &ty::ctxt, sp: Span, vis: ast::Visibility) {
                 tcx.sess.span_err(sp, "visibility has no effect inside functions");
             }
         }
-        let check_struct = |&: def: &ast::StructDef| {
+        let check_struct = |def: &ast::StructDef| {
             for f in &def.fields {
                match f.node.kind {
                     ast::NamedField(_, p) => check_inherited(tcx, f.span, p),
index a503398d4844fb2fdbbc0132444a3ffc71f21ac3..2f25f34a92ad07434340f8a6ab5b5fdaa85a910e 100644 (file)
@@ -307,8 +307,8 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
                     ViewPathSimple(binding, ref full_path) => {
                         let source_name =
                             full_path.segments.last().unwrap().identifier.name;
-                        if token::get_name(source_name).get() == "mod" ||
-                           token::get_name(source_name).get() == "self" {
+                        if &token::get_name(source_name)[] == "mod" ||
+                           &token::get_name(source_name)[] == "self" {
                             self.resolve_error(view_path.span,
                                 "`self` imports are only allowed within a { } list");
                         }
@@ -1020,7 +1020,7 @@ fn build_reduced_graph_for_external_crate_def(&mut self,
                         self.handle_external_def(def,
                                                  def_visibility,
                                                  &*child_name_bindings,
-                                                 token::get_name(name).get(),
+                                                 &token::get_name(name),
                                                  name,
                                                  root);
                     }
index dd9ccfbda7ca6a438ee6f4f57edc9126dfbc42a6..7b6ee3a729776161c6b038a5c42f689324eb2d82 100644 (file)
@@ -20,7 +20,7 @@
     E0254, // import conflicts with imported crate in this module
     E0255, // import conflicts with value in this module
     E0256, // import conflicts with type in this module
-    E0257, // inherent implementations are only allowen on types defined in the current module
+    E0257, // inherent implementations are only allowed on types defined in the current module
     E0258, // import conflicts with existing submodule
     E0259, // an extern crate has already been imported into this module
     E0260 // name conflicts with an external crate that has been imported into this module
index dd739059ed0ddf13c10d19ea06ce7a9aab9a90bb..a261599a70656877ab8bc01597956f520f599f4a 100644 (file)
@@ -1093,7 +1093,7 @@ fn names_to_string(&self, names: &[Name]) -> String {
             } else {
                 result.push_str("::")
             }
-            result.push_str(token::get_name(*name).get());
+            result.push_str(&token::get_name(*name));
         };
         result
     }
@@ -1111,7 +1111,7 @@ fn import_directive_subclass_to_string(&mut self,
                                         -> String {
         match subclass {
             SingleImport(_, source) => {
-                token::get_name(source).get().to_string()
+                token::get_name(source).to_string()
             }
             GlobImport => "*".to_string()
         }
@@ -1475,7 +1475,7 @@ fn get_binding(this: &mut Resolver,
         let mut import_resolutions = module_.import_resolutions.borrow_mut();
         let import_resolution = &mut (*import_resolutions)[target];
         {
-            let mut check_and_write_import = |&mut: namespace, result: &_, used_public: &mut bool| {
+            let mut check_and_write_import = |namespace, result: &_, used_public: &mut bool| {
                 let namespace_name = match namespace {
                     TypeNS => "type",
                     ValueNS => "value",
@@ -1708,13 +1708,13 @@ fn merge_import_resolution(&mut self,
 
         debug!("(resolving glob import) writing resolution `{}` in `{}` \
                to `{}`",
-               token::get_name(name).get(),
+               &token::get_name(name),
                self.module_to_string(&*containing_module),
                self.module_to_string(module_));
 
         // Merge the child item into the import resolution.
         {
-            let mut merge_child_item = |&mut : namespace| {
+            let mut merge_child_item = |namespace| {
                 if name_bindings.defined_in_namespace_with(namespace, IMPORTABLE | PUBLIC) {
                     let namespace_name = match namespace {
                         TypeNS => "type",
@@ -1725,8 +1725,8 @@ fn merge_import_resolution(&mut self,
                         let msg = format!("a {} named `{}` has already been imported \
                                            in this module",
                                           namespace_name,
-                                          token::get_name(name).get());
-                        span_err!(self.session, import_directive.span, E0251, "{}", msg.as_slice());
+                                          &token::get_name(name));
+                        span_err!(self.session, import_directive.span, E0251, "{}", msg);
                     } else {
                         let target = Target::new(containing_module.clone(),
                                                  name_bindings.clone(),
@@ -1757,7 +1757,7 @@ fn check_for_conflicting_import(&mut self,
                                     name: Name,
                                     namespace: Namespace) {
         debug!("check_for_conflicting_import: {}; target exists: {}",
-               token::get_name(name).get(),
+               &token::get_name(name),
                target.is_some());
 
         match *target {
@@ -1768,7 +1768,7 @@ fn check_for_conflicting_import(&mut self,
                                     TypeNS => "type",
                                     ValueNS => "value",
                                   },
-                                  token::get_name(name).get());
+                                  &token::get_name(name));
                 span_err!(self.session, import_span, E0252, "{}", &msg[]);
             }
             Some(_) | None => {}
@@ -1804,7 +1804,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
                     let msg = format!("import `{0}` conflicts with imported \
                                        crate in this module \
                                        (maybe you meant `use {0}::*`?)",
-                                      token::get_name(name).get());
+                                      &token::get_name(name));
                     span_err!(self.session, import_span, E0254, "{}", &msg[]);
                 }
                 Some(_) | None => {}
@@ -1826,7 +1826,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
                 if let Some(ref value) = *name_bindings.value_def.borrow() {
                     let msg = format!("import `{}` conflicts with value \
                                        in this module",
-                                      token::get_name(name).get());
+                                      &token::get_name(name));
                     span_err!(self.session, import_span, E0255, "{}", &msg[]);
                     if let Some(span) = value.value_span {
                         self.session.span_note(span,
@@ -1844,7 +1844,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
                         None => {
                             let msg = format!("import `{}` conflicts with type in \
                                                this module",
-                                              token::get_name(name).get());
+                                              &token::get_name(name));
                             span_err!(self.session, import_span, E0256, "{}", &msg[]);
                             if let Some(span) = ty.type_span {
                                 self.session.span_note(span,
@@ -1866,7 +1866,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
                                 _ => {
                                     let msg = format!("import `{}` conflicts with existing \
                                                        submodule",
-                                                      token::get_name(name).get());
+                                                      &token::get_name(name));
                                     span_err!(self.session, import_span, E0258, "{}", &msg[]);
                                     if let Some(span) = ty.type_span {
                                         self.session.span_note(span,
@@ -1892,7 +1892,7 @@ fn check_for_conflicts_between_external_crates(&self,
                 span_err!(self.session, span, E0259,
                           "an external crate named `{}` has already \
                                    been imported into this module",
-                                  token::get_name(name).get());
+                                  &token::get_name(name));
         }
     }
 
@@ -1906,7 +1906,7 @@ fn check_for_conflicts_between_external_crates_and_items(&self,
                           "the name `{}` conflicts with an external \
                                    crate that has been imported into this \
                                    module",
-                                  token::get_name(name).get());
+                                  &token::get_name(name));
         }
     }
 
@@ -1955,7 +1955,7 @@ fn search_parent_externals(needle: Name, module: &Rc<Module>)
                     let module_name = self.module_to_string(&*search_module);
                     let mut span = span;
                     let msg = if "???" == &module_name[] {
-                        span.hi = span.lo + Pos::from_usize(segment_name.get().len());
+                        span.hi = span.lo + Pos::from_usize(segment_name.len());
 
                         match search_parent_externals(name,
                                                      &self.current_module) {
@@ -2368,11 +2368,11 @@ fn resolve_module_prefix(&mut self,
         let mut containing_module;
         let mut i;
         let first_module_path_string = token::get_name(module_path[0]);
-        if "self" == first_module_path_string.get() {
+        if "self" == &first_module_path_string[] {
             containing_module =
                 self.get_nearest_normal_module_parent_or_self(module_);
             i = 1;
-        } else if "super" == first_module_path_string.get() {
+        } else if "super" == &first_module_path_string[] {
             containing_module =
                 self.get_nearest_normal_module_parent_or_self(module_);
             i = 0;  // We'll handle `super` below.
@@ -2383,7 +2383,7 @@ fn resolve_module_prefix(&mut self,
         // Now loop through all the `super`s we find.
         while i < module_path.len() {
             let string = token::get_name(module_path[i]);
-            if "super" != string.get() {
+            if "super" != &string[] {
                 break
             }
             debug!("(resolving module prefix) resolving `super` at {}",
@@ -2417,7 +2417,7 @@ fn resolve_name_in_module(&mut self,
                               allow_private_imports: bool)
                               -> ResolveResult<(Target, bool)> {
         debug!("(resolving name in module) resolving `{}` in `{}`",
-               token::get_name(name).get(),
+               &token::get_name(name),
                self.module_to_string(&*module_));
 
         // First, check the direct children of the module.
@@ -2493,7 +2493,7 @@ fn resolve_name_in_module(&mut self,
 
         // We're out of luck.
         debug!("(resolving name in module) failed to resolve `{}`",
-               token::get_name(name).get());
+               &token::get_name(name));
         return Failed(None);
     }
 
@@ -3756,15 +3756,14 @@ struct or enum variant",
                         }
                         Some(_) => {
                             self.resolve_error(path.span,
-                                format!("`{}` is not an enum variant, struct or const",
+                                &format!("`{}` is not an enum variant, struct or const",
                                     token::get_ident(
-                                        path.segments.last().unwrap().identifier)).as_slice());
+                                        path.segments.last().unwrap().identifier)));
                         }
                         None => {
                             self.resolve_error(path.span,
-                                format!("unresolved enum variant, struct or const `{}`",
-                                    token::get_ident(
-                                        path.segments.last().unwrap().identifier)).as_slice());
+                                &format!("unresolved enum variant, struct or const `{}`",
+                                    token::get_ident(path.segments.last().unwrap().identifier)));
                         }
                     }
 
@@ -4061,7 +4060,7 @@ fn resolve_module_relative_path(&mut self,
                     Some((span, msg)) => (span, msg),
                     None => {
                         let msg = format!("Use of undeclared type or module `{}`",
-                                          self.names_to_string(module_path.as_slice()));
+                                          self.names_to_string(&module_path));
                         (path.span, msg)
                     }
                 };
@@ -4163,7 +4162,7 @@ fn resolve_identifier_in_local_ribs(&mut self,
         let search_result = match namespace {
             ValueNS => {
                 let renamed = mtwt::resolve(ident);
-                self.search_ribs(self.value_ribs.as_slice(), renamed, span)
+                self.search_ribs(&self.value_ribs, renamed, span)
             }
             TypeNS => {
                 let name = ident.name;
@@ -4373,7 +4372,7 @@ fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
 
         let mut smallest = 0;
         for (i, other) in maybes.iter().enumerate() {
-            values[i] = lev_distance(name, other.get());
+            values[i] = lev_distance(name, &other);
 
             if values[i] <= values[smallest] {
                 smallest = i;
@@ -4384,9 +4383,9 @@ fn find_best_match_for_name(&mut self, name: &str, max_distance: uint)
             values[smallest] != uint::MAX &&
             values[smallest] < name.len() + 2 &&
             values[smallest] <= max_distance &&
-            name != maybes[smallest].get() {
+            name != &maybes[smallest][] {
 
-            Some(maybes[smallest].get().to_string())
+            Some(maybes[smallest].to_string())
 
         } else {
             None
@@ -4424,15 +4423,15 @@ fn resolve_expr(&mut self, expr: &Expr) {
                     Some((DefVariant(_, _, true), _)) => {
                         let path_name = self.path_names_to_string(path);
                         self.resolve_error(expr.span,
-                                format!("`{}` is a struct variant name, but \
-                                         this expression \
-                                         uses it like a function name",
-                                        path_name).as_slice());
+                                &format!("`{}` is a struct variant name, but \
+                                          this expression \
+                                          uses it like a function name",
+                                         path_name));
 
                         self.session.span_help(expr.span,
-                            format!("Did you mean to write: \
-                                    `{} {{ /* fields */ }}`?",
-                                    path_name).as_slice());
+                            &format!("Did you mean to write: \
+                                     `{} {{ /* fields */ }}`?",
+                                     path_name));
                     }
                     Some(def) => {
                         // Write the result into the def map.
@@ -4452,15 +4451,15 @@ fn resolve_expr(&mut self, expr: &Expr) {
                             Some((DefTy(struct_id, _), _))
                               if self.structs.contains_key(&struct_id) => {
                                 self.resolve_error(expr.span,
-                                        format!("`{}` is a structure name, but \
-                                                 this expression \
-                                                 uses it like a function name",
-                                                path_name).as_slice());
+                                        &format!("`{}` is a structure name, but \
+                                                  this expression \
+                                                  uses it like a function name",
+                                                 path_name));
 
                                 self.session.span_help(expr.span,
-                                    format!("Did you mean to write: \
-                                            `{} {{ /* fields */ }}`?",
-                                            path_name).as_slice());
+                                    &format!("Did you mean to write: \
+                                             `{} {{ /* fields */ }}`?",
+                                             path_name));
 
                             }
                             _ => {
@@ -4476,7 +4475,7 @@ fn resolve_expr(&mut self, expr: &Expr) {
                                     false // Stop advancing
                                 });
 
-                                if method_scope && token::get_name(self.self_name).get()
+                                if method_scope && &token::get_name(self.self_name)[]
                                                                    == path_name {
                                         self.resolve_error(
                                             expr.span,
@@ -4489,7 +4488,7 @@ fn resolve_expr(&mut self, expr: &Expr) {
                                         NoSuggestion => {
                                             // limit search to 5 to reduce the number
                                             // of stupid suggestions
-                                            self.find_best_match_for_name(path_name.as_slice(), 5)
+                                            self.find_best_match_for_name(&path_name, 5)
                                                                 .map_or("".to_string(),
                                                                         |x| format!("`{}`", x))
                                         }
@@ -4509,9 +4508,9 @@ fn resolve_expr(&mut self, expr: &Expr) {
 
                                     self.resolve_error(
                                         expr.span,
-                                        format!("unresolved name `{}`{}",
-                                                path_name,
-                                                msg).as_slice());
+                                        &format!("unresolved name `{}`{}",
+                                                 path_name,
+                                                 msg));
                                 }
                             }
                         }
index f841b6cf494deadc43f5d71c07cf911fbc71d516..9f26e9182ab1e5d04e820dd4fa9bfba46f71ce46 100644 (file)
 pub fn find_crate_name(sess: Option<&Session>,
                        attrs: &[ast::Attribute],
                        input: &Input) -> String {
-    let validate = |&: s: String, span: Option<Span>| {
+    let validate = |s: String, span: Option<Span>| {
         creader::validate_crate_name(sess, &s[], span);
         s
     };
@@ -141,7 +141,7 @@ pub fn find_crate_name(sess: Option<&Session>,
     if let Some(sess) = sess {
         if let Some(ref s) = sess.opts.crate_name {
             if let Some((attr, ref name)) = attr_crate_name {
-                if *s != name.get() {
+                if *s != &name[] {
                     let msg = format!("--crate-name and #[crate_name] are \
                                        required to match, but `{}` != `{}`",
                                       s, name);
@@ -153,7 +153,7 @@ pub fn find_crate_name(sess: Option<&Session>,
     }
 
     if let Some((attr, s)) = attr_crate_name {
-        return validate(s.get().to_string(), Some(attr.span));
+        return validate(s.to_string(), Some(attr.span));
     }
     if let Input::File(ref path) = *input {
         if let Some(s) = path.filestem_str() {
@@ -293,7 +293,7 @@ fn push(n: &mut String, s: &str) {
 
     // First, connect each component with <len, name> pairs.
     for e in path {
-        push(&mut n, &token::get_name(e.name()).get()[])
+        push(&mut n, &token::get_name(e.name()))
     }
 
     match hash {
@@ -609,7 +609,7 @@ fn link_rlib<'a>(sess: &'a Session,
                 // extension to it. This is to work around a bug in LLDB that
                 // would cause it to crash if the name of a file in an archive
                 // was exactly 16 bytes.
-                let bc_filename = obj_filename.with_extension(format!("{}.bc", i).as_slice());
+                let bc_filename = obj_filename.with_extension(&format!("{}.bc", i));
                 let bc_deflated_filename = obj_filename.with_extension(
                     &format!("{}.bytecode.deflate", i)[]);
 
@@ -1006,7 +1006,7 @@ fn link_args(cmd: &mut Command,
     if sess.opts.cg.rpath {
         let sysroot = sess.sysroot();
         let target_triple = &sess.opts.target_triple[];
-        let get_install_prefix_lib_path = |:| {
+        let get_install_prefix_lib_path = || {
             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
             let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
             let mut path = Path::new(install_prefix);
@@ -1044,8 +1044,11 @@ fn link_args(cmd: &mut Command,
 // in the current crate. Upstream crates with native library dependencies
 // may have their native library pulled in above.
 fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
-    sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, _| {
-        cmd.arg("-L").arg(path);
+    sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
+        match k {
+            PathKind::Framework => { cmd.arg("-F").arg(path); }
+            _ => { cmd.arg("-L").arg(path); }
+        }
         FileDoesntMatch
     });
 
@@ -1084,8 +1087,8 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
             // -force_load is the OSX equivalent of --whole-archive, but it
             // involves passing the full path to the library to link.
             let lib = archive::find_library(&l[],
-                                            sess.target.target.options.staticlib_prefix.as_slice(),
-                                            sess.target.target.options.staticlib_suffix.as_slice(),
+                                            &sess.target.target.options.staticlib_prefix,
+                                            &sess.target.target.options.staticlib_suffix,
                                             &search_path[],
                                             &sess.diagnostic().handler);
             let mut v = b"-Wl,-force_load,".to_vec();
index 38c68bc9fa426005e6add8fc17fd3a2f29ade027..c88e76f42707348001214e34eff7889dba5cc897 100644 (file)
@@ -64,7 +64,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
         debug!("reading {}", file);
         for i in iter::count(0us, 1) {
             let bc_encoded = time(sess.time_passes(),
-                                  format!("check for {}.{}.bytecode.deflate", name, i).as_slice(),
+                                  &format!("check for {}.{}.bytecode.deflate", name, i),
                                   (),
                                   |_| {
                                       archive.read(&format!("{}.{}.bytecode.deflate",
@@ -84,7 +84,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
             };
 
             let bc_decoded = if is_versioned_bytecode_format(bc_encoded) {
-                time(sess.time_passes(), format!("decode {}.{}.bc", file, i).as_slice(), (), |_| {
+                time(sess.time_passes(), &format!("decode {}.{}.bc", file, i), (), |_| {
                     // Read the version
                     let version = extract_bytecode_format_version(bc_encoded);
 
@@ -108,7 +108,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
                     }
                 })
             } else {
-                time(sess.time_passes(), format!("decode {}.{}.bc", file, i).as_slice(), (), |_| {
+                time(sess.time_passes(), &format!("decode {}.{}.bc", file, i), (), |_| {
                 // the object must be in the old, pre-versioning format, so simply
                 // inflate everything and let LLVM decide if it can make sense of it
                     match flate::inflate_bytes(bc_encoded) {
index 5312d2ca1ddeee3d40675c631a80262e4b82599e..8a30806f3b601ab62f98701f17e992df5e8199a0 100644 (file)
@@ -50,7 +50,7 @@ pub fn llvm_err(handler: &diagnostic::Handler, msg: String) -> ! {
             handler.fatal(&msg[]);
         } else {
             let err = ffi::c_str_to_bytes(&cstr);
-            let err = String::from_utf8_lossy(err.as_slice()).to_string();
+            let err = String::from_utf8_lossy(err).to_string();
             libc::free(cstr as *mut _);
             handler.fatal(&format!("{}: {}",
                                   &msg[],
@@ -223,8 +223,8 @@ fn create_target_machine(sess: &Session) -> TargetMachineRef {
     let tm = unsafe {
         let triple = CString::from_slice(triple.as_bytes());
         let cpu = match sess.opts.cg.target_cpu {
-            Some(ref s) => s.as_slice(),
-            None => sess.target.target.options.cpu.as_slice()
+            Some(ref s) => &**s,
+            None => &*sess.target.target.options.cpu
         };
         let cpu = CString::from_slice(cpu.as_bytes());
         let features = CString::from_slice(target_feature(sess).as_bytes());
@@ -375,7 +375,7 @@ struct HandlerFreeVars<'a> {
     match llvm::diagnostic::Diagnostic::unpack(info) {
         llvm::diagnostic::InlineAsm(inline) => {
             report_inline_asm(cgcx,
-                              llvm::twine_to_string(inline.message).as_slice(),
+                              &*llvm::twine_to_string(inline.message),
                               inline.cookie);
         }
 
@@ -390,11 +390,11 @@ struct HandlerFreeVars<'a> {
 
             if enabled {
                 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
-                cgcx.handler.note(format!("optimization {} for {} at {}: {}",
-                                          opt.kind.describe(),
-                                          pass_name,
-                                          if loc.is_empty() { "[unknown]" } else { loc.as_slice() },
-                                          llvm::twine_to_string(opt.message)).as_slice());
+                cgcx.handler.note(&format!("optimization {} for {} at {}: {}",
+                                           opt.kind.describe(),
+                                           pass_name,
+                                           if loc.is_empty() { "[unknown]" } else { &*loc },
+                                           llvm::twine_to_string(opt.message)));
             }
         }
 
@@ -423,7 +423,7 @@ unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
 
     if config.emit_no_opt_bc {
         let ext = format!("{}.no-opt.bc", name_extra);
-        let out = output_names.with_extension(ext.as_slice());
+        let out = output_names.with_extension(&ext);
         let out = CString::from_slice(out.as_vec());
         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
     }
@@ -439,7 +439,7 @@ unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
 
             // If we're verifying or linting, add them to the function pass
             // manager.
-            let addpass = |&: pass: &str| {
+            let addpass = |pass: &str| {
                 let pass = CString::from_slice(pass.as_bytes());
                 llvm::LLVMRustAddPass(fpm, pass.as_ptr())
             };
@@ -455,8 +455,7 @@ unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
             for pass in &config.passes {
                 let pass = CString::from_slice(pass.as_bytes());
                 if !llvm::LLVMRustAddPass(mpm, pass.as_ptr()) {
-                    cgcx.handler.warn(format!("unknown pass {:?}, ignoring",
-                                              pass).as_slice());
+                    cgcx.handler.warn(&format!("unknown pass {:?}, ignoring", pass));
                 }
             }
 
@@ -477,7 +476,7 @@ unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
 
                     if config.emit_lto_bc {
                         let name = format!("{}.lto.bc", name_extra);
-                        let out = output_names.with_extension(name.as_slice());
+                        let out = output_names.with_extension(&name);
                         let out = CString::from_slice(out.as_vec());
                         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
                     }
@@ -511,7 +510,7 @@ unsafe fn with_codegen<F>(tm: TargetMachineRef,
 
     if config.emit_bc {
         let ext = format!("{}.bc", name_extra);
-        let out = output_names.with_extension(ext.as_slice());
+        let out = output_names.with_extension(&ext);
         let out = CString::from_slice(out.as_vec());
         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
     }
@@ -519,7 +518,7 @@ unsafe fn with_codegen<F>(tm: TargetMachineRef,
     time(config.time_passes, "codegen passes", (), |()| {
         if config.emit_ir {
             let ext = format!("{}.ll", name_extra);
-            let out = output_names.with_extension(ext.as_slice());
+            let out = output_names.with_extension(&ext);
             let out = CString::from_slice(out.as_vec());
             with_codegen(tm, llmod, config.no_builtins, |cpm| {
                 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
@@ -660,7 +659,7 @@ pub fn run_passes(sess: &Session,
 
     // Produce final compile outputs.
 
-    let copy_if_one_unit = |&: ext: &str, output_type: config::OutputType, keep_numbered: bool| {
+    let copy_if_one_unit = |ext: &str, output_type: config::OutputType, keep_numbered: bool| {
         // Three cases:
         if sess.opts.cg.codegen_units == 1 {
             // 1) Only one codegen unit.  In this case it's no difficulty
@@ -685,7 +684,7 @@ pub fn run_passes(sess: &Session,
         }
     };
 
-    let link_obj = |&: output_path: &Path| {
+    let link_obj = |output_path: &Path| {
         // Running `ld -r` on a single input is kind of pointless.
         if sess.opts.cg.codegen_units == 1 {
             fs::copy(&crate_output.with_extension("0.o"),
@@ -910,7 +909,7 @@ fn run_work_multithreaded(sess: &Session,
         let mut tx = Some(tx);
         futures.push(rx);
 
-        thread::Builder::new().name(format!("codegen-{}", i)).spawn(move |:| {
+        thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
             let diag_handler = mk_handler(true, box diag_emitter);
 
             // Must construct cgcx inside the proc because it has non-Send
@@ -1001,7 +1000,7 @@ unsafe fn configure_llvm(sess: &Session) {
     let mut llvm_c_strs = Vec::new();
     let mut llvm_args = Vec::new();
     {
-        let mut add = |&mut : arg: &str| {
+        let mut add = |arg: &str| {
             let s = CString::from_slice(arg.as_bytes());
             llvm_args.push(s.as_ptr());
             llvm_c_strs.push(s);
@@ -1013,7 +1012,7 @@ unsafe fn configure_llvm(sess: &Session) {
         if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
 
         // FIXME #21627 disable faulty FastISel on AArch64 (even for -O0)
-        if sess.target.target.arch.as_slice() == "aarch64" { add("-fast-isel=0"); }
+        if sess.target.target.arch == "aarch64" { add("-fast-isel=0"); }
 
         for arg in &sess.opts.cg.llvm_args {
             add(&(*arg)[]);
index b0ce9641cf440e8a658e9bcb314d129720692fbe..e80564097df2302148bb4c390567652504354cdd 100644 (file)
@@ -309,7 +309,7 @@ fn process_method(&mut self, method: &ast::Method) {
                                 Some(def_id) => {
                                     result.push_str(" as ");
                                     result.push_str(
-                                        ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice());
+                                        &ty::item_path_str(&self.analysis.ty_cx, def_id));
                                 },
                                 None => {}
                             }
@@ -355,7 +355,7 @@ fn process_method(&mut self, method: &ast::Method) {
             },
         };
 
-        let qualname = format!("{}::{}", qualname, get_ident(method.pe_ident()).get());
+        let qualname = format!("{}::{}", qualname, &get_ident(method.pe_ident()));
         let qualname = &qualname[];
 
         // record the decl for this def (if it has one)
@@ -436,7 +436,7 @@ fn process_struct_field_def(&mut self,
                     Some(sub_span) => self.fmt.field_str(field.span,
                                                          Some(sub_span),
                                                          field.node.id,
-                                                         &name.get()[],
+                                                         &name[],
                                                          &qualname[],
                                                          &typ[],
                                                          scope_id),
@@ -525,7 +525,7 @@ fn process_static(&mut self,
         self.fmt.static_str(item.span,
                             sub_span,
                             item.id,
-                            get_ident(item.ident).get(),
+                            &get_ident(item.ident),
                             &qualname[],
                             &value[],
                             &ty_to_string(&*typ)[],
@@ -548,7 +548,7 @@ fn process_const(&mut self,
         self.fmt.static_str(item.span,
                             sub_span,
                             item.id,
-                            get_ident(item.ident).get(),
+                            &get_ident(item.ident),
                             &qualname[],
                             "",
                             &ty_to_string(&*typ)[],
@@ -607,7 +607,7 @@ fn process_enum(&mut self,
         }
         for variant in &enum_definition.variants {
             let name = get_ident(variant.node.name);
-            let name = name.get();
+            let name = &name;
             let mut qualname = enum_name.clone();
             qualname.push_str("::");
             qualname.push_str(name);
@@ -643,7 +643,7 @@ fn process_enum(&mut self,
                         item.id);
 
                     for field in &struct_def.fields {
-                        self.process_struct_field_def(field, qualname.as_slice(), variant.node.id);
+                        self.process_struct_field_def(field, &qualname, variant.node.id);
                         self.visit_ty(&*field.node.ty);
                     }
                 }
@@ -795,7 +795,7 @@ fn process_path(&mut self,
         let def_map = self.analysis.ty_cx.def_map.borrow();
         if !def_map.contains_key(&id) {
             self.sess.span_bug(span,
-                               format!("def_map has no key for {} in visit_expr", id).as_slice());
+                               &format!("def_map has no key for {} in visit_expr", id));
         }
         let def = &(*def_map)[id];
         let sub_span = self.span.span_for_last_ident(span);
@@ -1094,7 +1094,7 @@ fn visit_item(&mut self, item: &ast::Item) {
                                                sub_span,
                                                item.id,
                                                mod_id,
-                                               get_ident(ident).get(),
+                                               &get_ident(ident),
                                                self.cur_scope);
                         self.write_sub_paths_truncated(path, true);
                     }
@@ -1117,7 +1117,7 @@ fn visit_item(&mut self, item: &ast::Item) {
                         self.fmt.use_glob_str(path.span,
                                               sub_span,
                                               item.id,
-                                              name_string.as_slice(),
+                                              &name_string,
                                               self.cur_scope);
                         self.write_sub_paths(path, true);
                     }
@@ -1149,9 +1149,9 @@ fn visit_item(&mut self, item: &ast::Item) {
             }
             ast::ItemExternCrate(ref s) => {
                 let name = get_ident(item.ident);
-                let name = name.get();
+                let name = &name;
                 let location = match *s {
-                    Some((ref s, _)) => s.get().to_string(),
+                    Some((ref s, _)) => s.to_string(),
                     None => name.to_string(),
                 };
                 let alias_span = self.span.span_for_last_ident(item.span);
@@ -1200,7 +1200,7 @@ fn visit_item(&mut self, item: &ast::Item) {
                                      &value[]);
 
                 self.visit_ty(&**ty);
-                self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id);
+                self.process_generic_params(ty_params, item.span, &qualname, item.id);
             },
             ast::ItemMac(_) => (),
             _ => visit::walk_item(self, item),
@@ -1259,7 +1259,7 @@ fn visit_trait_item(&mut self, tm: &ast::TraitItem) {
                     },
                 };
 
-                qualname.push_str(get_ident(method_type.ident).get());
+                qualname.push_str(&get_ident(method_type.ident));
                 let qualname = &qualname[];
 
                 let sub_span = self.span.sub_span_after_keyword(method_type.span, keywords::Fn);
@@ -1541,7 +1541,7 @@ pub fn process_crate(sess: &Session,
 
     assert!(analysis.glob_map.is_some());
     let cratename = match attr::find_crate_name(&krate.attrs[]) {
-        Some(name) => name.get().to_string(),
+        Some(name) => name.to_string(),
         None => {
             info!("Could not find crate name, using 'unknown_crate'");
             String::from_str("unknown_crate")
index f6f03887528aec8a8b8343947a192cd126291303..3bd04ed29d4a1139a2a3bc502a6241793931c616 100644 (file)
@@ -229,8 +229,8 @@ pub fn record_with_span(&mut self,
 
         if !needs_span {
             self.span.sess.span_bug(span,
-                                    format!("Called record_with_span for '{}' \
-                                             which does not require a span", label).as_slice());
+                                    &format!("Called record_with_span for '{}' \
+                                              which does not require a span", label));
         }
 
         let values_str = match self.make_values_str(label, fields, values, span) {
index beec8071a72baf4f1491864da078b072aae0ca28..a724cdc0229d2f465af8865f8cd1ae42951dda33 100644 (file)
@@ -69,8 +69,8 @@ pub fn make_sub_span(&self, span: Span, sub_span: Option<Span>) -> Option<Span>
 
     pub fn snippet(&self, span: Span) -> String {
         match self.sess.codemap().span_to_snippet(span) {
-            Some(s) => s,
-            None => String::new(),
+            Ok(s) => s,
+            Err(_) => String::new(),
         }
     }
 
index 52fe8797592b5b72c8bfedc006fdfb8a07ef21ac..0f014800480e9db678c0feb7df8a0405542b61d8 100644 (file)
 use trans::tvec;
 use trans::type_of;
 use middle::ty::{self, Ty};
-use session::config::FullDebugInfo;
+use session::config::{NoDebugInfo, FullDebugInfo};
 use util::common::indenter;
 use util::nodemap::FnvHashMap;
 use util::ppaux::{Repr, vec_map_to_string};
 use std::iter::AdditiveIterator;
 use std::rc::Rc;
 use syntax::ast;
-use syntax::ast::{DUMMY_NODE_ID, Ident};
+use syntax::ast::{DUMMY_NODE_ID, Ident, NodeId};
 use syntax::codemap::Span;
 use syntax::fold::Folder;
 use syntax::ptr::P;
@@ -244,25 +244,29 @@ fn eq(self, other: ConstantExpr<'a>, tcx: &ty::ctxt) -> bool {
 // An option identifying a branch (either a literal, an enum variant or a range)
 #[derive(Debug)]
 enum Opt<'a, 'tcx> {
-    ConstantValue(ConstantExpr<'a>),
-    ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>),
-    Variant(ty::Disr, Rc<adt::Repr<'tcx>>, ast::DefId),
-    SliceLengthEqual(uint),
-    SliceLengthGreaterOrEqual(/* prefix length */ uint, /* suffix length */ uint),
+    ConstantValue(ConstantExpr<'a>, DebugLoc),
+    ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>, DebugLoc),
+    Variant(ty::Disr, Rc<adt::Repr<'tcx>>, ast::DefId, DebugLoc),
+    SliceLengthEqual(uint, DebugLoc),
+    SliceLengthGreaterOrEqual(/* prefix length */ uint,
+                              /* suffix length */ uint,
+                              DebugLoc),
 }
 
 impl<'a, 'tcx> Opt<'a, 'tcx> {
     fn eq(&self, other: &Opt<'a, 'tcx>, tcx: &ty::ctxt<'tcx>) -> bool {
         match (self, other) {
-            (&ConstantValue(a), &ConstantValue(b)) => a.eq(b, tcx),
-            (&ConstantRange(a1, a2), &ConstantRange(b1, b2)) => {
+            (&ConstantValue(a, _), &ConstantValue(b, _)) => a.eq(b, tcx),
+            (&ConstantRange(a1, a2, _), &ConstantRange(b1, b2, _)) => {
                 a1.eq(b1, tcx) && a2.eq(b2, tcx)
             }
-            (&Variant(a_disr, ref a_repr, a_def), &Variant(b_disr, ref b_repr, b_def)) => {
+            (&Variant(a_disr, ref a_repr, a_def, _),
+             &Variant(b_disr, ref b_repr, b_def, _)) => {
                 a_disr == b_disr && *a_repr == *b_repr && a_def == b_def
             }
-            (&SliceLengthEqual(a), &SliceLengthEqual(b)) => a == b,
-            (&SliceLengthGreaterOrEqual(a1, a2), &SliceLengthGreaterOrEqual(b1, b2)) => {
+            (&SliceLengthEqual(a, _), &SliceLengthEqual(b, _)) => a == b,
+            (&SliceLengthGreaterOrEqual(a1, a2, _),
+             &SliceLengthGreaterOrEqual(b1, b2, _)) => {
                 a1 == b1 && a2 == b2
             }
             _ => false
@@ -273,29 +277,39 @@ fn trans<'blk>(&self, mut bcx: Block<'blk, 'tcx>) -> OptResult<'blk, 'tcx> {
         let _icx = push_ctxt("match::trans_opt");
         let ccx = bcx.ccx();
         match *self {
-            ConstantValue(ConstantExpr(lit_expr)) => {
+            ConstantValue(ConstantExpr(lit_expr), _) => {
                 let lit_ty = ty::node_id_to_type(bcx.tcx(), lit_expr.id);
                 let (llval, _) = consts::const_expr(ccx, &*lit_expr);
                 let lit_datum = immediate_rvalue(llval, lit_ty);
                 let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
                 SingleResult(Result::new(bcx, lit_datum.val))
             }
-            ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2)) => {
+            ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2), _) => {
                 let (l1, _) = consts::const_expr(ccx, &**l1);
                 let (l2, _) = consts::const_expr(ccx, &**l2);
                 RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
             }
-            Variant(disr_val, ref repr, _) => {
+            Variant(disr_val, ref repr, _, _) => {
                 adt::trans_case(bcx, &**repr, disr_val)
             }
-            SliceLengthEqual(length) => {
+            SliceLengthEqual(length, _) => {
                 SingleResult(Result::new(bcx, C_uint(ccx, length)))
             }
-            SliceLengthGreaterOrEqual(prefix, suffix) => {
+            SliceLengthGreaterOrEqual(prefix, suffix, _) => {
                 LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
             }
         }
     }
+
+    fn debug_loc(&self) -> DebugLoc {
+        match *self {
+            ConstantValue(_,debug_loc)                 |
+            ConstantRange(_, _, debug_loc)             |
+            Variant(_, _, _, debug_loc)                |
+            SliceLengthEqual(_, debug_loc)             |
+            SliceLengthGreaterOrEqual(_, _, debug_loc) => debug_loc
+        }
+    }
 }
 
 #[derive(Copy, PartialEq)]
@@ -352,6 +366,9 @@ struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
     pats: Vec<&'p ast::Pat>,
     data: &'a ArmData<'p, 'blk, 'tcx>,
     bound_ptrs: Vec<(Ident, ValueRef)>,
+    // Thread along renamings done by the check_match::StaticInliner, so we can
+    // map back to original NodeIds
+    pat_renaming_map: Option<&'a FnvHashMap<(NodeId, Span), NodeId>>
 }
 
 impl<'a, 'p, 'blk, 'tcx> Repr<'tcx> for Match<'a, 'p, 'blk, 'tcx> {
@@ -405,7 +422,8 @@ fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
         Match {
             pats: pats,
             data: &*br.data,
-            bound_ptrs: bound_ptrs
+            bound_ptrs: bound_ptrs,
+            pat_renaming_map: br.pat_renaming_map,
         }
     }).collect()
 }
@@ -449,7 +467,8 @@ fn enter_match<'a, 'b, 'p, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
             Match {
                 pats: pats,
                 data: br.data,
-                bound_ptrs: bound_ptrs
+                bound_ptrs: bound_ptrs,
+                pat_renaming_map: br.pat_renaming_map,
             }
         })
     }).collect()
@@ -527,18 +546,18 @@ fn enter_opt<'a, 'p, 'blk, 'tcx>(
     let _indenter = indenter();
 
     let ctor = match opt {
-        &ConstantValue(ConstantExpr(expr)) => check_match::ConstantValue(
+        &ConstantValue(ConstantExpr(expr), _) => check_match::ConstantValue(
             const_eval::eval_const_expr(bcx.tcx(), &*expr)
         ),
-        &ConstantRange(ConstantExpr(lo), ConstantExpr(hi)) => check_match::ConstantRange(
+        &ConstantRange(ConstantExpr(lo), ConstantExpr(hi), _) => check_match::ConstantRange(
             const_eval::eval_const_expr(bcx.tcx(), &*lo),
             const_eval::eval_const_expr(bcx.tcx(), &*hi)
         ),
-        &SliceLengthEqual(n) =>
+        &SliceLengthEqual(n, _) =>
             check_match::Slice(n),
-        &SliceLengthGreaterOrEqual(before, after) =>
+        &SliceLengthGreaterOrEqual(before, after, _) =>
             check_match::SliceWithSubslice(before, after),
-        &Variant(_, _, def_id) =>
+        &Variant(_, _, def_id, _) =>
             check_match::Constructor::Variant(def_id)
     };
 
@@ -556,34 +575,50 @@ fn enter_opt<'a, 'p, 'blk, 'tcx>(
 // needs to be conditionally matched at runtime; for example, the discriminant
 // on a set of enum variants or a literal.
 fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
-                                    m: &[Match<'a, 'p, 'blk, 'tcx>], col: uint)
+                                    m: &[Match<'a, 'p, 'blk, 'tcx>],
+                                    col: uint)
                                     -> Vec<Opt<'p, 'tcx>> {
     let tcx = bcx.tcx();
 
     let mut found: Vec<Opt> = vec![];
     for br in m {
         let cur = br.pats[col];
+        let debug_loc = match br.pat_renaming_map {
+            Some(pat_renaming_map) => {
+                match pat_renaming_map.get(&(cur.id, cur.span)) {
+                    Some(&id) => DebugLoc::At(id, cur.span),
+                    None => DebugLoc::At(cur.id, cur.span),
+                }
+            }
+            None => DebugLoc::None
+        };
+
         let opt = match cur.node {
-            ast::PatLit(ref l) => ConstantValue(ConstantExpr(&**l)),
+            ast::PatLit(ref l) => {
+                ConstantValue(ConstantExpr(&**l), debug_loc)
+            }
             ast::PatIdent(..) | ast::PatEnum(..) | ast::PatStruct(..) => {
                 // This is either an enum variant or a variable binding.
                 let opt_def = tcx.def_map.borrow().get(&cur.id).cloned();
                 match opt_def {
                     Some(def::DefVariant(enum_id, var_id, _)) => {
                         let variant = ty::enum_variant_with_id(tcx, enum_id, var_id);
-                        Variant(variant.disr_val, adt::represent_node(bcx, cur.id), var_id)
+                        Variant(variant.disr_val,
+                                adt::represent_node(bcx, cur.id),
+                                var_id,
+                                debug_loc)
                     }
                     _ => continue
                 }
             }
             ast::PatRange(ref l1, ref l2) => {
-                ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2))
+                ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2), debug_loc)
             }
             ast::PatVec(ref before, None, ref after) => {
-                SliceLengthEqual(before.len() + after.len())
+                SliceLengthEqual(before.len() + after.len(), debug_loc)
             }
             ast::PatVec(ref before, Some(_), ref after) => {
-                SliceLengthGreaterOrEqual(before.len(), after.len())
+                SliceLengthGreaterOrEqual(before.len(), after.len(), debug_loc)
             }
             _ => continue
         };
@@ -747,7 +782,7 @@ fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> uint {
         }
     }
 
-    let column_score = |&: m: &[Match], col: uint| -> uint {
+    let column_score = |m: &[Match], col: uint| -> uint {
         let total_score = m.iter()
             .map(|row| row.pats[col])
             .map(|pat| pat_score(def_map, pat))
@@ -761,7 +796,7 @@ fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> uint {
         }
     };
 
-    let column_contains_any_nonwild_patterns = |&: &col: &uint| -> bool {
+    let column_contains_any_nonwild_patterns = |&col: &uint| -> bool {
         m.iter().any(|row| match row.pats[col].node {
             ast::PatWild(_) => false,
             _ => true
@@ -779,30 +814,32 @@ fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> uint {
 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
                               lhs: ValueRef,
                               rhs: ValueRef,
-                              rhs_t: Ty<'tcx>)
+                              rhs_t: Ty<'tcx>,
+                              debug_loc: DebugLoc)
                               -> Result<'blk, 'tcx> {
     fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
                                lhs: ValueRef,
                                rhs: ValueRef,
-                               rhs_t: Ty<'tcx>)
+                               rhs_t: Ty<'tcx>,
+                               debug_loc: DebugLoc)
                                -> Result<'blk, 'tcx> {
         let did = langcall(cx,
                            None,
                            &format!("comparison of `{}`",
                                    cx.ty_to_string(rhs_t))[],
                            StrEqFnLangItem);
-        callee::trans_lang_call(cx, did, &[lhs, rhs], None)
+        callee::trans_lang_call(cx, did, &[lhs, rhs], None, debug_loc)
     }
 
     let _icx = push_ctxt("compare_values");
     if ty::type_is_scalar(rhs_t) {
-        let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq);
+        let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq, debug_loc);
         return Result::new(rs.bcx, rs.val);
     }
 
     match rhs_t.sty {
         ty::ty_rptr(_, mt) => match mt.ty.sty {
-            ty::ty_str => compare_str(cx, lhs, rhs, rhs_t),
+            ty::ty_str => compare_str(cx, lhs, rhs, rhs_t, debug_loc),
             ty::ty_vec(ty, _) => match ty.sty {
                 ty::ty_uint(ast::TyU8) => {
                     // NOTE: cast &[u8] to &str and abuse the str_eq lang item,
@@ -812,7 +849,7 @@ fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
                                              ast::MutImmutable);
                     let lhs = BitCast(cx, lhs, type_of::type_of(cx.ccx(), t).ptr_to());
                     let rhs = BitCast(cx, rhs, type_of::type_of(cx.ccx(), t).ptr_to());
-                    compare_str(cx, lhs, rhs, rhs_t)
+                    compare_str(cx, lhs, rhs, rhs_t, debug_loc)
                 },
                 _ => cx.sess().bug("only byte strings supported in compare_values"),
             },
@@ -889,11 +926,13 @@ fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
         }
     }
 
+    for (_, &binding_info) in &data.bindings_map {
+        bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
+    }
+
     with_cond(bcx, Not(bcx, val, guard_expr.debug_loc()), |bcx| {
-        // Guard does not match: remove all bindings from the lllocals table
         for (_, &binding_info) in &data.bindings_map {
             call_lifetime_end(bcx, binding_info.llmatch);
-            bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
         }
         match chk {
             // If the default arm is the only one left, move on to the next
@@ -1029,8 +1068,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
                                         field_vals.len())
             );
             let mut vals = field_vals;
-            vals.push_all(vals_left.as_slice());
-            compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default);
+            vals.push_all(&vals_left);
+            compile_submatch(bcx, &pats, &vals, chk, has_genuine_default);
             return;
         }
         _ => ()
@@ -1044,7 +1083,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
     debug!("test_val={}", bcx.val_to_string(test_val));
     if opts.len() > 0 {
         match opts[0] {
-            ConstantValue(_) | ConstantRange(_, _) => {
+            ConstantValue(..) | ConstantRange(..) => {
                 test_val = load_if_immediate(bcx, val, left_ty);
                 kind = if ty::type_is_integral(left_ty) {
                     Switch
@@ -1052,12 +1091,12 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
                     Compare
                 };
             }
-            Variant(_, ref repr, _) => {
+            Variant(_, ref repr, _, _) => {
                 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val);
                 kind = the_kind;
                 if let Some(tval) = val_opt { test_val = tval; }
             }
-            SliceLengthEqual(_) | SliceLengthGreaterOrEqual(_, _) => {
+            SliceLengthEqual(..) | SliceLengthGreaterOrEqual(..) => {
                 let (_, len) = tvec::get_base_and_len(bcx, val, left_ty);
                 test_val = len;
                 kind = Switch;
@@ -1066,8 +1105,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
     }
     for o in &opts {
         match *o {
-            ConstantRange(_, _) => { kind = Compare; break },
-            SliceLengthGreaterOrEqual(_, _) => { kind = CompareSliceLength; break },
+            ConstantRange(..) => { kind = Compare; break },
+            SliceLengthGreaterOrEqual(..) => { kind = CompareSliceLength; break },
             _ => ()
         }
     }
@@ -1093,10 +1132,12 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
         // for the current conditional branch.
         let mut branch_chk = None;
         let mut opt_cx = else_cx;
+        let debug_loc = opt.debug_loc();
+
         if !exhaustive || i + 1 < len {
             opt_cx = bcx.fcx.new_temp_block("match_case");
             match kind {
-                Single => Br(bcx, opt_cx.llbb, DebugLoc::None),
+                Single => Br(bcx, opt_cx.llbb, debug_loc),
                 Switch => {
                     match opt.trans(bcx) {
                         SingleResult(r) => {
@@ -1119,22 +1160,33 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
                     let Result { bcx: after_cx, val: matches } = {
                         match opt.trans(bcx) {
                             SingleResult(Result { bcx, val }) => {
-                                compare_values(bcx, test_val, val, t)
+                                compare_values(bcx, test_val, val, t, debug_loc)
                             }
                             RangeResult(Result { val: vbegin, .. },
                                         Result { bcx, val: vend }) => {
                                 let Result { bcx, val: llge } =
-                                    compare_scalar_types(
-                                    bcx, test_val,
-                                    vbegin, t, ast::BiGe);
+                                    compare_scalar_types(bcx,
+                                                         test_val,
+                                                         vbegin,
+                                                         t,
+                                                         ast::BiGe,
+                                                         debug_loc);
                                 let Result { bcx, val: llle } =
-                                    compare_scalar_types(
-                                    bcx, test_val, vend,
-                                    t, ast::BiLe);
-                                Result::new(bcx, And(bcx, llge, llle, DebugLoc::None))
+                                    compare_scalar_types(bcx,
+                                                         test_val,
+                                                         vend,
+                                                         t,
+                                                         ast::BiLe,
+                                                         debug_loc);
+                                Result::new(bcx, And(bcx, llge, llle, debug_loc))
                             }
                             LowerBound(Result { bcx, val }) => {
-                                compare_scalar_types(bcx, test_val, val, t, ast::BiGe)
+                                compare_scalar_types(bcx,
+                                                     test_val,
+                                                     val,
+                                                     t,
+                                                     ast::BiGe,
+                                                     debug_loc)
                             }
                         }
                     };
@@ -1149,37 +1201,37 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
                     if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
                         branch_chk = Some(JumpToBasicBlock(bcx.llbb));
                     }
-                    CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb, DebugLoc::None);
+                    CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb, debug_loc);
                 }
                 _ => ()
             }
         } else if kind == Compare || kind == CompareSliceLength {
-            Br(bcx, else_cx.llbb, DebugLoc::None);
+            Br(bcx, else_cx.llbb, debug_loc);
         }
 
         let mut size = 0;
         let mut unpacked = Vec::new();
         match *opt {
-            Variant(disr_val, ref repr, _) => {
+            Variant(disr_val, ref repr, _, _) => {
                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
                     extract_variant_args(opt_cx, &**repr, disr_val, val);
                 size = argvals.len();
                 unpacked = argvals;
                 opt_cx = new_bcx;
             }
-            SliceLengthEqual(len) => {
+            SliceLengthEqual(len, _) => {
                 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
                 size = args.vals.len();
                 unpacked = args.vals.clone();
                 opt_cx = args.bcx;
             }
-            SliceLengthGreaterOrEqual(before, after) => {
+            SliceLengthGreaterOrEqual(before, after, _) => {
                 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
                 size = args.vals.len();
                 unpacked = args.vals.clone();
                 opt_cx = args.bcx;
             }
-            ConstantValue(_) | ConstantRange(_, _) => ()
+            ConstantValue(..) | ConstantRange(..) => ()
         }
         let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
         let mut opt_vals = unpacked;
@@ -1383,16 +1435,27 @@ fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
         bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
     }).collect();
 
-    let mut static_inliner = StaticInliner::new(scope_cx.tcx());
-    let arm_pats: Vec<Vec<P<ast::Pat>>> = arm_datas.iter().map(|arm_data| {
-        arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
-    }).collect();
+    let mut pat_renaming_map = if scope_cx.sess().opts.debuginfo != NoDebugInfo {
+        Some(FnvHashMap())
+    } else {
+        None
+    };
+
+    let arm_pats: Vec<Vec<P<ast::Pat>>> = {
+        let mut static_inliner = StaticInliner::new(scope_cx.tcx(),
+                                                    pat_renaming_map.as_mut());
+        arm_datas.iter().map(|arm_data| {
+            arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
+        }).collect()
+    };
+
     let mut matches = Vec::new();
     for (arm_data, pats) in arm_datas.iter().zip(arm_pats.iter()) {
         matches.extend(pats.iter().map(|p| Match {
             pats: vec![&**p],
             data: arm_data,
             bound_ptrs: Vec::new(),
+            pat_renaming_map: pat_renaming_map.as_ref()
         }));
     }
 
index b99622ce911d2f2b6ee0f393874335e78eee358d..8bb60eca8b14a12e1af6f3b8a7d6709c755d0649 100644 (file)
@@ -265,9 +265,9 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
             // Use the minimum integer type we figured out above
             let fields : Vec<_> = cases.iter().map(|c| {
                 let mut ftys = vec!(ty_of_inttype(cx.tcx(), min_ity));
-                ftys.push_all(c.tys.as_slice());
+                ftys.push_all(&c.tys);
                 if dtor { ftys.push(cx.tcx().types.bool); }
-                mk_struct(cx, ftys.as_slice(), false, t)
+                mk_struct(cx, &ftys, false, t)
             }).collect();
 
 
@@ -283,7 +283,7 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
             // This check is needed to avoid increasing the size of types when
             // the alignment of the first field is smaller than the overall
             // alignment of the type.
-            let (_, align) = union_size_and_align(fields.as_slice());
+            let (_, align) = union_size_and_align(&fields);
             let mut use_align = true;
             for st in &fields {
                 // Get the first non-zero-sized field
@@ -751,7 +751,7 @@ pub fn trans_get_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
         RawNullablePointer { nndiscr, nnty, .. } =>  {
             let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
             let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
-            val = ICmp(bcx, cmp, Load(bcx, scrutinee), C_null(llptrty));
+            val = ICmp(bcx, cmp, Load(bcx, scrutinee), C_null(llptrty), DebugLoc::None);
             signed = false;
         }
         StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
@@ -770,7 +770,7 @@ fn struct_wrapped_nullable_bitdiscr(bcx: Block, nndiscr: Disr, discrfield: &Disc
     let llptrptr = GEPi(bcx, scrutinee, &discrfield[]);
     let llptr = Load(bcx, llptrptr);
     let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
-    ICmp(bcx, cmp, llptr, C_null(val_ty(llptr)))
+    ICmp(bcx, cmp, llptr, C_null(val_ty(llptr)), DebugLoc::None)
 }
 
 /// Helper for cases where the discriminant is simply loaded.
index 05abd3ff5577d7b211a0a59a2ded4b493aeccf8f..e419be65fc4cc33f1a141aff8bf5e2dbf775d8c1 100644 (file)
@@ -77,13 +77,13 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
     fcx.pop_custom_cleanup_scope(temp_scope);
 
     let mut constraints = constraints.iter()
-                                     .map(|s| s.get().to_string())
+                                     .map(|s| s.to_string())
                                      .chain(ext_constraints.into_iter())
                                      .collect::<Vec<String>>()
                                      .connect(",");
 
     let mut clobbers = ia.clobbers.iter()
-                                  .map(|s| format!("~{{{}}}", s.get()))
+                                  .map(|s| format!("~{{{}}}", &s))
                                   .collect::<Vec<String>>()
                                   .connect(",");
     let more_clobbers = get_clobbers();
@@ -120,12 +120,12 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
         ast::AsmIntel => llvm::AD_Intel
     };
 
-    let asm = CString::from_slice(ia.asm.get().as_bytes());
+    let asm = CString::from_slice(ia.asm.as_bytes());
     let constraints = CString::from_slice(constraints.as_bytes());
     let r = InlineAsmCall(bcx,
                           asm.as_ptr(),
                           constraints.as_ptr(),
-                          inputs.as_slice(),
+                          &inputs,
                           output_type,
                           ia.volatile,
                           ia.alignstack,
index c2af6ec8c8ad82183cea6d88dfb267ad9c6c1b4e..52ef2b75f9571b3e89676948313ce897c829dc18 100644 (file)
@@ -57,7 +57,7 @@
 use trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_integral};
 use trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
 use trans::common::{CrateContext, ExternMap, FunctionContext};
-use trans::common::{Result};
+use trans::common::{Result, NodeIdAndSpan};
 use trans::common::{node_id_type, return_type_is_void};
 use trans::common::{tydesc_info, type_is_immediate};
 use trans::common::{type_is_zero_size, val_ty};
@@ -66,7 +66,7 @@
 use trans::context::SharedCrateContext;
 use trans::controlflow;
 use trans::datum;
-use trans::debuginfo::{self, DebugLoc};
+use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
 use trans::expr;
 use trans::foreign;
 use trans::glue;
@@ -115,7 +115,7 @@ pub fn with_insn_ctxt<F>(blk: F) where
     F: FnOnce(&[&'static str]),
 {
     TASK_LOCAL_INSN_KEY.with(move |slot| {
-        slot.borrow().as_ref().map(move |s| blk(s.as_slice()));
+        slot.borrow().as_ref().map(move |s| blk(s));
     })
 }
 
@@ -379,7 +379,8 @@ pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                                   llty_ptr: Type,
                                   info_ty: Ty<'tcx>,
                                   size: ValueRef,
-                                  align: ValueRef)
+                                  align: ValueRef,
+                                  debug_loc: DebugLoc)
                                   -> Result<'blk, 'tcx> {
     let _icx = push_ctxt("malloc_raw_exchange");
 
@@ -387,7 +388,8 @@ pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
     let r = callee::trans_lang_call(bcx,
         require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
         &[size, align],
-        None);
+        None,
+        debug_loc);
 
     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
 }
@@ -444,7 +446,7 @@ pub fn set_llvm_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: Val
 
     for attr in attrs {
         let mut used = true;
-        match attr.name().get() {
+        match &attr.name()[] {
             "no_stack_check" => unset_split_stack(llfn),
             "no_split_stack" => {
                 unset_split_stack(llfn);
@@ -538,9 +540,10 @@ pub fn compare_scalar_types<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
                                         lhs: ValueRef,
                                         rhs: ValueRef,
                                         t: Ty<'tcx>,
-                                        op: ast::BinOp_)
+                                        op: ast::BinOp_,
+                                        debug_loc: DebugLoc)
                                         -> Result<'blk, 'tcx> {
-    let f = |&: a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
+    let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op, debug_loc));
 
     match t.sty {
         ty::ty_tup(ref tys) if tys.is_empty() => f(nil_type),
@@ -559,7 +562,8 @@ pub fn compare_scalar_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
                                          lhs: ValueRef,
                                          rhs: ValueRef,
                                          nt: scalar_type,
-                                         op: ast::BinOp_)
+                                         op: ast::BinOp_,
+                                         debug_loc: DebugLoc)
                                          -> ValueRef {
     let _icx = push_ctxt("compare_scalar_values");
     fn die(cx: Block) -> ! {
@@ -586,7 +590,7 @@ fn die(cx: Block) -> ! {
           ast::BiGe => llvm::RealOGE,
           _ => die(cx)
         };
-        return FCmp(cx, cmp, lhs, rhs);
+        return FCmp(cx, cmp, lhs, rhs, debug_loc);
       }
       signed_int => {
         let cmp = match op {
@@ -598,7 +602,7 @@ fn die(cx: Block) -> ! {
           ast::BiGe => llvm::IntSGE,
           _ => die(cx)
         };
-        return ICmp(cx, cmp, lhs, rhs);
+        return ICmp(cx, cmp, lhs, rhs, debug_loc);
       }
       unsigned_int => {
         let cmp = match op {
@@ -610,7 +614,7 @@ fn die(cx: Block) -> ! {
           ast::BiGe => llvm::IntUGE,
           _ => die(cx)
         };
-        return ICmp(cx, cmp, lhs, rhs);
+        return ICmp(cx, cmp, lhs, rhs, debug_loc);
       }
     }
 }
@@ -621,7 +625,8 @@ pub fn compare_simd_types<'blk, 'tcx>(
                     rhs: ValueRef,
                     t: Ty<'tcx>,
                     size: uint,
-                    op: ast::BinOp)
+                    op: ast::BinOp_,
+                    debug_loc: DebugLoc)
                     -> ValueRef {
     let cmp = match t.sty {
         ty::ty_float(_) => {
@@ -632,7 +637,7 @@ pub fn compare_simd_types<'blk, 'tcx>(
             cx.sess().bug("compare_simd_types: comparison operators \
                            not supported for floating point SIMD types")
         },
-        ty::ty_uint(_) => match op.node {
+        ty::ty_uint(_) => match op {
             ast::BiEq => llvm::IntEQ,
             ast::BiNe => llvm::IntNE,
             ast::BiLt => llvm::IntULT,
@@ -641,7 +646,7 @@ pub fn compare_simd_types<'blk, 'tcx>(
             ast::BiGe => llvm::IntUGE,
             _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
         },
-        ty::ty_int(_) => match op.node {
+        ty::ty_int(_) => match op {
             ast::BiEq => llvm::IntEQ,
             ast::BiNe => llvm::IntNE,
             ast::BiLt => llvm::IntSLT,
@@ -657,7 +662,7 @@ pub fn compare_simd_types<'blk, 'tcx>(
     // to get the correctly sized type. This will compile to a single instruction
     // once the IR is converted to assembly if the SIMD instruction is supported
     // by the target architecture.
-    SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
+    SExt(cx, ICmp(cx, cmp, lhs, rhs, debug_loc), return_ty)
 }
 
 // Iterates through the elements of a structural type.
@@ -851,7 +856,7 @@ pub fn cast_shift_rhs<F, G>(op: ast::BinOp,
 
 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
                                 cx: Block<'blk, 'tcx>,
-                                span: Span,
+                                call_info: NodeIdAndSpan,
                                 divrem: ast::BinOp,
                                 lhs: ValueRef,
                                 rhs: ValueRef,
@@ -864,14 +869,16 @@ pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
         ("attempted remainder with a divisor of zero",
          "attempted remainder with overflow")
     };
+    let debug_loc = call_info.debug_loc();
+
     let (is_zero, is_signed) = match rhs_t.sty {
         ty::ty_int(t) => {
             let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
-            (ICmp(cx, llvm::IntEQ, rhs, zero), true)
+            (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
         }
         ty::ty_uint(t) => {
             let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
-            (ICmp(cx, llvm::IntEQ, rhs, zero), false)
+            (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
         }
         _ => {
             cx.sess().bug(&format!("fail-if-zero on unexpected type: {}",
@@ -879,7 +886,7 @@ pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
         }
     };
     let bcx = with_cond(cx, is_zero, |bcx| {
-        controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
+        controlflow::trans_fail(bcx, call_info, InternedString::new(zero_text))
     });
 
     // To quote LLVM's documentation for the sdiv instruction:
@@ -908,12 +915,13 @@ pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
             _ => unreachable!(),
         };
         let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
-                             C_integral(llty, -1, false));
+                             C_integral(llty, -1, false), debug_loc);
         with_cond(bcx, minus_one, |bcx| {
             let is_min = ICmp(bcx, llvm::IntEQ, lhs,
-                              C_integral(llty, min, true));
+                              C_integral(llty, min, true), debug_loc);
             with_cond(bcx, is_min, |bcx| {
-                controlflow::trans_fail(bcx, span,
+                controlflow::trans_fail(bcx,
+                                        call_info,
                                         InternedString::new(overflow_text))
             })
         })
@@ -1081,6 +1089,12 @@ pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
     F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>,
 {
     let _icx = push_ctxt("with_cond");
+
+    if bcx.unreachable.get() ||
+            (common::is_const(val) && common::const_to_uint(val) == 0) {
+        return bcx;
+    }
+
     let fcx = bcx.fcx;
     let next_cx = fcx.new_temp_block("next");
     let cond_cx = fcx.new_temp_block("cond");
@@ -1354,8 +1368,8 @@ fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>)
         // glue, shims, etc
         None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
 
-        _ => tcx.sess.bug(format!("unexpected variant in has_nested_returns: {}",
-                                  tcx.map.path_to_string(id)).as_slice())
+        _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
+                                   tcx.map.path_to_string(id)))
     };
 
     (blk.id, Some(cfg::CFG::new(tcx, &**blk)))
@@ -2247,8 +2261,8 @@ pub fn update_linkage(ccx: &CrateContext,
     if let Some(id) = id {
         let item = ccx.tcx().map.get(id);
         if let ast_map::NodeItem(i) = item {
-            if let Some(name) = attr::first_attr_value_str_by_name(i.attrs.as_slice(), "linkage") {
-                if let Some(linkage) = llvm_linkage_by_name(name.get()) {
+            if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
+                if let Some(linkage) = llvm_linkage_by_name(&name) {
                     llvm::SetLinkage(llval, linkage);
                 } else {
                     ccx.sess().span_fatal(i.span, "invalid linkage specified");
@@ -2721,7 +2735,7 @@ fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId,
 
     match attr::first_attr_value_str_by_name(attrs, "export_name") {
         // Use provided name
-        Some(name) => name.get().to_string(),
+        Some(name) => name.to_string(),
 
         _ => ccx.tcx().map.with_path(id, |path| {
             if attr::contains_name(attrs, "no_mangle") {
@@ -2729,7 +2743,7 @@ fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId,
                 path.last().unwrap().to_string()
             } else {
                 match weak_lang_items::link_name(attrs) {
-                    Some(name) => name.get().to_string(),
+                    Some(name) => name.to_string(),
                     None => {
                         // Usual name mangling
                         mangle_exported_name(ccx, path, ty, id)
@@ -2757,7 +2771,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
     let val = match item {
         ast_map::NodeItem(i) => {
             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
-            let sym = |&:| exported_name(ccx, id, ty, &i.attrs[]);
+            let sym = || exported_name(ccx, id, ty, &i.attrs[]);
 
             let v = match i.node {
                 ast::ItemStatic(_, _, ref expr) => {
@@ -2824,12 +2838,12 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
             match attr::first_attr_value_str_by_name(&i.attrs[],
                                                      "link_section") {
                 Some(sect) => {
-                    if contains_null(sect.get()) {
+                    if contains_null(&sect) {
                         ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`",
-                                                 sect.get())[]);
+                                                 &sect)[]);
                     }
                     unsafe {
-                        let buf = CString::from_slice(sect.get().as_bytes());
+                        let buf = CString::from_slice(sect.as_bytes());
                         llvm::LLVMSetSection(v, buf.as_ptr());
                     }
                 },
@@ -2869,7 +2883,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
                     let abi = ccx.tcx().map.get_foreign_abi(id);
                     let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
                     let name = foreign::link_name(&*ni);
-                    foreign::register_foreign_item_fn(ccx, abi, ty, &name.get()[])
+                    foreign::register_foreign_item_fn(ccx, abi, ty, &name)
                 }
                 ast::ForeignItemStatic(..) => {
                     foreign::register_static(ccx, &*ni)
@@ -2987,10 +3001,10 @@ pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
     let metadata = encoder::encode_metadata(encode_parms, krate);
     let mut compressed = encoder::metadata_encoding_version.to_vec();
-    compressed.push_all(match flate::deflate_bytes(metadata.as_slice()) {
+    compressed.push_all(&match flate::deflate_bytes(&metadata) {
         Some(compressed) => compressed,
         None => cx.sess().fatal("failed to compress metadata"),
-    }.as_slice());
+    });
     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[]);
     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
     let name = format!("rust_metadata_{}_{}",
@@ -3016,14 +3030,14 @@ fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
     unsafe {
         let mut declared = HashSet::new();
 
-        let iter_globals = |&: llmod| {
+        let iter_globals = |llmod| {
             ValueIter {
                 cur: llvm::LLVMGetFirstGlobal(llmod),
                 step: llvm::LLVMGetNextGlobal,
             }
         };
 
-        let iter_functions = |&: llmod| {
+        let iter_functions = |llmod| {
             ValueIter {
                 cur: llvm::LLVMGetFirstFunction(llmod),
                 step: llvm::LLVMGetNextFunction,
@@ -3062,7 +3076,7 @@ fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
                 let name = ffi::c_str_to_bytes(&llvm::LLVMGetValueName(val))
                                .to_vec();
                 if !declared.contains(&name) &&
-                   !reachable.contains(str::from_utf8(name.as_slice()).unwrap()) {
+                   !reachable.contains(str::from_utf8(&name).unwrap()) {
                     llvm::SetLinkage(val, llvm::InternalLinkage);
                 }
             }
index c288a8196e63c0b8e9fcbe53fc5e3fa41cf49a8a..2fcfc5e43931d2770391bde8b4c03e92b6505954 100644 (file)
@@ -856,22 +856,32 @@ pub fn FPCast(cx: Block, val: ValueRef, dest_ty: Type) -> ValueRef {
 
 
 /* Comparisons */
-pub fn ICmp(cx: Block, op: IntPredicate, lhs: ValueRef, rhs: ValueRef)
-     -> ValueRef {
+pub fn ICmp(cx: Block,
+            op: IntPredicate,
+            lhs: ValueRef,
+            rhs: ValueRef,
+            debug_loc: DebugLoc)
+            -> ValueRef {
     unsafe {
         if cx.unreachable.get() {
             return llvm::LLVMGetUndef(Type::i1(cx.ccx()).to_ref());
         }
+        debug_loc.apply(cx.fcx);
         B(cx).icmp(op, lhs, rhs)
     }
 }
 
-pub fn FCmp(cx: Block, op: RealPredicate, lhs: ValueRef, rhs: ValueRef)
-     -> ValueRef {
+pub fn FCmp(cx: Block,
+            op: RealPredicate,
+            lhs: ValueRef,
+            rhs: ValueRef,
+            debug_loc: DebugLoc)
+            -> ValueRef {
     unsafe {
         if cx.unreachable.get() {
             return llvm::LLVMGetUndef(Type::i1(cx.ccx()).to_ref());
         }
+        debug_loc.apply(cx.fcx);
         B(cx).fcmp(op, lhs, rhs)
     }
 }
@@ -941,9 +951,17 @@ pub fn Call(cx: Block,
     B(cx).call(fn_, args, attributes)
 }
 
-pub fn CallWithConv(cx: Block, fn_: ValueRef, args: &[ValueRef], conv: CallConv,
-                    attributes: Option<AttrBuilder>) -> ValueRef {
-    if cx.unreachable.get() { return _UndefReturn(cx, fn_); }
+pub fn CallWithConv(cx: Block,
+                    fn_: ValueRef,
+                    args: &[ValueRef],
+                    conv: CallConv,
+                    attributes: Option<AttrBuilder>,
+                    debug_loc: DebugLoc)
+                    -> ValueRef {
+    if cx.unreachable.get() {
+        return _UndefReturn(cx, fn_);
+    }
+    debug_loc.apply(cx.fcx);
     B(cx).call_with_conv(fn_, args, conv, attributes)
 }
 
index fecd1a9013bb2c5bb9f7ea8cb1b278ad951bcccb..bc171e3ae4381fbbce881c5fdc3e3627b53e1d1e 100644 (file)
@@ -159,7 +159,7 @@ fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> {
 
 fn struct_ty(ccx: &CrateContext, ty: Type) -> Type {
     let size = ty_size(ty) * 8;
-    Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
+    Type::struct_(ccx, &coerce_to_int(ccx, size), false)
 }
 
 pub fn compute_abi_info(ccx: &CrateContext,
index 9583158a0e243971d028b6e0edef7b4a223a9409..4871617e89f3bfd1b0b9c5f319f984cd774ac18c 100644 (file)
@@ -154,7 +154,7 @@ fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> {
 
 fn struct_ty(ccx: &CrateContext, ty: Type) -> Type {
     let size = ty_size(ty) * 8;
-    Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
+    Type::struct_(ccx, &coerce_to_int(ccx, size), false)
 }
 
 pub fn compute_abi_info(ccx: &CrateContext,
index 2484e74e19349a9f2aa30398d255ba1432a09fa3..ab41fe31a6e20b0343e7fbe409b75404119557b3 100644 (file)
@@ -237,7 +237,7 @@ fn classify(ty: Type,
                 unify(cls, ix + off / 8, SSEDs);
             }
             Struct => {
-                classify_struct(ty.field_types().as_slice(), cls, ix, off, ty.is_packed());
+                classify_struct(&ty.field_types(), cls, ix, off, ty.is_packed());
             }
             Array => {
                 let len = ty.array_length();
@@ -322,11 +322,11 @@ fn fixup(ty: Type, cls: &mut [RegClass]) {
     let words = (ty_size(ty) + 7) / 8;
     let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
     if words > 4 {
-        all_mem(cls.as_mut_slice());
+        all_mem(&mut cls);
         return cls;
     }
-    classify(ty, cls.as_mut_slice(), 0, 0);
-    fixup(ty, cls.as_mut_slice());
+    classify(ty, &mut cls, 0, 0);
+    fixup(ty, &mut cls);
     return cls;
 }
 
@@ -381,7 +381,7 @@ fn llvec_len(cls: &[RegClass]) -> uint {
         // if the type contains only a vector, pass it as that vector.
         tys[0]
     } else {
-        Type::struct_(ccx, tys.as_slice(), false)
+        Type::struct_(ccx, &tys, false)
     }
 }
 
@@ -398,11 +398,11 @@ fn x86_64_ty<F>(ccx: &CrateContext,
     {
         if !ty.is_reg_ty() {
             let cls = classify_ty(ty);
-            if is_mem_cls(cls.as_slice()) {
+            if is_mem_cls(&cls) {
                 ArgType::indirect(ty, Some(ind_attr))
             } else {
                 ArgType::direct(ty,
-                                Some(llreg_ty(ccx, cls.as_slice())),
+                                Some(llreg_ty(ccx, &cls)),
                                 None,
                                 None)
             }
index 5f383d54a68ca5d355fb45fc49e90335dd245dfb..e45918ce5a7455998131deae030462b578f89512 100644 (file)
@@ -36,8 +36,8 @@
 use trans::cleanup;
 use trans::cleanup::CleanupMethods;
 use trans::closure;
-use trans::common;
-use trans::common::*;
+use trans::common::{self, Block, Result, NodeIdAndSpan, ExprId, CrateContext,
+                    ExprOrMethodCall, FunctionContext, MethodCallKey};
 use trans::consts;
 use trans::datum::*;
 use trans::debuginfo::{DebugLoc, ToDebugLoc};
@@ -136,7 +136,7 @@ fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                              ref_expr: &ast::Expr)
                              -> Callee<'blk, 'tcx> {
         debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
-        let expr_ty = node_id_type(bcx, ref_expr.id);
+        let expr_ty = common::node_id_type(bcx, ref_expr.id);
         match def {
             def::DefFn(did, _) if {
                 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
@@ -147,8 +147,9 @@ fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                     _ => false
                 }
             } => {
-                let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
-                                            bcx.fcx.param_substs);
+                let substs = common::node_id_substs(bcx.ccx(),
+                                                    ExprId(ref_expr.id),
+                                                    bcx.fcx.param_substs);
                 Callee {
                     bcx: bcx,
                     data: NamedTupleConstructor(substs, 0)
@@ -158,8 +159,9 @@ fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                 ty::ty_bare_fn(_, ref f) => f.abi == synabi::RustIntrinsic,
                 _ => false
             } => {
-                let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
-                                            bcx.fcx.param_substs);
+                let substs = common::node_id_substs(bcx.ccx(),
+                                                    ExprId(ref_expr.id),
+                                                    bcx.fcx.param_substs);
                 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
                 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
             }
@@ -178,8 +180,9 @@ fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             }
             def::DefVariant(tid, vid, _) => {
                 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
-                let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
-                                            bcx.fcx.param_substs);
+                let substs = common::node_id_substs(bcx.ccx(),
+                                                    ExprId(ref_expr.id),
+                                                    bcx.fcx.param_substs);
 
                 // Nullary variants are not callable
                 assert!(vinfo.args.len() > 0);
@@ -190,8 +193,9 @@ fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                 }
             }
             def::DefStruct(_) => {
-                let substs = node_id_substs(bcx.ccx(), ExprId(ref_expr.id),
-                                            bcx.fcx.param_substs);
+                let substs = common::node_id_substs(bcx.ccx(),
+                                                    ExprId(ref_expr.id),
+                                                    bcx.fcx.param_substs);
                 Callee {
                     bcx: bcx,
                     data: NamedTupleConstructor(substs, 0)
@@ -226,7 +230,7 @@ pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
                               -> Datum<'tcx, Rvalue> {
     let _icx = push_ctxt("trans_fn_ref");
 
-    let substs = node_id_substs(ccx, node, param_substs);
+    let substs = common::node_id_substs(ccx, node, param_substs);
     debug!("trans_fn_ref(def_id={}, node={:?}, substs={})",
            def_id.repr(ccx.tcx()),
            node,
@@ -269,7 +273,7 @@ pub fn trans_fn_pointer_shim<'a, 'tcx>(
     let _icx = push_ctxt("trans_fn_pointer_shim");
     let tcx = ccx.tcx();
 
-    let bare_fn_ty = erase_regions(tcx, &bare_fn_ty);
+    let bare_fn_ty = common::erase_regions(tcx, &bare_fn_ty);
     match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty) {
         Some(&llval) => { return llval; }
         None => { }
@@ -352,7 +356,7 @@ pub fn trans_fn_pointer_shim<'a, 'tcx>(
     );
 
     bcx = trans_call_inner(bcx,
-                           None,
+                           DebugLoc::None,
                            bare_fn_ty,
                            |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) },
                            ArgVals(&llargs[]),
@@ -515,7 +519,7 @@ pub fn trans_fn_ref_with_substs<'a, 'tcx>(
                                                           param_substs,
                                                           &ref_ty);
             let llptrty = type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to();
-            if llptrty != val_ty(val) {
+            if llptrty != common::val_ty(val) {
                 let val = consts::ptrcast(val, llptrty);
                 return Datum::new(val, ref_ty, Rvalue::new(ByValue));
             }
@@ -563,7 +567,7 @@ pub fn trans_fn_ref_with_substs<'a, 'tcx>(
     // other weird situations. Annoying.
     let llty = type_of::type_of_fn_from_ty(ccx, fn_type);
     let llptrty = llty.ptr_to();
-    if val_ty(val) != llptrty {
+    if common::val_ty(val) != llptrty {
         debug!("trans_fn_ref_with_vtables(): casting pointer!");
         val = consts::ptrcast(val, llptrty);
     } else {
@@ -577,34 +581,34 @@ pub fn trans_fn_ref_with_substs<'a, 'tcx>(
 // Translating calls
 
 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
-                                  call_ex: &ast::Expr,
+                                  call_expr: &ast::Expr,
                                   f: &ast::Expr,
                                   args: CallArgs<'a, 'tcx>,
                                   dest: expr::Dest)
                                   -> Block<'blk, 'tcx> {
     let _icx = push_ctxt("trans_call");
     trans_call_inner(in_cx,
-                     Some(common::expr_info(call_ex)),
-                     expr_ty_adjusted(in_cx, f),
+                     call_expr.debug_loc(),
+                     common::expr_ty_adjusted(in_cx, f),
                      |cx, _| trans(cx, f),
                      args,
                      Some(dest)).bcx
 }
 
 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
-                                         call_ex: &ast::Expr,
+                                         call_expr: &ast::Expr,
                                          rcvr: &ast::Expr,
                                          args: CallArgs<'a, 'tcx>,
                                          dest: expr::Dest)
                                          -> Block<'blk, 'tcx> {
     let _icx = push_ctxt("trans_method_call");
-    debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
-    let method_call = MethodCall::expr(call_ex.id);
+    debug!("trans_method_call(call_expr={})", call_expr.repr(bcx.tcx()));
+    let method_call = MethodCall::expr(call_expr.id);
     let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
     trans_call_inner(
         bcx,
-        Some(common::expr_info(call_ex)),
-        monomorphize_type(bcx, method_ty),
+        call_expr.debug_loc(),
+        common::monomorphize_type(bcx, method_ty),
         |cx, arg_cleanup_scope| {
             meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
         },
@@ -615,7 +619,8 @@ pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                                    did: ast::DefId,
                                    args: &[ValueRef],
-                                   dest: Option<expr::Dest>)
+                                   dest: Option<expr::Dest>,
+                                   debug_loc: DebugLoc)
                                    -> Result<'blk, 'tcx> {
     let fty = if did.krate == ast::LOCAL_CRATE {
         ty::node_id_to_type(bcx.tcx(), did.node)
@@ -623,7 +628,7 @@ pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
         csearch::get_type(bcx.tcx(), did).ty
     };
     callee::trans_call_inner(bcx,
-                             None,
+                             debug_loc,
                              fty,
                              |bcx, _| {
                                 trans_fn_ref_with_substs_to_callee(bcx,
@@ -646,7 +651,7 @@ pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
 /// somewhere. Nonetheless we return the actual return value of the function.
 pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
-                                           call_info: Option<NodeIdAndSpan>,
+                                           debug_loc: DebugLoc,
                                            callee_ty: Ty<'tcx>,
                                            get_callee: F,
                                            args: CallArgs<'a, 'tcx>,
@@ -687,7 +692,13 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
             assert!(abi == synabi::RustIntrinsic);
             assert!(dest.is_some());
 
-            let call_info = call_info.expect("no call info for intrinsic call?");
+            let call_info = match debug_loc {
+                DebugLoc::At(id, span) => NodeIdAndSpan { id: id, span: span },
+                DebugLoc::None => {
+                    bcx.sess().bug("No call info for intrinsic call?")
+                }
+            };
+
             return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
                                                    arg_cleanup_scope, args,
                                                    dest.unwrap(), substs,
@@ -703,7 +714,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
                                                        disr,
                                                        args,
                                                        dest.unwrap(),
-                                                       call_info.debug_loc());
+                                                       debug_loc);
         }
     };
 
@@ -724,12 +735,12 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
             };
             if !is_rust_fn ||
               type_of::return_uses_outptr(ccx, ret_ty) ||
-              type_needs_drop(bcx.tcx(), ret_ty) {
+              common::type_needs_drop(bcx.tcx(), ret_ty) {
                 // Push the out-pointer if we use an out-pointer for this
                 // return type, otherwise push "undef".
-                if type_is_zero_size(ccx, ret_ty) {
+                if common::type_is_zero_size(ccx, ret_ty) {
                     let llty = type_of::type_of(ccx, ret_ty);
-                    Some(C_undef(llty.ptr_to()))
+                    Some(common::C_undef(llty.ptr_to()))
                 } else {
                     Some(alloc_ty(bcx, ret_ty, "__llret"))
                 }
@@ -781,7 +792,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
                                       llfn,
                                       &llargs[],
                                       callee_ty,
-                                      call_info.debug_loc());
+                                      debug_loc);
         bcx = b;
         llresult = llret;
 
@@ -790,7 +801,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
         match (opt_llretslot, ret_ty) {
             (Some(llretslot), ty::FnConverging(ret_ty)) => {
                 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
-                    !type_is_zero_size(bcx.ccx(), ret_ty)
+                    !common::type_is_zero_size(bcx.ccx(), ret_ty)
                 {
                     store_ty(bcx, llret, llretslot, ret_ty)
                 }
@@ -804,7 +815,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
 
         let mut llargs = Vec::new();
         let arg_tys = match args {
-            ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
+            ArgExprs(a) => a.iter().map(|x| common::expr_ty(bcx, &**x)).collect(),
             _ => panic!("expected arg exprs.")
         };
         bcx = trans_args(bcx,
@@ -816,9 +827,13 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
                          abi);
         fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
 
-        bcx = foreign::trans_native_call(bcx, callee_ty,
-                                         llfn, opt_llretslot.unwrap(),
-                                         &llargs[], arg_tys);
+        bcx = foreign::trans_native_call(bcx,
+                                         callee_ty,
+                                         llfn,
+                                         opt_llretslot.unwrap(),
+                                         &llargs[],
+                                         arg_tys,
+                                         debug_loc);
     }
 
     fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
@@ -831,7 +846,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
             bcx = glue::drop_ty(bcx,
                                 llretslot,
                                 ret_ty,
-                                call_info.debug_loc());
+                                debug_loc);
             call_lifetime_end(bcx, llretslot);
         }
         _ => {}
@@ -892,7 +907,7 @@ fn trans_args_under_call_abi<'blk, 'tcx>(
 
     // Now untuple the rest of the arguments.
     let tuple_expr = &arg_exprs[1];
-    let tuple_type = node_id_type(bcx, tuple_expr.id);
+    let tuple_type = common::node_id_type(bcx, tuple_expr.id);
 
     match tuple_type.sty {
         ty::ty_tup(ref field_types) => {
@@ -1014,7 +1029,7 @@ pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
                 }
                 let arg_ty = if i >= num_formal_args {
                     assert!(variadic);
-                    expr_ty_adjusted(cx, &**arg_expr)
+                    common::expr_ty_adjusted(cx, &**arg_expr)
                 } else {
                     arg_tys[i]
                 };
index ac76b52598d15c6e8917093c012173ed38c0e3a4..bebba151a0d313dee2db00c21bb38349b54f6b71 100644 (file)
@@ -940,11 +940,12 @@ fn trans<'blk>(&self,
                    bcx: Block<'blk, 'tcx>,
                    debug_loc: DebugLoc)
                    -> Block<'blk, 'tcx> {
-        debug_loc.apply(bcx.fcx);
-
         match self.heap {
             HeapExchange => {
-                glue::trans_exchange_free_ty(bcx, self.ptr, self.content_ty)
+                glue::trans_exchange_free_ty(bcx,
+                                             self.ptr,
+                                             self.content_ty,
+                                             debug_loc)
             }
         }
     }
@@ -975,11 +976,13 @@ fn trans<'blk>(&self,
                    bcx: Block<'blk, 'tcx>,
                    debug_loc: DebugLoc)
                    -> Block<'blk, 'tcx> {
-        debug_loc.apply(bcx.fcx);
-
         match self.heap {
             HeapExchange => {
-                glue::trans_exchange_free_dyn(bcx, self.ptr, self.size, self.align)
+                glue::trans_exchange_free_dyn(bcx,
+                                              self.ptr,
+                                              self.size,
+                                              self.align,
+                                              debug_loc)
             }
         }
     }
index b65d50095b3f09c0397ff10757d884a5d978dd42..87b7f413fd1e55b112cc1259f275766caba222f8 100644 (file)
@@ -590,7 +590,7 @@ pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
     pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
 
     pub fn ident(&self, ident: Ident) -> String {
-        token::get_ident(ident).get().to_string()
+        token::get_ident(ident).to_string()
     }
 
     pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
@@ -834,8 +834,8 @@ pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> Va
         }
 
         let sc = llvm::LLVMConstStringInContext(cx.llcx(),
-                                                s.get().as_ptr() as *const c_char,
-                                                s.get().len() as c_uint,
+                                                s.as_ptr() as *const c_char,
+                                                s.len() as c_uint,
                                                 !null_terminated as Bool);
 
         let gsym = token::gensym("str");
@@ -853,7 +853,7 @@ pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> Va
 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
 // you will be kicked off fast isel. See issue #4352 for an example of this.
 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
-    let len = s.get().len();
+    let len = s.len();
     let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
     C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
 }
index 0403a2f2e3c679d9d4447c79db69b76c045a4046..278323d186b21cb88de133cf3726ab2c71e206e7 100644 (file)
@@ -58,13 +58,13 @@ pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit)
             }
         }
         ast::LitFloat(ref fs, t) => {
-            C_floating(fs.get(), Type::float_from_ty(cx, t))
+            C_floating(&fs, Type::float_from_ty(cx, t))
         }
         ast::LitFloatUnsuffixed(ref fs) => {
             let lit_float_ty = ty::node_id_to_type(cx.tcx(), e.id);
             match lit_float_ty.sty {
                 ty::ty_float(t) => {
-                    C_floating(fs.get(), Type::float_from_ty(cx, t))
+                    C_floating(&fs, Type::float_from_ty(cx, t))
                 }
                 _ => {
                     cx.sess().span_bug(lit.span,
@@ -241,8 +241,10 @@ pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr)
                                         ty::ty_vec(unit_ty, Some(len)) => {
                                             let llunitty = type_of::type_of(cx, unit_ty);
                                             let llptr = ptrcast(llconst, llunitty.ptr_to());
-                                            assert!(cx.const_globals().borrow_mut()
-                                                      .insert(llptr as int, llconst).is_none());
+                                            let prev_const = cx.const_globals().borrow_mut()
+                                                             .insert(llptr as int, llconst);
+                                            assert!(prev_const.is_none() ||
+                                                    prev_const == Some(llconst));
                                             assert_eq!(abi::FAT_PTR_ADDR, 0);
                                             assert_eq!(abi::FAT_PTR_EXTRA, 1);
                                             llconst = C_struct(cx, &[
@@ -289,7 +291,7 @@ pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr)
 // the bool returned is whether this expression can be inlined into other crates
 // if it's assigned to a static.
 fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef {
-    let map_list = |&: exprs: &[P<ast::Expr>]| {
+    let map_list = |exprs: &[P<ast::Expr>]| {
         exprs.iter().map(|e| const_expr(cx, &**e).0)
              .fold(Vec::new(), |mut l, val| { l.push(val); l })
     };
@@ -582,7 +584,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef {
               })
           }
           ast::ExprVec(ref es) => {
-            const_vec(cx, e, es.as_slice()).0
+            const_vec(cx, e, es).0
           }
           ast::ExprRepeat(ref elem, ref count) => {
             let vec_ty = ty::expr_ty(cx.tcx(), e);
index 3a2a1d158642e161ee93b2b25d1db2816b3b42fe..27dba9c4809b93b830279af8046af9c7698300f9 100644 (file)
@@ -224,11 +224,11 @@ unsafe fn create_context_and_module(sess: &Session, mod_name: &str) -> (ContextR
     let mod_name = CString::from_slice(mod_name.as_bytes());
     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
 
-    let data_layout = sess.target.target.data_layout.as_slice();
+    let data_layout = &*sess.target.target.data_layout;
     let data_layout = CString::from_slice(data_layout.as_bytes());
     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
 
-    let llvm_target = sess.target.target.llvm_target.as_slice();
+    let llvm_target = &*sess.target.target.llvm_target;
     let llvm_target = CString::from_slice(llvm_target.as_bytes());
     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
     (llcx, llmod)
index 651058a567485e8638d8d84f676631404bf05fea..8004726d25ea2bff709c58f4995931b596538058 100644 (file)
@@ -28,7 +28,6 @@
 use syntax::ast;
 use syntax::ast::Ident;
 use syntax::ast_util;
-use syntax::codemap::Span;
 use syntax::parse::token::InternedString;
 use syntax::parse::token;
 use syntax::visit::Visitor;
@@ -361,31 +360,32 @@ pub fn trans_ret<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
 }
 
 pub fn trans_fail<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
-                              sp: Span,
+                              call_info: NodeIdAndSpan,
                               fail_str: InternedString)
                               -> Block<'blk, 'tcx> {
     let ccx = bcx.ccx();
     let _icx = push_ctxt("trans_fail_value");
 
     let v_str = C_str_slice(ccx, fail_str);
-    let loc = bcx.sess().codemap().lookup_char_pos(sp.lo);
+    let loc = bcx.sess().codemap().lookup_char_pos(call_info.span.lo);
     let filename = token::intern_and_get_ident(&loc.file.name[]);
     let filename = C_str_slice(ccx, filename);
     let line = C_uint(ccx, loc.line);
     let expr_file_line_const = C_struct(ccx, &[v_str, filename, line], false);
     let expr_file_line = consts::const_addr_of(ccx, expr_file_line_const, ast::MutImmutable);
     let args = vec!(expr_file_line);
-    let did = langcall(bcx, Some(sp), "", PanicFnLangItem);
+    let did = langcall(bcx, Some(call_info.span), "", PanicFnLangItem);
     let bcx = callee::trans_lang_call(bcx,
                                       did,
                                       &args[],
-                                      Some(expr::Ignore)).bcx;
+                                      Some(expr::Ignore),
+                                      call_info.debug_loc()).bcx;
     Unreachable(bcx);
     return bcx;
 }
 
 pub fn trans_fail_bounds_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
-                                           sp: Span,
+                                           call_info: NodeIdAndSpan,
                                            index: ValueRef,
                                            len: ValueRef)
                                            -> Block<'blk, 'tcx> {
@@ -393,7 +393,7 @@ pub fn trans_fail_bounds_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
     let _icx = push_ctxt("trans_fail_bounds_check");
 
     // Extract the file/line from the span
-    let loc = bcx.sess().codemap().lookup_char_pos(sp.lo);
+    let loc = bcx.sess().codemap().lookup_char_pos(call_info.span.lo);
     let filename = token::intern_and_get_ident(&loc.file.name[]);
 
     // Invoke the lang item
@@ -402,11 +402,12 @@ pub fn trans_fail_bounds_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
     let file_line_const = C_struct(ccx, &[filename, line], false);
     let file_line = consts::const_addr_of(ccx, file_line_const, ast::MutImmutable);
     let args = vec!(file_line, index, len);
-    let did = langcall(bcx, Some(sp), "", PanicBoundsCheckFnLangItem);
+    let did = langcall(bcx, Some(call_info.span), "", PanicBoundsCheckFnLangItem);
     let bcx = callee::trans_lang_call(bcx,
                                       did,
                                       &args[],
-                                      Some(expr::Ignore)).bcx;
+                                      Some(expr::Ignore),
+                                      call_info.debug_loc()).bcx;
     Unreachable(bcx);
     return bcx;
 }
index c6b70e1a1abc354a47b187b628d4d94b93c584ce..c10ff753936b317dbaad2ccf5b63e89aea0f00f5 100644 (file)
@@ -802,7 +802,7 @@ pub fn create_global_var_metadata(cx: &CrateContext,
     let variable_type = ty::node_id_to_type(cx.tcx(), node_id);
     let type_metadata = type_metadata(cx, variable_type, span);
     let namespace_node = namespace_for_item(cx, ast_util::local_def(node_id));
-    let var_name = token::get_ident(ident).get().to_string();
+    let var_name = token::get_ident(ident).to_string();
     let linkage_name =
         namespace_node.mangled_name_of_contained_item(&var_name[]);
     let var_scope = namespace_node.scope;
@@ -1094,7 +1094,7 @@ pub fn get_cleanup_debug_loc_for_ast_node<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
         // bodies), in which case we also just want to return the span of the
         // whole expression.
         let code_snippet = cx.sess().codemap().span_to_snippet(node_span);
-        if let Some(code_snippet) = code_snippet {
+        if let Ok(code_snippet) = code_snippet {
             let bytes = code_snippet.as_bytes();
 
             if bytes.len() > 0 && &bytes[bytes.len()-1..] == b"}" {
@@ -1113,7 +1113,7 @@ pub fn get_cleanup_debug_loc_for_ast_node<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
     }
 }
 
-#[derive(Copy, Clone, PartialEq, Eq)]
+#[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub enum DebugLoc {
     At(ast::NodeId, Span),
     None
@@ -1246,7 +1246,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
 
     let (ident, fn_decl, generics, top_level_block, span, has_path) = match fnitem {
         ast_map::NodeItem(ref item) => {
-            if contains_nodebug_attribute(item.attrs.as_slice()) {
+            if contains_nodebug_attribute(&item.attrs) {
                 return FunctionDebugContext::FunctionWithoutDebugInfo;
             }
 
@@ -1263,7 +1263,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
         ast_map::NodeImplItem(ref item) => {
             match **item {
                 ast::MethodImplItem(ref method) => {
-                    if contains_nodebug_attribute(method.attrs.as_slice()) {
+                    if contains_nodebug_attribute(&method.attrs) {
                         return FunctionDebugContext::FunctionWithoutDebugInfo;
                     }
 
@@ -1302,7 +1302,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
         ast_map::NodeTraitItem(ref trait_method) => {
             match **trait_method {
                 ast::ProvidedMethod(ref method) => {
-                    if contains_nodebug_attribute(method.attrs.as_slice()) {
+                    if contains_nodebug_attribute(&method.attrs) {
                         return FunctionDebugContext::FunctionWithoutDebugInfo;
                     }
 
@@ -1350,7 +1350,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
 
     // Get_template_parameters() will append a `<...>` clause to the function
     // name if necessary.
-    let mut function_name = String::from_str(token::get_ident(ident).get());
+    let mut function_name = String::from_str(&token::get_ident(ident));
     let template_parameters = get_template_parameters(cx,
                                                       generics,
                                                       param_substs,
@@ -1399,7 +1399,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
     };
 
     let scope_map = create_scope_map(cx,
-                                     fn_decl.inputs.as_slice(),
+                                     &fn_decl.inputs,
                                      &*top_level_block,
                                      fn_metadata,
                                      fn_ast_id);
@@ -1499,7 +1499,7 @@ fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                 let ident = special_idents::type_self;
 
                 let ident = token::get_ident(ident);
-                let name = CString::from_slice(ident.get().as_bytes());
+                let name = CString::from_slice(ident.as_bytes());
                 let param_metadata = unsafe {
                     llvm::LLVMDIBuilderCreateTemplateTypeParameter(
                         DIB(cx),
@@ -1533,7 +1533,7 @@ fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
             if cx.sess().opts.debuginfo == FullDebugInfo {
                 let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP);
                 let ident = token::get_ident(ident);
-                let name = CString::from_slice(ident.get().as_bytes());
+                let name = CString::from_slice(ident.as_bytes());
                 let param_metadata = unsafe {
                     llvm::LLVMDIBuilderCreateTemplateTypeParameter(
                         DIB(cx),
@@ -1656,7 +1656,7 @@ fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
         CapturedVariable => (0, DW_TAG_auto_variable)
     };
 
-    let name = CString::from_slice(name.get().as_bytes());
+    let name = CString::from_slice(name.as_bytes());
     match (variable_access, [].as_slice()) {
         (DirectVariable { alloca }, address_operations) |
         (IndirectVariable {alloca, address_operations}, _) => {
@@ -1993,7 +1993,7 @@ fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
             let name = if field.name == special_idents::unnamed_field.name {
                 "".to_string()
             } else {
-                token::get_name(field.name).get().to_string()
+                token::get_name(field.name).to_string()
             };
 
             let offset = if self.is_simd {
@@ -2223,7 +2223,7 @@ fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
                 // MemberDescription of the struct's single field.
                 let sole_struct_member_description = MemberDescription {
                     name: match non_null_variant.arg_names {
-                        Some(ref names) => token::get_ident(names[0]).get().to_string(),
+                        Some(ref names) => token::get_ident(names[0]).to_string(),
                         None => "".to_string()
                     },
                     llvm_type: non_null_llvm_type,
@@ -2237,13 +2237,13 @@ fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
                                                       .get_unique_type_id_of_enum_variant(
                                                           cx,
                                                           self.enum_type,
-                                                          non_null_variant_name.get());
+                                                          &non_null_variant_name);
 
                 // Now we can create the metadata of the artificial struct
                 let artificial_struct_metadata =
                     composite_type_metadata(cx,
                                             artificial_struct_llvm_type,
-                                            non_null_variant_name.get(),
+                                            &non_null_variant_name,
                                             unique_type_id,
                                             &[sole_struct_member_description],
                                             self.containing_scope,
@@ -2373,7 +2373,7 @@ fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
     // Could do some consistency checks here: size, align, field count, discr type
 
     let variant_name = token::get_name(variant_info.name);
-    let variant_name = variant_name.get();
+    let variant_name = &variant_name;
     let unique_type_id = debug_context(cx).type_map
                                           .borrow_mut()
                                           .get_unique_type_id_of_enum_variant(
@@ -2392,7 +2392,7 @@ fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
         Some(ref names) => {
             names.iter()
                  .map(|ident| {
-                     token::get_ident(*ident).get().to_string()
+                     token::get_ident(*ident).to_string()
                  }).collect()
         }
         None => variant_info.args.iter().map(|_| "".to_string()).collect()
@@ -2443,7 +2443,7 @@ fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
         .iter()
         .map(|v| {
             let token = token::get_name(v.name);
-            let name = CString::from_slice(token.get().as_bytes());
+            let name = CString::from_slice(token.as_bytes());
             unsafe {
                 llvm::LLVMDIBuilderCreateEnumerator(
                     DIB(cx),
@@ -2453,7 +2453,7 @@ fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
         })
         .collect();
 
-    let discriminant_type_metadata = |&: inttype| {
+    let discriminant_type_metadata = |inttype| {
         // We can reuse the type of the discriminant for all monomorphized
         // instances of an enum because it doesn't depend on any type parameters.
         // The def_id, uniquely identifying the enum's polytype acts as key in
@@ -2473,7 +2473,7 @@ fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                                   codemap::DUMMY_SP);
                 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
 
-                let name = CString::from_slice(discriminant_name.get().as_bytes());
+                let name = CString::from_slice(discriminant_name.as_bytes());
                 let discriminant_type_metadata = unsafe {
                     llvm::LLVMDIBuilderCreateEnumerationType(
                         DIB(cx),
@@ -2483,7 +2483,7 @@ fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                         UNKNOWN_LINE_NUMBER,
                         bytes_to_bits(discriminant_size),
                         bytes_to_bits(discriminant_align),
-                        create_DIArray(DIB(cx), enumerators_metadata.as_slice()),
+                        create_DIArray(DIB(cx), &enumerators_metadata),
                         discriminant_base_type_metadata)
                 };
 
@@ -3126,7 +3126,7 @@ fn contains_nodebug_attribute(attributes: &[ast::Attribute]) -> bool {
     attributes.iter().any(|attr| {
         let meta_item: &ast::MetaItem = &*attr.node.value;
         match meta_item.node {
-            ast::MetaWord(ref value) => value.get() == "no_debug",
+            ast::MetaWord(ref value) => &value[] == "no_debug",
             _ => false
         }
     })
@@ -3764,7 +3764,7 @@ fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
 
             match optional_length {
                 Some(len) => {
-                    output.push_str(format!("; {}", len).as_slice());
+                    output.push_str(&format!("; {}", len));
                 }
                 None => { /* nothing to do */ }
             };
@@ -3847,7 +3847,7 @@ fn push_item_name(cx: &CrateContext,
                 let mut path_element_count = 0;
                 for path_element in path {
                     let name = token::get_name(path_element.name());
-                    output.push_str(name.get());
+                    output.push_str(&name);
                     output.push_str("::");
                     path_element_count += 1;
                 }
@@ -3862,7 +3862,7 @@ fn push_item_name(cx: &CrateContext,
                 let name = token::get_name(path.last()
                                                .expect("debuginfo: Empty item path?")
                                                .name());
-                output.push_str(name.get());
+                output.push_str(&name);
             }
         });
     }
@@ -3912,8 +3912,8 @@ fn fill_nested(node: &NamespaceTreeNode, output: &mut String) {
                 None => {}
             }
             let string = token::get_name(node.name);
-            output.push_str(&format!("{}", string.get().len())[]);
-            output.push_str(string.get());
+            output.push_str(&format!("{}", string.len())[]);
+            output.push_str(&string);
         }
 
         let mut name = String::from_str("_ZN");
@@ -3970,7 +3970,7 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc<NamespaceTree
                     };
                     let namespace_name = token::get_name(name);
                     let namespace_name = CString::from_slice(namespace_name
-                                                                .get().as_bytes());
+                                                                .as_bytes());
                     let scope = unsafe {
                         llvm::LLVMDIBuilderCreateNameSpace(
                             DIB(cx),
@@ -4070,11 +4070,10 @@ fn get_or_insert_gdb_debug_scripts_section_global(ccx: &CrateContext)
 
 fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool {
     let omit_gdb_pretty_printer_section =
-        attr::contains_name(ccx.tcx()
-                               .map
-                               .krate()
-                               .attrs
-                               .as_slice(),
+        attr::contains_name(&ccx.tcx()
+                                .map
+                                .krate()
+                                .attrs,
                             "omit_gdb_pretty_printer_section");
 
     !omit_gdb_pretty_printer_section &&
index 44eb5b190e1a65666aafad1f46abd1cb44ac9793..9ea7a276d97c657453dcd8b0e9a19107c26db480 100644 (file)
@@ -350,7 +350,7 @@ fn unsize_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
         debug!("dest_ty={}", unsized_ty.repr(bcx.tcx()));
         // Closures for extracting and manipulating the data and payload parts of
         // the fat pointer.
-        let info = |bcx, _val| unsized_info(bcx,
+        let info = |bcx, _val| unsized_info(bcx,
                                               k,
                                               expr.id,
                                               datum_ty,
@@ -382,8 +382,8 @@ fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                                -> DatumBlock<'blk, 'tcx, Expr> {
         let tcx = bcx.tcx();
         let dest_ty = ty::close_type(tcx, datum.ty);
-        let base = |bcx, val| Load(bcx, get_dataptr(bcx, val));
-        let len = |bcx, val| Load(bcx, get_len(bcx, val));
+        let base = |bcx, val| Load(bcx, get_dataptr(bcx, val));
+        let len = |bcx, val| Load(bcx, get_len(bcx, val));
         into_fat_ptr(bcx, expr, datum, dest_ty, base, len)
     }
 
@@ -586,7 +586,7 @@ fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             let contents_ty = expr_ty(bcx, &**contents);
             match box_ty.sty {
                 ty::ty_uniq(..) => {
-                    trans_uniq_expr(bcx, box_ty, &**contents, contents_ty)
+                    trans_uniq_expr(bcx, expr, box_ty, &**contents, contents_ty)
                 }
                 _ => bcx.sess().span_bug(expr.span,
                                          "expected unique box")
@@ -696,6 +696,8 @@ fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
     let ccx = bcx.ccx();
     let mut bcx = bcx;
 
+    let index_expr_debug_loc = index_expr.debug_loc();
+
     // Check for overloaded index.
     let method_ty = ccx.tcx()
                        .method_map
@@ -778,16 +780,20 @@ fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             debug!("trans_index: base {}", bcx.val_to_string(base));
             debug!("trans_index: len {}", bcx.val_to_string(len));
 
-            let bounds_check = ICmp(bcx, llvm::IntUGE, ix_val, len);
+            let bounds_check = ICmp(bcx,
+                                    llvm::IntUGE,
+                                    ix_val,
+                                    len,
+                                    index_expr_debug_loc);
             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
             let expected = Call(bcx,
                                 expect,
                                 &[bounds_check, C_bool(ccx, false)],
                                 None,
-                                index_expr.debug_loc());
+                                index_expr_debug_loc);
             bcx = with_cond(bcx, expected, |bcx| {
                 controlflow::trans_fail_bounds_check(bcx,
-                                                     index_expr.span,
+                                                     expr_info(index_expr),
                                                      ix_val,
                                                      len)
             });
@@ -1056,7 +1062,7 @@ fn make_field(field_name: &str, expr: P<ast::Expr>) -> ast::Field {
             if let Some(did) = did {
                 let substs = Substs::new_type(ty_params, vec![]);
                 trans_struct(bcx,
-                             fields.as_slice(),
+                             &fields,
                              None,
                              expr.span,
                              expr.id,
@@ -1398,7 +1404,7 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
         trans_adt(bcx,
                   ty,
                   discr,
-                  numbered_fields.as_slice(),
+                  &numbered_fields,
                   optbase,
                   dest,
                   DebugLoc::At(expr_id, expr_span))
@@ -1574,7 +1580,7 @@ fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
         }
         ast::UnUniq => {
-            trans_uniq_expr(bcx, un_ty, sub_expr, expr_ty(bcx, sub_expr))
+            trans_uniq_expr(bcx, expr, un_ty, sub_expr, expr_ty(bcx, sub_expr))
         }
         ast::UnDeref => {
             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
@@ -1584,6 +1590,7 @@ fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
 }
 
 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
+                               box_expr: &ast::Expr,
                                box_ty: Ty<'tcx>,
                                contents: &ast::Expr,
                                contents_ty: Ty<'tcx>)
@@ -1595,7 +1602,12 @@ fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
     let size = llsize_of(bcx.ccx(), llty);
     let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
     let llty_ptr = llty.ptr_to();
-    let Result { bcx, val } = malloc_raw_dyn(bcx, llty_ptr, box_ty, size, align);
+    let Result { bcx, val } = malloc_raw_dyn(bcx,
+                                             llty_ptr,
+                                             box_ty,
+                                             size,
+                                             align,
+                                             box_expr.debug_loc());
     // Unique boxes do not allocate for zero-size types. The standard library
     // may assume that `free` is never called on the pointer returned for
     // `Box<ZeroSizeType>`.
@@ -1697,8 +1709,12 @@ fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             FDiv(bcx, lhs, rhs, binop_debug_loc)
         } else {
             // Only zero-check integers; fp /0 is NaN
-            bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
-                                                  op, lhs, rhs, rhs_t);
+            bcx = base::fail_if_zero_or_overflows(bcx,
+                                                  expr_info(binop_expr),
+                                                  op,
+                                                  lhs,
+                                                  rhs,
+                                                  rhs_t);
             if is_signed {
                 SDiv(bcx, lhs, rhs, binop_debug_loc)
             } else {
@@ -1711,7 +1727,8 @@ fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             FRem(bcx, lhs, rhs, binop_debug_loc)
         } else {
             // Only zero-check integers; fp %0 is NaN
-            bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
+            bcx = base::fail_if_zero_or_overflows(bcx,
+                                                  expr_info(binop_expr),
                                                   op, lhs, rhs, rhs_t);
             if is_signed {
                 SRem(bcx, lhs, rhs, binop_debug_loc)
@@ -1733,9 +1750,21 @@ fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
       }
       ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
         if ty::type_is_scalar(rhs_t) {
-            unpack_result!(bcx, base::compare_scalar_types(bcx, lhs, rhs, rhs_t, op.node))
+            unpack_result!(bcx,
+                           base::compare_scalar_types(bcx,
+                                                      lhs,
+                                                      rhs,
+                                                      rhs_t,
+                                                      op.node,
+                                                      binop_debug_loc))
         } else if is_simd {
-            base::compare_simd_types(bcx, lhs, rhs, intype, ty::simd_size(tcx, lhs_t), op)
+            base::compare_simd_types(bcx,
+                                     lhs,
+                                     rhs,
+                                     intype,
+                                     ty::simd_size(tcx, lhs_t),
+                                     op.node,
+                                     binop_debug_loc)
         } else {
             bcx.tcx().sess.span_bug(binop_expr.span, "comparison operator unsupported for type")
         }
@@ -1845,7 +1874,7 @@ fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                                    -> Result<'blk, 'tcx> {
     let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
     callee::trans_call_inner(bcx,
-                             Some(expr_info(expr)),
+                             expr.debug_loc(),
                              monomorphize_type(bcx, method_ty),
                              |bcx, arg_cleanup_scope| {
                                 meth::trans_method_callee(bcx,
@@ -1872,7 +1901,7 @@ fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
     all_args.extend(args.iter().map(|e| &**e));
     unpack_result!(bcx,
                    callee::trans_call_inner(bcx,
-                                            Some(expr_info(expr)),
+                                            expr.debug_loc(),
                                             monomorphize_type(bcx,
                                                               method_type),
                                             |bcx, arg_cleanup_scope| {
index 00bb3036546763787988d23ea4e5559e939d4bf0..5f25a3c7a9210171d73d051ed5a36a86f86ce65b 100644 (file)
@@ -18,6 +18,7 @@
 use trans::build::*;
 use trans::cabi;
 use trans::common::*;
+use trans::debuginfo::DebugLoc;
 use trans::machine;
 use trans::monomorphize;
 use trans::type_::Type;
@@ -118,7 +119,7 @@ pub fn register_static(ccx: &CrateContext,
         // static and call it a day. Some linkages (like weak) will make it such
         // that the static actually has a null value.
         Some(name) => {
-            let linkage = match llvm_linkage_by_name(name.get()) {
+            let linkage = match llvm_linkage_by_name(&name) {
                 Some(linkage) => linkage,
                 None => {
                     ccx.sess().span_fatal(foreign_item.span,
@@ -134,7 +135,7 @@ pub fn register_static(ccx: &CrateContext,
             };
             unsafe {
                 // Declare a symbol `foo` with the desired linkage.
-                let buf = CString::from_slice(ident.get().as_bytes());
+                let buf = CString::from_slice(ident.as_bytes());
                 let g1 = llvm::LLVMAddGlobal(ccx.llmod(), llty2.to_ref(),
                                              buf.as_ptr());
                 llvm::SetLinkage(g1, linkage);
@@ -146,7 +147,7 @@ pub fn register_static(ccx: &CrateContext,
                 // `extern_with_linkage_foo` will instead be initialized to
                 // zero.
                 let mut real_name = "_rust_extern_with_linkage_".to_string();
-                real_name.push_str(ident.get());
+                real_name.push_str(&ident);
                 let real_name = CString::from_vec(real_name.into_bytes());
                 let g2 = llvm::LLVMAddGlobal(ccx.llmod(), llty.to_ref(),
                                              real_name.as_ptr());
@@ -157,7 +158,7 @@ pub fn register_static(ccx: &CrateContext,
         }
         None => unsafe {
             // Generate an external declaration.
-            let buf = CString::from_slice(ident.get().as_bytes());
+            let buf = CString::from_slice(ident.as_bytes());
             llvm::LLVMAddGlobal(ccx.llmod(), llty.to_ref(), buf.as_ptr())
         }
     }
@@ -218,7 +219,8 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                                      llfn: ValueRef,
                                      llretptr: ValueRef,
                                      llargs_rust: &[ValueRef],
-                                     passed_arg_tys: Vec<Ty<'tcx>>)
+                                     passed_arg_tys: Vec<Ty<'tcx>>,
+                                     call_debug_loc: DebugLoc)
                                      -> Block<'blk, 'tcx>
 {
     let ccx = bcx.ccx();
@@ -370,7 +372,8 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                                         llfn,
                                         &llargs_foreign[],
                                         cc,
-                                        Some(attrs));
+                                        Some(attrs),
+                                        call_debug_loc);
 
     // If the function we just called does not use an outpointer,
     // store the result into the rust outpointer. Cast the outpointer
@@ -431,7 +434,7 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
 // ABIs are handled at all correctly.
 fn gate_simd_ffi(tcx: &ty::ctxt, decl: &ast::FnDecl, ty: &ty::BareFnTy) {
     if !tcx.sess.features.borrow().simd_ffi {
-        let check = |&: ast_ty: &ast::Ty, ty: ty::Ty| {
+        let check = |ast_ty: &ast::Ty, ty: ty::Ty| {
             if ty::type_is_simd(tcx, ty) {
                 tcx.sess.span_err(ast_ty.span,
                               &format!("use of SIMD type `{}` in FFI is highly experimental and \
@@ -468,7 +471,7 @@ pub fn trans_foreign_mod(ccx: &CrateContext, foreign_mod: &ast::ForeignMod) {
                     }
 
                     register_foreign_item_fn(ccx, abi, ty,
-                                             &lname.get()[]);
+                                             &lname);
                     // Unlike for other items, we shouldn't call
                     // `base::update_linkage` here.  Foreign items have
                     // special linkage requirements, which are handled
@@ -478,7 +481,7 @@ pub fn trans_foreign_mod(ccx: &CrateContext, foreign_mod: &ast::ForeignMod) {
         }
 
         ccx.item_symbols().borrow_mut().insert(foreign_item.id,
-                                             lname.get().to_string());
+                                             lname.to_string());
     }
 }
 
@@ -649,7 +652,7 @@ unsafe fn build_wrap_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
         // Array for the arguments we will pass to the rust function.
         let mut llrust_args = Vec::new();
         let mut next_foreign_arg_counter: c_uint = 0;
-        let mut next_foreign_arg = |&mut : pad: bool| -> c_uint {
+        let mut next_foreign_arg = |pad: bool| -> c_uint {
             next_foreign_arg_counter += if pad {
                 2
             } else {
@@ -788,7 +791,7 @@ unsafe fn build_wrap_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
         debug!("calling llrustfn = {}, t = {}",
                ccx.tn().val_to_string(llrustfn), t.repr(ccx.tcx()));
         let attributes = base::get_fn_llvm_attributes(ccx, t);
-        let llrust_ret_val = builder.call(llrustfn, llrust_args.as_slice(), Some(attributes));
+        let llrust_ret_val = builder.call(llrustfn, &llrust_args, Some(attributes));
 
         // Get the return value where the foreign fn expects it.
         let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast {
@@ -898,7 +901,7 @@ fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
         _ => ccx.sess().bug("foreign_types_for_fn_ty called on non-function type")
     };
     let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);
-    let llsig = foreign_signature(ccx, &fn_sig, fn_sig.inputs.as_slice());
+    let llsig = foreign_signature(ccx, &fn_sig, &fn_sig.inputs);
     let fn_ty = cabi::compute_abi_info(ccx,
                                        &llsig.llarg_tys[],
                                        llsig.llret_ty,
@@ -911,7 +914,7 @@ fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
            ty.repr(ccx.tcx()),
            ccx.tn().types_to_str(&llsig.llarg_tys[]),
            ccx.tn().type_to_string(llsig.llret_ty),
-           ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>().as_slice()),
+           ccx.tn().types_to_str(&fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>()),
            ccx.tn().type_to_string(fn_ty.ret_ty.ty),
            llsig.ret_def);
 
@@ -959,7 +962,7 @@ fn lltype_for_fn_from_foreign_types(ccx: &CrateContext, tys: &ForeignTypes) -> T
     }
 
     if tys.fn_sig.variadic {
-        Type::variadic_func(llargument_tys.as_slice(), &llreturn_ty)
+        Type::variadic_func(&llargument_tys, &llreturn_ty)
     } else {
         Type::func(&llargument_tys[], &llreturn_ty)
     }
index 5d26daab5cd8739f19f9d6d6a1e285ddb015fdfd..8cf9a51b3bfd9ec6f74c7303fd2c3700e681ad9c 100644 (file)
 use syntax::ast;
 use syntax::parse::token;
 
-pub fn trans_exchange_free_dyn<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef,
-                                           size: ValueRef, align: ValueRef)
+pub fn trans_exchange_free_dyn<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
+                                           v: ValueRef,
+                                           size: ValueRef,
+                                           align: ValueRef,
+                                           debug_loc: DebugLoc)
                                            -> Block<'blk, 'tcx> {
     let _icx = push_ctxt("trans_exchange_free");
     let ccx = cx.ccx();
     callee::trans_lang_call(cx,
         langcall(cx, None, "", ExchangeFreeFnLangItem),
         &[PointerCast(cx, v, Type::i8p(ccx)), size, align],
-        Some(expr::Ignore)).bcx
+        Some(expr::Ignore),
+        debug_loc).bcx
 }
 
-pub fn trans_exchange_free<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef,
-                                       size: u64, align: u32) -> Block<'blk, 'tcx> {
-    trans_exchange_free_dyn(cx, v, C_uint(cx.ccx(), size),
-                                   C_uint(cx.ccx(), align))
+pub fn trans_exchange_free<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
+                                       v: ValueRef,
+                                       size: u64,
+                                       align: u32,
+                                       debug_loc: DebugLoc)
+                                       -> Block<'blk, 'tcx> {
+    trans_exchange_free_dyn(cx,
+                            v,
+                            C_uint(cx.ccx(), size),
+                            C_uint(cx.ccx(), align),
+                            debug_loc)
 }
 
-pub fn trans_exchange_free_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef,
-                                          content_ty: Ty<'tcx>) -> Block<'blk, 'tcx> {
+pub fn trans_exchange_free_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
+                                          ptr: ValueRef,
+                                          content_ty: Ty<'tcx>,
+                                          debug_loc: DebugLoc)
+                                          -> Block<'blk, 'tcx> {
     assert!(type_is_sized(bcx.ccx().tcx(), content_ty));
     let sizing_type = sizing_type_of(bcx.ccx(), content_ty);
     let content_size = llsize_of_alloc(bcx.ccx(), sizing_type);
@@ -71,7 +85,7 @@ pub fn trans_exchange_free_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef,
     // `Box<ZeroSizeType>` does not allocate.
     if content_size != 0 {
         let content_align = align_of(bcx.ccx(), content_ty);
-        trans_exchange_free(bcx, ptr, content_size, content_align)
+        trans_exchange_free(bcx, ptr, content_size, content_align, debug_loc)
     } else {
         bcx
     }
@@ -328,7 +342,11 @@ fn size_and_align_of_dst<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, info:
             // Return the sum of sizes and max of aligns.
             let size = Add(bcx, sized_size, unsized_size, DebugLoc::None);
             let align = Select(bcx,
-                               ICmp(bcx, llvm::IntULT, sized_align, unsized_align),
+                               ICmp(bcx,
+                                    llvm::IntULT,
+                                    sized_align,
+                                    unsized_align,
+                                    DebugLoc::None),
                                sized_align,
                                unsized_align);
             (size, align)
@@ -394,7 +412,7 @@ fn make_drop_glue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v0: ValueRef, t: Ty<'tcx>)
                         let info = GEPi(bcx, v0, &[0, abi::FAT_PTR_EXTRA]);
                         let info = Load(bcx, info);
                         let (llsize, llalign) = size_and_align_of_dst(bcx, content_ty, info);
-                        trans_exchange_free_dyn(bcx, llbox, llsize, llalign)
+                        trans_exchange_free_dyn(bcx, llbox, llsize, llalign, DebugLoc::None)
                     })
                 }
                 _ => {
@@ -404,7 +422,7 @@ fn make_drop_glue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v0: ValueRef, t: Ty<'tcx>)
                     let not_null = IsNotNull(bcx, llbox);
                     with_cond(bcx, not_null, |bcx| {
                         let bcx = drop_ty(bcx, llbox, content_ty, DebugLoc::None);
-                        trans_exchange_free_ty(bcx, llbox, content_ty)
+                        trans_exchange_free_ty(bcx, llbox, content_ty, DebugLoc::None)
                     })
                 }
             }
index 6228043eeb1a9b307bf50dfa4e57f33ed0189e28..5687247561e9cfe13f6e1b4bfb47031e7b6c2aec 100644 (file)
@@ -36,7 +36,7 @@
 use util::ppaux::{Repr, ty_to_string};
 
 pub fn get_simple_intrinsic(ccx: &CrateContext, item: &ast::ForeignItem) -> Option<ValueRef> {
-    let name = match token::get_ident(item.ident).get() {
+    let name = match &token::get_ident(item.ident)[] {
         "sqrtf32" => "llvm.sqrt.f32",
         "sqrtf64" => "llvm.sqrt.f64",
         "powif32" => "llvm.powi.f32",
@@ -118,25 +118,25 @@ pub fn check_intrinsics(ccx: &CrateContext) {
             if transmute_restriction.original_from != transmute_restriction.substituted_from {
                 ccx.sess().span_err(
                     transmute_restriction.span,
-                    format!("transmute called on types with potentially different sizes: \
-                             {} (could be {} bit{}) to {} (could be {} bit{})",
-                            ty_to_string(ccx.tcx(), transmute_restriction.original_from),
-                            from_type_size as uint,
-                            if from_type_size == 1 {""} else {"s"},
-                            ty_to_string(ccx.tcx(), transmute_restriction.original_to),
-                            to_type_size as uint,
-                            if to_type_size == 1 {""} else {"s"}).as_slice());
+                    &format!("transmute called on types with potentially different sizes: \
+                              {} (could be {} bit{}) to {} (could be {} bit{})",
+                             ty_to_string(ccx.tcx(), transmute_restriction.original_from),
+                             from_type_size as uint,
+                             if from_type_size == 1 {""} else {"s"},
+                             ty_to_string(ccx.tcx(), transmute_restriction.original_to),
+                             to_type_size as uint,
+                             if to_type_size == 1 {""} else {"s"}));
             } else {
                 ccx.sess().span_err(
                     transmute_restriction.span,
-                    format!("transmute called on types with different sizes: \
-                             {} ({} bit{}) to {} ({} bit{})",
-                            ty_to_string(ccx.tcx(), transmute_restriction.original_from),
-                            from_type_size as uint,
-                            if from_type_size == 1 {""} else {"s"},
-                            ty_to_string(ccx.tcx(), transmute_restriction.original_to),
-                            to_type_size as uint,
-                            if to_type_size == 1 {""} else {"s"}).as_slice());
+                    &format!("transmute called on types with different sizes: \
+                              {} ({} bit{}) to {} ({} bit{})",
+                             ty_to_string(ccx.tcx(), transmute_restriction.original_from),
+                             from_type_size as uint,
+                             if from_type_size == 1 {""} else {"s"},
+                             ty_to_string(ccx.tcx(), transmute_restriction.original_to),
+                             to_type_size as uint,
+                             if to_type_size == 1 {""} else {"s"}));
             }
         }
     }
@@ -166,7 +166,7 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
     let name = token::get_ident(foreign_item.ident);
 
     // For `transmute` we can just trans the input expr directly into dest
-    if name.get() == "transmute" {
+    if &name[] == "transmute" {
         let llret_ty = type_of::type_of(ccx, ret_ty.unwrap());
         match args {
             callee::ArgExprs(arg_exprs) => {
@@ -183,7 +183,7 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
                 // This should be caught by the intrinsicck pass
                 assert_eq!(in_type_size, out_type_size);
 
-                let nonpointer_nonaggregate = |&: llkind: TypeKind| -> bool {
+                let nonpointer_nonaggregate = |llkind: TypeKind| -> bool {
                     use llvm::TypeKind::*;
                     match llkind {
                         Half | Float | Double | X86_FP80 | FP128 |
@@ -274,13 +274,13 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
     let call_debug_location = DebugLoc::At(call_info.id, call_info.span);
 
     // These are the only intrinsic functions that diverge.
-    if name.get() == "abort" {
+    if &name[] == "abort" {
         let llfn = ccx.get_intrinsic(&("llvm.trap"));
         Call(bcx, llfn, &[], None, call_debug_location);
         fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope);
         Unreachable(bcx);
         return Result::new(bcx, C_undef(Type::nil(ccx).ptr_to()));
-    } else if name.get() == "unreachable" {
+    } else if &name[] == "unreachable" {
         fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope);
         Unreachable(bcx);
         return Result::new(bcx, C_nil(ccx));
@@ -307,9 +307,9 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
     };
 
     let simple = get_simple_intrinsic(ccx, &*foreign_item);
-    let llval = match (simple, name.get()) {
+    let llval = match (simple, &name[]) {
         (Some(llfn), _) => {
-            Call(bcx, llfn, llargs.as_slice(), None, call_debug_location)
+            Call(bcx, llfn, &llargs, None, call_debug_location)
         }
         (_, "breakpoint") => {
             let llfn = ccx.get_intrinsic(&("llvm.debugtrap"));
@@ -365,7 +365,7 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
         (_, "init") => {
             let tp_ty = *substs.types.get(FnSpace, 0);
             if !return_type_is_void(ccx, tp_ty) {
-                // Just zero out the stack slot. (See comment on base::memzero for explaination)
+                // Just zero out the stack slot. (See comment on base::memzero for explanation)
                 zero_mem(bcx, llresult, tp_ty);
             }
             C_nil(ccx)
index f522024c2e7e910ec782cb5ad4fbd0233fbb0adb..5161382a927ac3c5d1668dab2c42f15b3c2c6202 100644 (file)
@@ -567,8 +567,8 @@ pub fn trans_object_shim<'a, 'tcx>(
                 data.principal_trait_ref_with_self_ty(tcx, object_ty)
             }
             _ => {
-                tcx.sess.bug(format!("trans_object_shim() called on non-object: {}",
-                                     object_ty.repr(tcx)).as_slice());
+                tcx.sess.bug(&format!("trans_object_shim() called on non-object: {}",
+                                      object_ty.repr(tcx)));
             }
         };
 
@@ -595,7 +595,7 @@ pub fn trans_object_shim<'a, 'tcx>(
     let function_name =
         link::mangle_internal_name_by_type_and_seq(ccx, method_bare_fn_ty, "object_shim");
     let llfn =
-        decl_internal_rust_fn(ccx, method_bare_fn_ty, function_name.as_slice());
+        decl_internal_rust_fn(ccx, method_bare_fn_ty, &function_name);
 
     let sig = ty::erase_late_bound_regions(ccx.tcx(), &fty.sig);
 
@@ -624,11 +624,11 @@ pub fn trans_object_shim<'a, 'tcx>(
             RustCall => {
                 // unpack the tuple to extract the input type arguments:
                 match sig.inputs[1].sty {
-                    ty::ty_tup(ref tys) => tys.as_slice(),
+                    ty::ty_tup(ref tys) => &**tys,
                     _ => {
                         bcx.sess().bug(
-                            format!("rust-call expects a tuple not {}",
-                                    sig.inputs[1].repr(tcx)).as_slice());
+                            &format!("rust-call expects a tuple not {}",
+                                     sig.inputs[1].repr(tcx)));
                     }
                 }
             }
@@ -667,13 +667,13 @@ pub fn trans_object_shim<'a, 'tcx>(
            method_offset_in_vtable);
 
     bcx = trans_call_inner(bcx,
-                           None,
+                           DebugLoc::None,
                            method_bare_fn_ty,
                            |bcx, _| trans_trait_callee_from_llval(bcx,
                                                                   method_bare_fn_ty,
                                                                   method_offset_in_vtable,
                                                                   llobject),
-                           ArgVals(llargs.as_slice()),
+                           ArgVals(&llargs),
                            dest).bcx;
 
     finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
@@ -744,8 +744,8 @@ pub fn get_vtable<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                 // an object type; this cannot happen because we
                 // cannot cast an unsized type into a trait object
                 bcx.sess().bug(
-                    format!("cannot get vtable for an object type: {}",
-                            data.repr(bcx.tcx())).as_slice());
+                    &format!("cannot get vtable for an object type: {}",
+                             data.repr(bcx.tcx())));
             }
             traits::VtableParam(..) => {
                 bcx.sess().bug(
index b3d388b0f0236b3e8f257db91d197b44fceba0bd..5796e72a61018e126d43f7cc6c32a6c8ad1313c3 100644 (file)
@@ -139,7 +139,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
 
     // This shouldn't need to option dance.
     let mut hash_id = Some(hash_id);
-    let mut mk_lldecl = |&mut : abi: abi::Abi| {
+    let mut mk_lldecl = |abi: abi::Abi| {
         let lldecl = if abi != abi::Rust {
             foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, &s[])
         } else {
@@ -149,7 +149,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
         ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl);
         lldecl
     };
-    let setup_lldecl = |&: lldecl, attrs: &[ast::Attribute]| {
+    let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| {
         base::update_linkage(ccx, lldecl, None, base::OriginalTranslation);
         set_llvm_fn_attrs(ccx, attrs, lldecl);
 
index 66f603cbe07f2aea9c9d7bad2617e69f5da54e4e..edd4da4711f9c6610c60f9c7839c7b7f4a8efdbf 100644 (file)
@@ -73,11 +73,19 @@ pub fn make_drop_glue_unboxed<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             let unit_size = llsize_of_alloc(ccx, llty);
             if unit_size != 0 {
                 let len = get_len(bcx, vptr);
-                let not_empty = ICmp(bcx, llvm::IntNE, len, C_uint(ccx, 0us));
+                let not_empty = ICmp(bcx,
+                                     llvm::IntNE,
+                                     len,
+                                     C_uint(ccx, 0us),
+                                     DebugLoc::None);
                 with_cond(bcx, not_empty, |bcx| {
                     let llalign = C_uint(ccx, machine::llalign_of_min(ccx, llty));
                     let size = Mul(bcx, C_uint(ccx, unit_size), len, DebugLoc::None);
-                    glue::trans_exchange_free_dyn(bcx, dataptr, size, llalign)
+                    glue::trans_exchange_free_dyn(bcx,
+                                                  dataptr,
+                                                  size,
+                                                  llalign,
+                                                  DebugLoc::None)
                 })
             } else {
                 bcx
@@ -209,7 +217,7 @@ pub fn trans_lit_str<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
     match dest {
         Ignore => bcx,
         SaveIn(lldest) => {
-            let bytes = str_lit.get().len();
+            let bytes = str_lit.len();
             let llbytes = C_uint(bcx.ccx(), bytes);
             let llcstr = C_cstr(bcx.ccx(), str_lit, false);
             let llcstr = consts::ptrcast(llcstr, Type::i8p(bcx.ccx()));
@@ -242,7 +250,7 @@ pub fn write_content<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                     match dest {
                         Ignore => return bcx,
                         SaveIn(lldest) => {
-                            let bytes = s.get().len();
+                            let bytes = s.len();
                             let llbytes = C_uint(bcx.ccx(), bytes);
                             let llcstr = C_cstr(bcx.ccx(), (*s).clone(), false);
                             base::call_memcpy(bcx,
@@ -343,7 +351,7 @@ pub fn elements_required(bcx: Block, content_expr: &ast::Expr) -> uint {
     match content_expr.node {
         ast::ExprLit(ref lit) => {
             match lit.node {
-                ast::LitStr(ref s, _) => s.get().len(),
+                ast::LitStr(ref s, _) => s.len(),
                 _ => {
                     bcx.tcx().sess.span_bug(content_expr.span,
                                             "unexpected evec content")
@@ -439,7 +447,7 @@ pub fn iter_vec_loop<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
     { // i < count
         let lhs = Load(cond_bcx, loop_counter);
         let rhs = count;
-        let cond_val = ICmp(cond_bcx, llvm::IntULT, lhs, rhs);
+        let cond_val = ICmp(cond_bcx, llvm::IntULT, lhs, rhs, DebugLoc::None);
 
         CondBr(cond_bcx, cond_val, body_bcx.llbb, next_bcx.llbb, DebugLoc::None);
     }
@@ -493,7 +501,7 @@ pub fn iter_vec_raw<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
         let data_ptr =
             Phi(header_bcx, val_ty(data_ptr), &[data_ptr], &[bcx.llbb]);
         let not_yet_at_end =
-            ICmp(header_bcx, llvm::IntULT, data_ptr, data_end_ptr);
+            ICmp(header_bcx, llvm::IntULT, data_ptr, data_end_ptr, DebugLoc::None);
         let body_bcx = fcx.new_temp_block("iter_vec_loop_body");
         let next_bcx = fcx.new_temp_block("iter_vec_next");
         CondBr(header_bcx, not_yet_at_end, body_bcx.llbb, next_bcx.llbb, DebugLoc::None);
index 2243982c20d61fcea680e035475493a91c4779a7..9d1c0fadefcd22718ca1dac09debc1fb7cb9e3fc 100644 (file)
@@ -113,7 +113,7 @@ pub fn type_of_rust_fn<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
     let mut atys: Vec<Type> = Vec::new();
 
     // First, munge the inputs, if this has the `rust-call` ABI.
-    let inputs = untuple_arguments_if_necessary(cx, sig.inputs.as_slice(), abi);
+    let inputs = untuple_arguments_if_necessary(cx, &sig.inputs, abi);
 
     // Arg 0: Output pointer.
     // (if the output type is non-immediate)
index b6fd2eb57be27c7b8a953b21faef93363038c665..464522f167b472b6aa46667095e1b1ba999bc547 100644 (file)
@@ -150,7 +150,6 @@ pub fn get_next_use(self) -> Option<Use> {
 }
 
 /// Iterator for the users of a value
-#[allow(missing_copy_implementations)]
 pub struct Users {
     next: Option<Use>
 }
index 8809931cd80c23b23f81096be36772dd5b33d520..0dbb53e09b7d97f32c28bb05c563e8d65503e898 100644 (file)
@@ -272,7 +272,7 @@ pub fn ast_path_substs_for_ty<'tcx>(
         }
     };
 
-    prohibit_projections(this.tcx(), assoc_bindings.as_slice());
+    prohibit_projections(this.tcx(), &assoc_bindings);
 
     create_substs_for_ast_path(this,
                                rscope,
@@ -526,7 +526,7 @@ pub fn instantiate_poly_trait_ref<'tcx>(
 {
     let mut projections = Vec::new();
 
-    // the trait reference introduces a binding level here, so
+    // The trait reference introduces a binding level here, so
     // we need to shift the `rscope`. It'd be nice if we could
     // do away with this rscope stuff and work this knowledge
     // into resolve_lifetimes, as we do with non-omitted
@@ -656,7 +656,7 @@ fn ast_path_to_trait_ref<'a,'tcx>(
 
     match projections {
         None => {
-            prohibit_projections(this.tcx(), assoc_bindings.as_slice());
+            prohibit_projections(this.tcx(), &assoc_bindings);
         }
         Some(ref mut v) => {
             for binding in &assoc_bindings {
@@ -960,7 +960,7 @@ fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
 
         // FIXME(#20300) -- search where clauses, not bounds
         suitable_bounds =
-            traits::transitive_bounds(tcx, ty_param_def.bounds.trait_bounds.as_slice())
+            traits::transitive_bounds(tcx, &ty_param_def.bounds.trait_bounds)
             .filter(|b| trait_defines_associated_type_named(this, b.def_id(), assoc_name))
             .collect();
     }
@@ -1160,12 +1160,11 @@ pub fn ast_ty_to_ty<'tcx>(
                                                    using the syntax `<Type \
                                                    as {}>::{}`",
                                                   path_str,
-                                                  token::get_ident(
+                                                  &token::get_ident(
                                                       path.segments
                                                           .last()
                                                           .unwrap()
-                                                          .identifier)
-                                                  .get());
+                                                          .identifier));
                         this.tcx().types.err
                     }
                     def::DefAssociatedPath(provenance, assoc_ident) => {
@@ -1595,11 +1594,11 @@ pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
     let region_bound = compute_region_bound(this,
                                             rscope,
                                             span,
-                                            region_bounds.as_slice(),
+                                            &region_bounds,
                                             principal_trait_ref,
                                             builtin_bounds);
 
-    ty::sort_bounds_list(projection_bounds.as_mut_slice());
+    ty::sort_bounds_list(&mut projection_bounds);
 
     ty::ExistentialBounds {
         region_bound: region_bound,
index 174a902953476da2db8519a7cca58188dbb3bb2e..1249e0d8ce1e549979cf446f3368a49d1a809e58 100644 (file)
@@ -164,7 +164,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>,
             check_pat_enum(pcx, pat, path, subpats, expected);
         }
         ast::PatStruct(ref path, ref fields, etc) => {
-            check_pat_struct(pcx, pat, path, fields.as_slice(), etc, expected);
+            check_pat_struct(pcx, pat, path, fields, etc, expected);
         }
         ast::PatTup(ref elements) => {
             let element_tys: Vec<_> =
@@ -480,7 +480,7 @@ pub fn check_pat_struct<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, pat: &'tcx ast::Pat,
         .unwrap_or_else(|| Substs::empty());
 
     let struct_fields = ty::struct_fields(tcx, variant_def_id, &item_substs);
-    check_struct_pat_fields(pcx, pat.span, fields, struct_fields.as_slice(),
+    check_struct_pat_fields(pcx, pat.span, fields, &struct_fields,
                             variant_def_id, etc);
 }
 
index 93c6445606eb896ebe2bb0b7025a0bdc6ceadd19..6a9d34d7637b23d57a9be8b71387f5e991dd47b6 100644 (file)
@@ -252,10 +252,10 @@ fn confirm_builtin_call<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
                                                       call_expr.span,
                                                       expected,
                                                       fn_sig.output,
-                                                      fn_sig.inputs.as_slice());
+                                                      &fn_sig.inputs);
     check_argument_types(fcx,
                          call_expr.span,
-                         fn_sig.inputs.as_slice(),
+                         &fn_sig.inputs,
                          &expected_arg_tys[],
                          arg_exprs,
                          AutorefArgs::No,
index dc4d7d466472800a9ddb633e0207c32e5be7c9e4..a5b938c7600c2c5eee6d7042fa9aa030eef5b609 100644 (file)
@@ -159,11 +159,11 @@ pub fn compare_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>,
     // vs 'b).  However, the normal subtyping rules on fn types handle
     // this kind of equivalency just fine.
     //
-    // We now use these subsititions to ensure that all declared bounds are
+    // We now use these substitutions to ensure that all declared bounds are
     // satisfied by the implementation's method.
     //
     // We do this by creating a parameter environment which contains a
-    // substition corresponding to impl_to_skol_substs. We then build
+    // substitution corresponding to impl_to_skol_substs. We then build
     // trait_to_skol_substs and use it to convert the predicates contained
     // in the trait_m.generics to the skolemized form.
     //
index 1cfb019395870fa63ec47d6b6125f52dfc270764..77701af25d39ab0f9aebde4fd8d7c19f77a41936 100644 (file)
@@ -655,9 +655,9 @@ fn upcast(&mut self,
             None => {
                 self.tcx().sess.span_bug(
                     self.span,
-                    format!("cannot upcast `{}` to `{}`",
-                            source_trait_ref.repr(self.tcx()),
-                            target_trait_def_id.repr(self.tcx())).as_slice());
+                    &format!("cannot upcast `{}` to `{}`",
+                             source_trait_ref.repr(self.tcx()),
+                             target_trait_def_id.repr(self.tcx())));
             }
         }
     }
index a988fb4cc6e19015e0b58ec43b737db33bbd6742..ba49ae637b32e6cd9c6de0f2dd3bd8eeb2cd5d1d 100644 (file)
@@ -368,7 +368,7 @@ fn assemble_inherent_candidates_from_param(&mut self,
             })
             .collect();
 
-        self.elaborate_bounds(bounds.as_slice(), |this, poly_trait_ref, m, method_num| {
+        self.elaborate_bounds(&bounds, |this, poly_trait_ref, m, method_num| {
             let trait_ref =
                 this.erase_late_bound_regions(&poly_trait_ref);
 
index c22d2a9bb416fe01a4e5537a29f22efb0dc00128..063300a1d72803778be778f1febfaf6036da028a 100644 (file)
@@ -342,7 +342,7 @@ fn handle_external_def(traits: &mut AllTraitsVec,
             }
         }
         let cstore = &ccx.tcx.sess.cstore;
-        cstore.iter_crate_data(|&mut: cnum, _| {
+        cstore.iter_crate_data(|cnum, _| {
             csearch::each_top_level_item_of_crate(cstore, cnum, |dl, _, _| {
                 handle_external_def(&mut traits, ccx, cstore, dl)
             })
index adf15fbf28a8f040708e9e9aaea3b371558fdd9a..9c0d6f7dae386c48de85dc3c8e9d325661121d6c 100644 (file)
@@ -730,7 +730,7 @@ pub fn check_item<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx ast::Item) {
                 check_impl_items_against_trait(ccx,
                                                it.span,
                                                &*impl_trait_ref,
-                                               impl_items.as_slice());
+                                               impl_items);
               }
               None => { }
           }
@@ -801,12 +801,12 @@ pub fn check_item<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx ast::Item) {
 fn check_trait_on_unimplemented<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
                                generics: &ast::Generics,
                                item: &ast::Item) {
-    if let Some(ref attr) = item.attrs.iter().find(|&: a| {
+    if let Some(ref attr) = item.attrs.iter().find(|a| {
         a.check_name("rustc_on_unimplemented")
     }) {
         if let Some(ref istring) = attr.value_str() {
-            let parser = Parser::new(istring.get());
-            let types = generics.ty_params.as_slice();
+            let parser = Parser::new(&istring);
+            let types = &*generics.ty_params;
             for token in parser {
                 match token {
                     Piece::String(_) => (), // Normal string, no need to check it
@@ -908,9 +908,9 @@ fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
                                 // caught in resolve.
                                 tcx.sess.span_bug(
                                     impl_method.span,
-                                    format!("item `{}` is of a different kind from its trait `{}`",
-                                            token::get_name(impl_item_ty.name()),
-                                            impl_trait_ref.repr(tcx)).as_slice());
+                                    &format!("item `{}` is of a different kind from its trait `{}`",
+                                             token::get_name(impl_item_ty.name()),
+                                             impl_trait_ref.repr(tcx)));
                             }
                         }
                     }
@@ -919,9 +919,9 @@ fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
                         // caught in resolve.
                         tcx.sess.span_bug(
                             impl_method.span,
-                            format!("method `{}` is not a member of trait `{}`",
-                                    token::get_name(impl_item_ty.name()),
-                                    impl_trait_ref.repr(tcx)).as_slice());
+                            &format!("method `{}` is not a member of trait `{}`",
+                                     token::get_name(impl_item_ty.name()),
+                                     impl_trait_ref.repr(tcx)));
                     }
                 }
             }
@@ -944,9 +944,9 @@ fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
                                 // already been caught in resolve.
                                 tcx.sess.span_bug(
                                     typedef.span,
-                                    format!("item `{}` is of a different kind from its trait `{}`",
-                                            token::get_name(typedef_ty.name()),
-                                            impl_trait_ref.repr(tcx)).as_slice());
+                                    &format!("item `{}` is of a different kind from its trait `{}`",
+                                             token::get_name(typedef_ty.name()),
+                                             impl_trait_ref.repr(tcx)));
                             }
                         }
                     }
@@ -955,11 +955,11 @@ fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
                         // caught in resolve.
                         tcx.sess.span_bug(
                             typedef.span,
-                            format!(
+                            &format!(
                                 "associated type `{}` is not a member of \
                                  trait `{}`",
                                 token::get_name(typedef_ty.name()),
-                                impl_trait_ref.repr(tcx)).as_slice());
+                                impl_trait_ref.repr(tcx)));
                     }
                 }
             }
@@ -1715,7 +1715,7 @@ pub fn adjust_expr_ty(&self,
     {
         let raw_ty = self.expr_ty(expr);
         let raw_ty = self.infcx().shallow_resolve(raw_ty);
-        let resolve_ty = |&: ty: Ty<'tcx>| self.infcx().resolve_type_vars_if_possible(&ty);
+        let resolve_ty = |ty: Ty<'tcx>| self.infcx().resolve_type_vars_if_possible(&ty);
         ty::adjust_ty(self.tcx(),
                       expr.span,
                       expr.id,
@@ -3104,7 +3104,7 @@ fn suggest_field_names<'tcx>(id : DefId,
                                  tcx : &ty::ctxt<'tcx>,
                                  skip : Vec<&str>) {
         let ident = token::get_ident(field.node);
-        let name = ident.get();
+        let name = &ident;
         // only find fits with at least one matching letter
         let mut best_dist = name.len();
         let fields = ty::lookup_struct_fields(tcx, id);
@@ -3123,7 +3123,7 @@ fn suggest_field_names<'tcx>(id : DefId,
         }
         if let Some(n) = best {
             tcx.sess.span_help(field.span,
-                format!("did you mean `{}`?", n).as_slice());
+                &format!("did you mean `{}`?", n));
         }
     }
 
@@ -3286,7 +3286,7 @@ fn check_struct_or_variant_fields<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                     let (_, seen) = class_field_map[name];
                     if !seen {
                         missing_fields.push(
-                            format!("`{}`", token::get_name(name).get()))
+                            format!("`{}`", &token::get_name(name)))
                     }
                 }
 
@@ -3734,7 +3734,7 @@ fn check_struct_fields_on_error<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
         }
       }
       ast::ExprMatch(ref discrim, ref arms, match_src) => {
-        _match::check_match(fcx, expr, &**discrim, arms.as_slice(), expected, match_src);
+        _match::check_match(fcx, expr, &**discrim, arms, expected, match_src);
       }
       ast::ExprClosure(capture, ref decl, ref body) => {
           closure::check_expr_closure(fcx, expr, capture, &**decl, &**body, expected);
@@ -5217,14 +5217,14 @@ pub fn check_bounds_are_used<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
 
 pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &ast::ForeignItem) {
     fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
-        let name = token::intern(format!("P{}", n).as_slice());
+        let name = token::intern(&format!("P{}", n));
         ty::mk_param(ccx.tcx, subst::FnSpace, n, name)
     }
 
     let tcx = ccx.tcx;
     let name = token::get_ident(it.ident);
-    let (n_tps, inputs, output) = if name.get().starts_with("atomic_") {
-        let split : Vec<&str> = name.get().split('_').collect();
+    let (n_tps, inputs, output) = if name.starts_with("atomic_") {
+        let split : Vec<&str> = name.split('_').collect();
         assert!(split.len() >= 2, "Atomic intrinsic not correct format");
 
         //We only care about the operation here
@@ -5253,10 +5253,10 @@ fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
             }
         };
         (n_tps, inputs, ty::FnConverging(output))
-    } else if name.get() == "abort" || name.get() == "unreachable" {
+    } else if &name[] == "abort" || &name[] == "unreachable" {
         (0, Vec::new(), ty::FnDiverging)
     } else {
-        let (n_tps, inputs, output) = match name.get() {
+        let (n_tps, inputs, output) = match &name[] {
             "breakpoint" => (0, Vec::new(), ty::mk_nil(tcx)),
             "size_of" |
             "pref_align_of" | "min_align_of" => (1, Vec::new(), ccx.tcx.types.uint),
index 6f66010925ec0b5411d059312947ce6bdb08c573..19287f19d8d504415029c333e02df817610634e0 100644 (file)
@@ -153,31 +153,31 @@ pub fn check_object_safety<'tcx>(tcx: &ty::ctxt<'tcx>,
             ObjectSafetyViolation::Method(method, MethodViolationCode::ByValueSelf) => {
                 tcx.sess.span_note(
                     span,
-                    format!("method `{}` has a receiver type of `Self`, \
-                             which cannot be used with a trait object",
-                            method.name.user_string(tcx)).as_slice());
+                    &format!("method `{}` has a receiver type of `Self`, \
+                              which cannot be used with a trait object",
+                             method.name.user_string(tcx)));
             }
 
             ObjectSafetyViolation::Method(method, MethodViolationCode::StaticMethod) => {
                 tcx.sess.span_note(
                     span,
-                    format!("method `{}` has no receiver",
-                            method.name.user_string(tcx)).as_slice());
+                    &format!("method `{}` has no receiver",
+                             method.name.user_string(tcx)));
             }
 
             ObjectSafetyViolation::Method(method, MethodViolationCode::ReferencesSelf) => {
                 tcx.sess.span_note(
                     span,
-                    format!("method `{}` references the `Self` type \
-                             in its arguments or return type",
-                            method.name.user_string(tcx)).as_slice());
+                    &format!("method `{}` references the `Self` type \
+                              in its arguments or return type",
+                             method.name.user_string(tcx)));
             }
 
             ObjectSafetyViolation::Method(method, MethodViolationCode::Generic) => {
                 tcx.sess.span_note(
                     span,
-                    format!("method `{}` has generic type parameters",
-                            method.name.user_string(tcx)).as_slice());
+                    &format!("method `{}` has generic type parameters",
+                             method.name.user_string(tcx)));
             }
         }
     }
@@ -288,7 +288,7 @@ pub fn select_all_fcx_obligations_and_apply_defaults(fcx: &FnCtxt) {
 pub fn select_all_fcx_obligations_or_error(fcx: &FnCtxt) {
     debug!("select_all_fcx_obligations_or_error");
 
-    // upvar inference should have ensured that all deferrred call
+    // upvar inference should have ensured that all deferred call
     // resolutions are handled by now.
     assert!(fcx.inh.deferred_call_resolutions.borrow().is_empty());
 
index 71b495af444dd240f313e5a53f59ecedd489355c..1079e87a48bf620cac30fa691412f88e05adfe59 100644 (file)
@@ -170,7 +170,7 @@ fn check_type_defn<F>(&mut self, item: &ast::Item, mut lookup_fields: F) where
                 variants.iter().flat_map(|v| v.fields.iter().map(|f| f.ty)).collect();
 
             regionck::regionck_ensure_component_tys_wf(
-                fcx, item.span, field_tys.as_slice());
+                fcx, item.span, &field_tys);
         });
     }
 
@@ -227,7 +227,7 @@ fn check_impl(&mut self,
             // There are special rules that apply to drop.
             if
                 fcx.tcx().lang_items.drop_trait() == Some(trait_ref.def_id) &&
-                !attr::contains_name(item.attrs.as_slice(), "unsafe_destructor")
+                !attr::contains_name(&item.attrs, "unsafe_destructor")
             {
                 match self_ty.sty {
                     ty::ty_struct(def_id, _) |
index f047a36c56095fcc3433b872c2edb9480f1addb7..fca40df7aaa6af71a3a032d8bbbbbaf125d0c6e2 100644 (file)
@@ -405,7 +405,7 @@ fn report_error(&self, e: infer::fixup_err) {
                     let span = self.reason.span(self.tcx);
                     span_err!(self.tcx.sess, span, E0104,
                         "cannot resolve lifetime for captured variable `{}`: {}",
-                        ty::local_var_name_str(self.tcx, upvar_id.var_id).get().to_string(),
+                        ty::local_var_name_str(self.tcx, upvar_id.var_id).to_string(),
                         infer::fixup_err_to_string(e));
                 }
 
index 5b97175ab22fbda3e2f675ba0f96db5b7f50ac15..a571b2793df17906a806f40a12eb4305095fe82e 100644 (file)
@@ -94,9 +94,9 @@ fn visit_item(&mut self, item: &'v ast::Item) {
                                     param_ty.user_string(self.tcx));
                             self.tcx.sess.span_note(
                                 item.span,
-                                format!("for a limited time, you can add \
-                                         `#![feature(old_orphan_check)]` to your crate \
-                                         to disable this rule").as_slice());
+                                &format!("for a limited time, you can add \
+                                          `#![feature(old_orphan_check)]` to your crate \
+                                          to disable this rule"));
                         }
                     }
                 }
index 7dfa5298fb4c78b092d2e438b8b4694193f8ba27..ce26658cf4b9392535ce65ff3ccf20d0327c6727 100644 (file)
@@ -169,9 +169,9 @@ fn get_item_type_scheme(&self, id: ast::DefId) -> ty::TypeScheme<'tcx> {
                 ty_of_foreign_item(self, &*foreign_item, abi)
             }
             x => {
-                self.tcx.sess.bug(format!("unexpected sort of node \
-                                           in get_item_type_scheme(): {:?}",
-                                          x).as_slice());
+                self.tcx.sess.bug(&format!("unexpected sort of node \
+                                            in get_item_type_scheme(): {:?}",
+                                           x));
             }
         }
     }
@@ -562,7 +562,7 @@ fn convert(ccx: &CollectCtxt, it: &ast::Item) {
             write_ty_to_tcx(tcx, it.id, scheme.ty);
             get_enum_variant_types(ccx,
                                    scheme.ty,
-                                   enum_definition.variants.as_slice(),
+                                   &enum_definition.variants,
                                    generics);
         },
         ast::ItemImpl(_, _,
@@ -846,7 +846,7 @@ fn trait_def_of_item<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>,
                        ref generics,
                        ref supertraits,
                        ref items) => {
-            (unsafety, generics, supertraits, items.as_slice())
+            (unsafety, generics, supertraits, items)
         }
         ref s => {
             tcx.sess.span_bug(
@@ -878,7 +878,7 @@ fn trait_def_of_item<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>,
 
     let bounds = compute_bounds(ccx,
                                 self_param_ty.to_ty(ccx.tcx),
-                                bounds.as_slice(),
+                                bounds,
                                 SizedByDefault::No,
                                 it.span);
 
@@ -1136,7 +1136,7 @@ fn predicates_for_associated_types<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>,
 
                 let bounds = compute_bounds(ccx,
                                             assoc_ty,
-                                            assoc_type_def.bounds.as_slice(),
+                                            &*assoc_type_def.bounds,
                                             SizedByDefault::Yes,
                                             assoc_type_def.span);
 
@@ -1448,7 +1448,7 @@ fn conv_param_bounds<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>,
     let astconv::PartitionedBounds { builtin_bounds,
                                      trait_bounds,
                                      region_bounds } =
-        astconv::partition_bounds(ccx.tcx, span, ast_bounds.as_slice());
+        astconv::partition_bounds(ccx.tcx, span, ast_bounds);
 
     let mut projection_bounds = Vec::new();
 
@@ -1701,9 +1701,9 @@ fn enforce_impl_ty_params_are_constrained<'tcx>(tcx: &ty::ctxt<'tcx>,
             if ty::has_attr(tcx, impl_def_id, "old_impl_check") {
                 tcx.sess.span_warn(
                     ty_param.span,
-                    format!("the type parameter `{}` is not constrained by the \
-                             impl trait, self type, or predicates",
-                            param_ty.user_string(tcx)).as_slice());
+                    &format!("the type parameter `{}` is not constrained by the \
+                              impl trait, self type, or predicates",
+                             param_ty.user_string(tcx)));
             } else {
                 span_err!(tcx.sess, ty_param.span, E0207,
                     "the type parameter `{}` is not constrained by the \
@@ -1711,8 +1711,8 @@ impl trait, self type, or predicates",
                             param_ty.user_string(tcx));
                 tcx.sess.span_help(
                     ty_param.span,
-                    format!("you can temporarily opt out of this rule by placing \
-                             the `#[old_impl_check]` attribute on the impl").as_slice());
+                    &format!("you can temporarily opt out of this rule by placing \
+                              the `#[old_impl_check]` attribute on the impl"));
             }
         }
     }
index 680ff2fcda64cd6e6c35eb871e01aa0a7254a8dc..17cf92d39d8f542d332f7fab010e401280c7f3fd 100644 (file)
     E0189, // can only cast a boxed pointer to a boxed object
     E0190, // can only cast a &-pointer to an &-object
     E0191, // value of the associated type must be specified
-    E0192, // negative imples are allowed just fo `Send` and `Sync`
+    E0192, // negative imples are allowed just for `Send` and `Sync`
     E0193, // cannot bound type where clause bounds may only be attached to types
            // involving type parameters
     E0194,
     E0199, // implementing trait is not unsafe
     E0200, // trait requires an `unsafe impl` declaration
     E0201, // duplicate method in trait impl
-    E0202, // associated items are not allowed in inherint impls
+    E0202, // associated items are not allowed in inherent impls
     E0203, // type parameter has more than one relaxed default bound,
            // and only one is supported
     E0204, // trait `Copy` may not be implemented for this type; field
index a07179b31bbd897725af62686a63778b9f63e2eb..ccf392365cea0ee27ea5eadc44d9e3f161b98af9 100644 (file)
@@ -83,7 +83,6 @@
 #![feature(rustc_private)]
 #![feature(slicing_syntax, unsafe_destructor)]
 #![feature(staged_api)]
-#![feature(std_misc)]
 
 #[macro_use] extern crate log;
 #[macro_use] extern crate syntax;
index ddb485d9776d14d244d643494aed017142b0295c..60e969c4f99dd410c23f089fef3f56e9aa07e49a 100644 (file)
@@ -79,7 +79,6 @@ fn anon_regions(&self,
 // A scope in which any omitted region defaults to `default`. This is
 // used after the `->` in function signatures, but also for backwards
 // compatibility with object types. The latter use may go away.
-#[allow(missing_copy_implementations)]
 pub struct SpecificRscope {
     default: ty::Region
 }
index 40197ee2c4988bf3eb0c717340f8a502d52a1864..567a388836f25e52c382b36616accb5d5ebf5918 100644 (file)
 use self::ParamKind::*;
 
 use arena;
-use arena::Arena;
+use arena::TypedArena;
 use middle::resolve_lifetime as rl;
 use middle::subst;
 use middle::subst::{ParamSpace, FnSpace, TypeSpace, SelfSpace, VecPerParamSpace};
 
 pub fn infer_variance(tcx: &ty::ctxt) {
     let krate = tcx.map.krate();
-    let mut arena = arena::Arena::new();
+    let mut arena = arena::TypedArena::new();
     let terms_cx = determine_parameters_to_be_inferred(tcx, &mut arena, krate);
     let constraints_cx = add_constraints_from_crate(terms_cx, krate);
     solve_constraints(constraints_cx);
@@ -254,7 +254,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 
 struct TermsContext<'a, 'tcx: 'a> {
     tcx: &'a ty::ctxt<'tcx>,
-    arena: &'a Arena,
+    arena: &'a TypedArena<VarianceTerm<'a>>,
 
     empty_variances: Rc<ty::ItemVariances>,
 
@@ -282,7 +282,7 @@ struct InferredInfo<'a> {
 }
 
 fn determine_parameters_to_be_inferred<'a, 'tcx>(tcx: &'a ty::ctxt<'tcx>,
-                                                 arena: &'a mut Arena,
+                                                 arena: &'a mut TypedArena<VarianceTerm<'a>>,
                                                  krate: &ast::Crate)
                                                  -> TermsContext<'a, 'tcx> {
     let mut terms_cx = TermsContext {
@@ -312,7 +312,7 @@ fn add_inferred(&mut self,
                     index: uint,
                     param_id: ast::NodeId) {
         let inf_index = InferredIndex(self.inferred_infos.len());
-        let term = self.arena.alloc(|| InferredTerm(inf_index));
+        let term = self.arena.alloc(InferredTerm(inf_index));
         self.inferred_infos.push(InferredInfo { item_id: item_id,
                                                 kind: kind,
                                                 space: space,
@@ -455,10 +455,10 @@ fn add_constraints_from_crate<'a, 'tcx>(terms_cx: TermsContext<'a, 'tcx>,
 
     let unsafe_lang_item = terms_cx.tcx.lang_items.unsafe_type();
 
-    let covariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Covariant));
-    let contravariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Contravariant));
-    let invariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Invariant));
-    let bivariant = terms_cx.arena.alloc(|| ConstantTerm(ty::Bivariant));
+    let covariant = terms_cx.arena.alloc(ConstantTerm(ty::Covariant));
+    let contravariant = terms_cx.arena.alloc(ConstantTerm(ty::Contravariant));
+    let invariant = terms_cx.arena.alloc(ConstantTerm(ty::Invariant));
+    let bivariant = terms_cx.arena.alloc(ConstantTerm(ty::Bivariant));
     let mut constraint_cx = ConstraintContext {
         terms_cx: terms_cx,
 
@@ -597,7 +597,7 @@ fn is_to_be_inferred(&self, param_id: ast::NodeId) -> bool {
         // parameter (by inspecting parent of its binding declaration
         // to see if it is introduced by a type or by a fn/impl).
 
-        let check_result = |&: this:&ConstraintContext| -> bool {
+        let check_result = |this:&ConstraintContext| -> bool {
             let tcx = this.terms_cx.tcx;
             let decl_id = this.find_binding_for_lifetime(param_id);
             // Currently only called on lifetimes; double-checking that.
@@ -719,7 +719,7 @@ fn xform(&mut self,
             }
 
             _ => {
-                &*self.terms_cx.arena.alloc(|| TransformTerm(v1, v2))
+                &*self.terms_cx.arena.alloc(TransformTerm(v1, v2))
             }
         }
     }
index 6e79bd9bebda1003233dfa0a9b8ce95d06e125f7..dfa5b01270efd3dfc79c9ecda7f62b1bc1b359d4 100644 (file)
@@ -195,7 +195,7 @@ fn build_struct(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::Stru
     let fields = ty::lookup_struct_fields(tcx, did);
 
     clean::Struct {
-        struct_type: match fields.as_slice() {
+        struct_type: match &*fields {
             [] => doctree::Unit,
             [ref f] if f.name == unnamed_field.name => doctree::Newtype,
             [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
@@ -306,13 +306,14 @@ fn build_impl(cx: &DocContext, tcx: &ty::ctxt,
                 let mut item = method.clean(cx);
                 item.inner = match item.inner.clone() {
                     clean::TyMethodItem(clean::TyMethod {
-                        unsafety, decl, self_, generics
+                        unsafety, decl, self_, generics, abi
                     }) => {
                         clean::MethodItem(clean::Method {
                             unsafety: unsafety,
                             decl: decl,
                             self_: self_,
                             generics: generics,
+                            abi: abi
                         })
                     }
                     _ => panic!("not a tymethod"),
@@ -340,7 +341,7 @@ fn build_impl(cx: &DocContext, tcx: &ty::ctxt,
     let polarity = csearch::get_impl_polarity(tcx, did);
     return Some(clean::Item {
         inner: clean::ImplItem(clean::Impl {
-            derived: clean::detect_derived(attrs.as_slice()),
+            derived: clean::detect_derived(&attrs),
             trait_: associated_trait.clean(cx).map(|bound| {
                 match bound {
                     clean::TraitBound(polyt, _) => polyt.trait_,
index 57eaf042aa02edc676697cb3173d92d881dd0209..7ab9d8c6672c42976df9630c088ab319853d49af 100644 (file)
@@ -27,6 +27,7 @@
 pub use self::TraitMethod::*;
 
 use syntax;
+use syntax::abi;
 use syntax::ast;
 use syntax::ast_util;
 use syntax::ast_util::PostExpansionMethod;
@@ -48,7 +49,6 @@
 
 use std::rc::Rc;
 use std::u32;
-use std::str::Str as StrTrait; // Conflicts with Str variant
 use std::old_path::Path as FsPath; // Conflicts with Path struct
 
 use core::DocContext;
@@ -136,7 +136,7 @@ fn clean(&self, cx: &DocContext) -> Crate {
 
         // Figure out the name of this crate
         let input = &cx.input;
-        let name = link::find_crate_name(None, self.attrs.as_slice(), input);
+        let name = link::find_crate_name(None, &self.attrs, input);
 
         // Clean the crate, translating the entire libsyntax AST to one that is
         // understood by rustdoc.
@@ -171,7 +171,7 @@ fn clean(&self, cx: &DocContext) -> Crate {
                     ModuleItem(..) => {}
                     _ => continue,
                 }
-                let prim = match PrimitiveType::find(child.attrs.as_slice()) {
+                let prim = match PrimitiveType::find(&child.attrs) {
                     Some(prim) => prim,
                     None => continue,
                 };
@@ -223,7 +223,7 @@ fn clean(&self, cx: &DocContext) -> ExternalCrate {
                     _ => return
                 };
                 let attrs = inline::load_attrs(cx, tcx, did);
-                PrimitiveType::find(attrs.as_slice()).map(|prim| primitives.push(prim));
+                PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
             })
         });
         ExternalCrate {
@@ -257,7 +257,7 @@ pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
         for attr in &self.attrs {
             match *attr {
                 List(ref x, ref list) if "doc" == *x => {
-                    return Some(list.as_slice());
+                    return Some(list);
                 }
                 _ => {}
             }
@@ -271,7 +271,7 @@ pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
         for attr in &self.attrs {
             match *attr {
                 NameValue(ref x, ref v) if "doc" == *x => {
-                    return Some(v.as_slice());
+                    return Some(v);
                 }
                 _ => {}
             }
@@ -411,12 +411,12 @@ pub enum Attribute {
 impl Clean<Attribute> for ast::MetaItem {
     fn clean(&self, cx: &DocContext) -> Attribute {
         match self.node {
-            ast::MetaWord(ref s) => Word(s.get().to_string()),
+            ast::MetaWord(ref s) => Word(s.to_string()),
             ast::MetaList(ref s, ref l) => {
-                List(s.get().to_string(), l.clean(cx))
+                List(s.to_string(), l.clean(cx))
             }
             ast::MetaNameValue(ref s, ref v) => {
-                NameValue(s.get().to_string(), lit_to_string(v))
+                NameValue(s.to_string(), lit_to_string(v))
             }
         }
     }
@@ -433,7 +433,7 @@ impl attr::AttrMetaMethods for Attribute {
     fn name(&self) -> InternedString {
         match *self {
             Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
-                token::intern_and_get_ident(n.as_slice())
+                token::intern_and_get_ident(n)
             }
         }
     }
@@ -441,7 +441,7 @@ fn name(&self) -> InternedString {
     fn value_str(&self) -> Option<InternedString> {
         match *self {
             NameValue(_, ref v) => {
-                Some(token::intern_and_get_ident(v.as_slice()))
+                Some(token::intern_and_get_ident(v))
             }
             _ => None,
         }
@@ -626,7 +626,7 @@ fn clean(&self, cx: &DocContext) -> TyParamBound {
         let fqn = csearch::get_item_path(tcx, self.def_id);
         let fqn = fqn.into_iter().map(|i| i.to_string())
                      .collect::<Vec<String>>();
-        let path = external_path(cx, fqn.last().unwrap().as_slice(),
+        let path = external_path(cx, fqn.last().unwrap(),
                                  Some(self.def_id), vec![], self.substs);
         cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
                                                             (fqn, TypeTrait));
@@ -690,7 +690,7 @@ fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
 impl Lifetime {
     pub fn get_ref<'a>(&'a self) -> &'a str {
         let Lifetime(ref s) = *self;
-        let s: &'a str = s.as_slice();
+        let s: &'a str = s;
         return s;
     }
 
@@ -701,19 +701,19 @@ pub fn statik() -> Lifetime {
 
 impl Clean<Lifetime> for ast::Lifetime {
     fn clean(&self, _: &DocContext) -> Lifetime {
-        Lifetime(token::get_name(self.name).get().to_string())
+        Lifetime(token::get_name(self.name).to_string())
     }
 }
 
 impl Clean<Lifetime> for ast::LifetimeDef {
     fn clean(&self, _: &DocContext) -> Lifetime {
-        Lifetime(token::get_name(self.lifetime.name).get().to_string())
+        Lifetime(token::get_name(self.lifetime.name).to_string())
     }
 }
 
 impl Clean<Lifetime> for ty::RegionParameterDef {
     fn clean(&self, _: &DocContext) -> Lifetime {
-        Lifetime(token::get_name(self.name).get().to_string())
+        Lifetime(token::get_name(self.name).to_string())
     }
 }
 
@@ -722,7 +722,7 @@ fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
         match *self {
             ty::ReStatic => Some(Lifetime::statik()),
             ty::ReLateBound(_, ty::BrNamed(_, name)) =>
-                Some(Lifetime(token::get_name(name).get().to_string())),
+                Some(Lifetime(token::get_name(name).to_string())),
             ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
 
             ty::ReLateBound(..) |
@@ -946,13 +946,14 @@ pub struct Method {
     pub self_: SelfTy,
     pub unsafety: ast::Unsafety,
     pub decl: FnDecl,
+    pub abi: abi::Abi
 }
 
 impl Clean<Item> for ast::Method {
     fn clean(&self, cx: &DocContext) -> Item {
         let all_inputs = &self.pe_fn_decl().inputs;
         let inputs = match self.pe_explicit_self().node {
-            ast::SelfStatic => all_inputs.as_slice(),
+            ast::SelfStatic => &**all_inputs,
             _ => &all_inputs[1..]
         };
         let decl = FnDecl {
@@ -974,6 +975,7 @@ fn clean(&self, cx: &DocContext) -> Item {
                 self_: self.pe_explicit_self().node.clean(cx),
                 unsafety: self.pe_unsafety().clone(),
                 decl: decl,
+                abi: self.pe_abi()
             }),
         }
     }
@@ -985,12 +987,13 @@ pub struct TyMethod {
     pub decl: FnDecl,
     pub generics: Generics,
     pub self_: SelfTy,
+    pub abi: abi::Abi
 }
 
 impl Clean<Item> for ast::TypeMethod {
     fn clean(&self, cx: &DocContext) -> Item {
         let inputs = match self.explicit_self.node {
-            ast::SelfStatic => self.decl.inputs.as_slice(),
+            ast::SelfStatic => &*self.decl.inputs,
             _ => &self.decl.inputs[1..]
         };
         let decl = FnDecl {
@@ -1012,6 +1015,7 @@ fn clean(&self, cx: &DocContext) -> Item {
                 decl: decl,
                 self_: self.explicit_self.node.clean(cx),
                 generics: self.generics.clean(cx),
+                abi: self.abi
             }),
         }
     }
@@ -1104,7 +1108,7 @@ fn clean(&self, cx: &DocContext) -> FnDecl {
         } else {
             Vec::new().into_iter()
         }.peekable();
-        if names.peek().map(|s| s.as_slice()) == Some("self") {
+        if names.peek().map(|s| &**s) == Some("self") {
             let _ = names.next();
         }
         FnDecl {
@@ -1302,6 +1306,7 @@ fn clean(&self, cx: &DocContext) -> Item {
                 generics: (&self.generics, subst::FnSpace).clean(cx),
                 self_: self_,
                 decl: (self.def_id, &sig).clean(cx),
+                abi: self.fty.abi
             })
         }
     }
@@ -1397,7 +1402,7 @@ pub enum TypeKind {
 
 impl PrimitiveType {
     fn from_str(s: &str) -> Option<PrimitiveType> {
-        match s.as_slice() {
+        match s {
             "isize" | "int" => Some(Isize),
             "i8" => Some(I8),
             "i16" => Some(I16),
@@ -1428,7 +1433,7 @@ fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
             for sub_attr in list {
                 let value = match *sub_attr {
                     NameValue(ref k, ref v)
-                        if *k == "primitive" => v.as_slice(),
+                        if *k == "primitive" => v,
                     _ => continue,
                 };
                 match PrimitiveType::from_str(value) {
@@ -1567,7 +1572,7 @@ fn clean(&self, cx: &DocContext) -> Type {
                     ty::ty_struct(..) => TypeStruct,
                     _ => TypeEnum,
                 };
-                let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
+                let path = external_path(cx, &fqn.last().unwrap().to_string(),
                                          None, vec![], substs);
                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
                 ResolvedPath {
@@ -1581,7 +1586,7 @@ fn clean(&self, cx: &DocContext) -> Type {
                 let fqn = csearch::get_item_path(cx.tcx(), did);
                 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
                 let (typarams, bindings) = bounds.clean(cx);
-                let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
+                let path = external_path(cx, &fqn.last().unwrap().to_string(),
                                          Some(did), bindings, principal.substs());
                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
                 ResolvedPath {
@@ -1780,7 +1785,7 @@ fn clean(&self, cx: &DocContext) -> Item {
 impl<'tcx> Clean<Item> for ty::VariantInfo<'tcx> {
     fn clean(&self, cx: &DocContext) -> Item {
         // use syntax::parse::token::special_idents::unnamed_field;
-        let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
+        let kind = match self.arg_names.as_ref().map(|s| &**s) {
             None | Some([]) if self.args.len() == 0 => CLikeVariant,
             None | Some([]) => {
                 TupleVariant(self.args.clean(cx))
@@ -1954,20 +1959,20 @@ fn path_to_string(p: &ast::Path) -> String {
         } else {
             first = false;
         }
-        s.push_str(i.get());
+        s.push_str(&i);
     }
     s
 }
 
 impl Clean<String> for ast::Ident {
     fn clean(&self, _: &DocContext) -> String {
-        token::get_ident(*self).get().to_string()
+        token::get_ident(*self).to_string()
     }
 }
 
 impl Clean<String> for ast::Name {
     fn clean(&self, _: &DocContext) -> String {
-        token::get_name(*self).get().to_string()
+        token::get_name(*self).to_string()
     }
 }
 
@@ -2132,7 +2137,7 @@ fn clean(&self, cx: &DocContext) -> Item {
                             TypeImplItem(i) => i,
                         }
                     }).collect(),
-                derived: detect_derived(self.attrs.as_slice()),
+                derived: detect_derived(&self.attrs),
                 polarity: Some(self.polarity.clean(cx)),
             }),
         }
@@ -2159,7 +2164,7 @@ fn clean(&self, cx: &DocContext) -> Vec<Item> {
         // forcefully don't inline if this is not public or if the
         // #[doc(no_inline)] attribute is present.
         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
-            a.name().get() == "doc" && match a.meta_item_list() {
+            &a.name()[] == "doc" && match a.meta_item_list() {
                 Some(l) => attr::contains_name(l, "no_inline"),
                 None => false,
             }
@@ -2302,8 +2307,8 @@ impl ToSource for syntax::codemap::Span {
     fn to_src(&self, cx: &DocContext) -> String {
         debug!("converting span {:?} to snippet", self.clean(cx));
         let sn = match cx.sess().codemap().span_to_snippet(*self) {
-            Some(x) => x.to_string(),
-            None    => "".to_string()
+            Ok(x) => x.to_string(),
+            Err(_) => "".to_string()
         };
         debug!("got snippet {}", sn);
         sn
@@ -2312,7 +2317,7 @@ fn to_src(&self, cx: &DocContext) -> String {
 
 fn lit_to_string(lit: &ast::Lit) -> String {
     match lit.node {
-        ast::LitStr(ref st, _) => st.get().to_string(),
+        ast::LitStr(ref st, _) => st.to_string(),
         ast::LitBinary(ref data) => format!("{:?}", data),
         ast::LitByte(b) => {
             let mut res = String::from_str("b'");
@@ -2324,8 +2329,8 @@ fn lit_to_string(lit: &ast::Lit) -> String {
         },
         ast::LitChar(c) => format!("'{}'", c),
         ast::LitInt(i, _t) => i.to_string(),
-        ast::LitFloat(ref f, _t) => f.get().to_string(),
-        ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
+        ast::LitFloat(ref f, _t) => f.to_string(),
+        ast::LitFloatUnsuffixed(ref f) => f.to_string(),
         ast::LitBool(b) => b.to_string(),
     }
 }
@@ -2337,7 +2342,7 @@ fn name_from_pat(p: &ast::Pat) -> String {
     match p.node {
         PatWild(PatWildSingle) => "_".to_string(),
         PatWild(PatWildMulti) => "..".to_string(),
-        PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
+        PatIdent(_, ref p, _) => token::get_ident(p.node).to_string(),
         PatEnum(ref p, _) => path_to_string(p),
         PatStruct(ref name, ref fields, etc) => {
             format!("{} {{ {}{} }}", path_to_string(name),
@@ -2487,11 +2492,11 @@ impl Clean<Stability> for attr::Stability {
     fn clean(&self, _: &DocContext) -> Stability {
         Stability {
             level: self.level,
-            feature: self.feature.get().to_string(),
+            feature: self.feature.to_string(),
             since: self.since.as_ref().map_or("".to_string(),
-                                              |interned| interned.get().to_string()),
+                                              |interned| interned.to_string()),
             reason: self.reason.as_ref().map_or("".to_string(),
-                                                |interned| interned.get().to_string()),
+                                                |interned| interned.to_string()),
         }
     }
 }
index fc3d6f5912ffb566c1a88f73001fc21551192c87..f862970446c14909dd0a2a6568b0c923a3b1fa25 100644 (file)
@@ -119,10 +119,10 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec<String>, externs: Externs,
 
     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
 
-    let name = link::find_crate_name(Some(&sess), krate.attrs.as_slice(),
+    let name = link::find_crate_name(Some(&sess), &krate.attrs,
                                      &input);
 
-    let krate = driver::phase_2_configure_and_expand(&sess, krate, name.as_slice(), None)
+    let krate = driver::phase_2_configure_and_expand(&sess, krate, &name, None)
                     .expect("phase_2_configure_and_expand aborted in rustdoc!");
 
     let mut forest = ast_map::Forest::new(krate);
index 84e88158219ae584273f5e524d4c205f2d13d84d..942aec7d22f2c0bff99a4faaab2fce803e7cb477 100644 (file)
@@ -36,7 +36,7 @@ pub fn load(in_header: &[String], before_content: &[String], after_content: &[St
 pub fn load_string(input: &Path) -> old_io::IoResult<Option<String>> {
     let mut f = try!(old_io::File::open(input));
     let d = try!(f.read_to_end());
-    Ok(str::from_utf8(d.as_slice()).map(|s| s.to_string()).ok())
+    Ok(str::from_utf8(&d).map(|s| s.to_string()).ok())
 }
 
 macro_rules! load_or_return {
@@ -63,7 +63,7 @@ macro_rules! load_or_return {
 pub fn load_external_files(names: &[String]) -> Option<String> {
     let mut out = String::new();
     for name in names {
-        out.push_str(load_or_return!(name.as_slice(), None, None).as_slice());
+        out.push_str(&*load_or_return!(&name, None, None));
         out.push('\n');
     }
     Some(out)
index fe8ac3fde5fcc596e3a2f4f37dd0e09302e7859e..f04e1cc75202f348ceb13318ad89ec88dd13ff75 100644 (file)
@@ -24,7 +24,7 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
         // Because the internet is always right, turns out there's not that many
         // characters to escape: http://stackoverflow.com/questions/7381974
         let Escape(s) = *self;
-        let pile_o_bits = s.as_slice();
+        let pile_o_bits = s;
         let mut last = 0;
         for (i, ch) in s.bytes().enumerate() {
             match ch as char {
index e86c0e39714083faacbcaf37bf61441b0562f9cb..cc2cf21095e413fc820db076e4a16b0e6a2f9bd2 100644 (file)
@@ -109,10 +109,10 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                 if i > 0 {
                     try!(f.write_str(", "))
                 }
-                try!(f.write_str(tp.name.as_slice()));
+                try!(f.write_str(&tp.name));
 
                 if tp.bounds.len() > 0 {
-                    try!(write!(f, ": {}", TyParamBounds(tp.bounds.as_slice())));
+                    try!(write!(f, ": {}", TyParamBounds(&tp.bounds)));
                 }
 
                 match tp.default {
@@ -139,7 +139,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
             }
             match pred {
                 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
-                    let bounds = bounds.as_slice();
+                    let bounds = bounds;
                     try!(write!(f, "{}: {}", ty, TyParamBounds(bounds)));
                 }
                 &clean::WherePredicate::RegionPredicate { ref lifetime,
@@ -259,7 +259,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 
 impl fmt::Display for clean::PathSegment {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        try!(f.write_str(self.name.as_slice()));
+        try!(f.write_str(&self.name));
         write!(f, "{}", self.params)
     }
 }
@@ -321,8 +321,8 @@ fn path<F, G>(w: &mut fmt::Formatter,
 
     let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
     let cache = cache();
-    let abs_root = root(&*cache, loc.as_slice());
-    let rel_root = match path.segments[0].name.as_slice() {
+    let abs_root = root(&*cache, &loc);
+    let rel_root = match &*path.segments[0].name {
         "self" => Some("./".to_string()),
         _ => None,
     };
@@ -331,17 +331,17 @@ fn path<F, G>(w: &mut fmt::Formatter,
         let amt = path.segments.len() - 1;
         match rel_root {
             Some(root) => {
-                let mut root = String::from_str(root.as_slice());
+                let mut root = String::from_str(&root);
                 for seg in &path.segments[..amt] {
                     if "super" == seg.name ||
                             "self" == seg.name {
                         try!(write!(w, "{}::", seg.name));
                     } else {
-                        root.push_str(seg.name.as_slice());
+                        root.push_str(&seg.name);
                         root.push_str("/");
                         try!(write!(w, "<a class='mod'
                                             href='{}index.html'>{}</a>::",
-                                      root.as_slice(),
+                                      root,
                                       seg.name));
                     }
                 }
@@ -357,21 +357,21 @@ fn path<F, G>(w: &mut fmt::Formatter,
     match info(&*cache) {
         // This is a documented path, link to it!
         Some((ref fqp, shortty)) if abs_root.is_some() => {
-            let mut url = String::from_str(abs_root.unwrap().as_slice());
+            let mut url = String::from_str(&abs_root.unwrap());
             let to_link = &fqp[..fqp.len() - 1];
             for component in to_link {
-                url.push_str(component.as_slice());
+                url.push_str(component);
                 url.push_str("/");
             }
             match shortty {
                 ItemType::Module => {
-                    url.push_str(fqp.last().unwrap().as_slice());
+                    url.push_str(fqp.last().unwrap());
                     url.push_str("/index.html");
                 }
                 _ => {
                     url.push_str(shortty.to_static_str());
                     url.push_str(".");
-                    url.push_str(fqp.last().unwrap().as_slice());
+                    url.push_str(fqp.last().unwrap());
                     url.push_str(".html");
                 }
             }
@@ -384,7 +384,7 @@ fn path<F, G>(w: &mut fmt::Formatter,
             try!(write!(w, "{}", last.name));
         }
     }
-    try!(write!(w, "{}", generics.as_slice()));
+    try!(write!(w, "{}", generics));
     Ok(())
 }
 
@@ -454,13 +454,14 @@ impl fmt::Display for clean::Type {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         match *self {
             clean::TyParamBinder(id) => {
-                f.write_str(cache().typarams[ast_util::local_def(id)].as_slice())
+                f.write_str(&cache().typarams[ast_util::local_def(id)])
             }
             clean::Generic(ref name) => {
-                f.write_str(name.as_slice())
+                f.write_str(name)
             }
             clean::ResolvedPath{ did, ref typarams, ref path } => {
-                try!(resolved_path(f, did, path, false));
+                // Paths like Self::Output should be rendered with all segments
+                try!(resolved_path(f, did, path, path.segments[0].name == "Self"));
                 tybounds(f, typarams)
             }
             clean::Infer => write!(f, "_"),
@@ -468,7 +469,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
             clean::BareFunction(ref decl) => {
                 write!(f, "{}{}fn{}{}",
                        UnsafetySpace(decl.unsafety),
-                       match decl.abi.as_slice() {
+                       match &*decl.abi {
                            "" => " extern ".to_string(),
                            "\"Rust\"" => "".to_string(),
                            s => format!(" extern {} ", s)
@@ -478,18 +479,17 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
             }
             clean::Tuple(ref typs) => {
                 primitive_link(f, clean::PrimitiveTuple,
-                               match typs.as_slice() {
+                               &*match &**typs {
                                     [ref one] => format!("({},)", one),
-                                    many => format!("({})",
-                                                    CommaSep(many.as_slice()))
-                               }.as_slice())
+                                    many => format!("({})", CommaSep(&many)),
+                               })
             }
             clean::Vector(ref t) => {
-                primitive_link(f, clean::Slice, format!("[{}]", **t).as_slice())
+                primitive_link(f, clean::Slice, &format!("[{}]", **t))
             }
             clean::FixedVector(ref t, ref s) => {
                 primitive_link(f, clean::Slice,
-                               format!("[{}; {}]", **t, *s).as_slice())
+                               &format!("[{}; {}]", **t, *s))
             }
             clean::Bottom => f.write_str("!"),
             clean::RawPointer(m, ref t) => {
@@ -506,10 +506,10 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                         match **bt {
                             clean::Generic(_) =>
                                 primitive_link(f, clean::Slice,
-                                    format!("&amp;{}{}[{}]", lt, m, **bt).as_slice()),
+                                    &format!("&amp;{}{}[{}]", lt, m, **bt)),
                             _ => {
                                 try!(primitive_link(f, clean::Slice,
-                                    format!("&amp;{}{}[", lt, m).as_slice()));
+                                    &format!("&amp;{}{}[", lt, m)));
                                 try!(write!(f, "{}", **bt));
                                 primitive_link(f, clean::Slice, "]")
                             }
@@ -577,23 +577,21 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
             clean::SelfStatic => {},
             clean::SelfValue => args.push_str("self"),
             clean::SelfBorrowed(Some(ref lt), mtbl) => {
-                args.push_str(format!("&amp;{} {}self", *lt,
-                                      MutableSpace(mtbl)).as_slice());
+                args.push_str(&format!("&amp;{} {}self", *lt, MutableSpace(mtbl)));
             }
             clean::SelfBorrowed(None, mtbl) => {
-                args.push_str(format!("&amp;{}self",
-                                      MutableSpace(mtbl)).as_slice());
+                args.push_str(&format!("&amp;{}self", MutableSpace(mtbl)));
             }
             clean::SelfExplicit(ref typ) => {
-                args.push_str(format!("self: {}", *typ).as_slice());
+                args.push_str(&format!("self: {}", *typ));
             }
         }
         for (i, input) in d.inputs.values.iter().enumerate() {
             if i > 0 || args.len() > 0 { args.push_str(", "); }
             if input.name.len() > 0 {
-                args.push_str(format!("{}: ", input.name).as_slice());
+                args.push_str(&format!("{}: ", input.name));
             }
-            args.push_str(format!("{}", input.type_).as_slice());
+            args.push_str(&format!("{}", input.type_));
         }
         write!(f, "({args}){arrow}", args = args, arrow = d.output)
     }
@@ -748,7 +746,7 @@ fn fmt_inner<'a>(f: &mut fmt::Formatter,
             let tot = cnt.total();
             if tot == 0 { return Ok(()) }
 
-            context.push(m.name.as_slice());
+            context.push(&m.name);
             let path = context.connect("::");
 
             try!(write!(f, "<tr>"));
index 38b191846f1985229c1f494731a884738a63fd6a..6acd15379461cfbafcc91f9f2fb9cb56b7c16822 100644 (file)
@@ -61,18 +61,18 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
     loop {
         let next = lexer.next_token();
 
-        let snip = |&: sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap();
+        let snip = |sp| sess.span_diagnostic.cm.span_to_snippet(sp).unwrap();
 
         if next.tok == token::Eof { break }
 
         let klass = match next.tok {
             token::Whitespace => {
-                try!(write!(out, "{}", Escape(snip(next.sp).as_slice())));
+                try!(write!(out, "{}", Escape(&snip(next.sp))));
                 continue
             },
             token::Comment => {
                 try!(write!(out, "<span class='comment'>{}</span>",
-                            Escape(snip(next.sp).as_slice())));
+                            Escape(&snip(next.sp))));
                 continue
             },
             token::Shebang(s) => {
@@ -142,7 +142,7 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
 
             // keywords are also included in the identifier set
             token::Ident(ident, _is_mod_sep) => {
-                match token::get_ident(ident).get() {
+                match &token::get_ident(ident)[] {
                     "ref" | "mut" => "kw-2",
 
                     "self" => "self",
@@ -179,10 +179,10 @@ fn doit(sess: &parse::ParseSess, mut lexer: lexer::StringReader,
         // stringifying this token
         let snip = sess.span_diagnostic.cm.span_to_snippet(next.sp).unwrap();
         if klass == "" {
-            try!(write!(out, "{}", Escape(snip.as_slice())));
+            try!(write!(out, "{}", Escape(&snip)));
         } else {
             try!(write!(out, "<span class='{}'>{}</span>", klass,
-                          Escape(snip.as_slice())));
+                          Escape(&snip)));
         }
     }
 
index 7e08226019f9849ca56a1f7e7538a59201381f31..c513fe2e8eb3cf2b44056a6d1395cf5669aa1cd2 100644 (file)
@@ -165,6 +165,13 @@ fn hoedown_buffer_put(b: *mut hoedown_buffer, c: *const libc::c_char,
 
 }
 
+// hoedown_buffer helpers
+impl hoedown_buffer {
+    fn as_bytes(&self) -> &[u8] {
+        unsafe { slice::from_raw_parts(self.data, self.size as usize) }
+    }
+}
+
 /// Returns Some(code) if `s` is a line that should be stripped from
 /// documentation but used in example code. `code` is the portion of
 /// `s` that should be used in tests. (None for lines that should be
@@ -194,15 +201,13 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
 
             let opaque = opaque as *mut hoedown_html_renderer_state;
             let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque);
-            let text = slice::from_raw_buf(&(*orig_text).data,
-                                           (*orig_text).size as uint);
+            let text = (*orig_text).as_bytes();
             let origtext = str::from_utf8(text).unwrap();
             debug!("docblock: ==============\n{:?}\n=======", text);
             let rendered = if lang.is_null() {
                 false
             } else {
-                let rlang = slice::from_raw_buf(&(*lang).data,
-                                                (*lang).size as uint);
+                let rlang = (*lang).as_bytes();
                 let rlang = str::from_utf8(rlang).unwrap();
                 if !LangString::parse(rlang).rust {
                     (my_opaque.dfltblk)(ob, orig_text, lang,
@@ -224,15 +229,13 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
                     let test = origtext.lines().map(|l| {
                         stripped_filtered_line(l).unwrap_or(l)
                     }).collect::<Vec<&str>>().connect("\n");
-                    let krate = krate.as_ref().map(|s| s.as_slice());
-                    let test = test::maketest(test.as_slice(), krate, false, false);
-                    s.push_str(format!("<span class='rusttest'>{}</span>",
-                                         Escape(test.as_slice())).as_slice());
+                    let krate = krate.as_ref().map(|s| &**s);
+                    let test = test::maketest(&test, krate, false, false);
+                    s.push_str(&format!("<span class='rusttest'>{}</span>", Escape(&test)));
                 });
-                s.push_str(highlight::highlight(text.as_slice(),
-                                                None,
-                                                Some("rust-example-rendered"))
-                             .as_slice());
+                s.push_str(&highlight::highlight(&text,
+                                                 None,
+                                                 Some("rust-example-rendered")));
                 let output = CString::from_vec(s.into_bytes());
                 hoedown_buffer_puts(ob, output.as_ptr());
             })
@@ -248,9 +251,7 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
         let s = if text.is_null() {
             "".to_string()
         } else {
-            let s = unsafe {
-                slice::from_raw_buf(&(*text).data, (*text).size as uint)
-            };
+            let s = unsafe { (*text).as_bytes() };
             str::from_utf8(s).unwrap().to_string()
         };
 
@@ -323,7 +324,7 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
         };
 
         if ret.is_ok() {
-            let buf = slice::from_raw_buf(&(*ob).data, (*ob).size as uint);
+            let buf = (*ob).as_bytes();
             ret = w.write_str(str::from_utf8(buf).unwrap());
         }
         hoedown_buffer_free(ob);
@@ -341,13 +342,12 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
             let block_info = if lang.is_null() {
                 LangString::all_false()
             } else {
-                let lang = slice::from_raw_buf(&(*lang).data,
-                                               (*lang).size as uint);
+                let lang = (*lang).as_bytes();
                 let s = str::from_utf8(lang).unwrap();
                 LangString::parse(s)
             };
             if !block_info.rust { return }
-            let text = slice::from_raw_buf(&(*text).data, (*text).size as uint);
+            let text = (*text).as_bytes();
             let opaque = opaque as *mut hoedown_html_renderer_state;
             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
             let text = str::from_utf8(text).unwrap();
@@ -370,7 +370,7 @@ pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
             if text.is_null() {
                 tests.register_header("", level as u32);
             } else {
-                let text = slice::from_raw_buf(&(*text).data, (*text).size as uint);
+                let text = (*text).as_bytes();
                 let text = str::from_utf8(text).unwrap();
                 tests.register_header(text, level as u32);
             }
@@ -420,7 +420,7 @@ fn parse(string: &str) -> LangString {
         let mut seen_other_tags = false;
         let mut data = LangString::all_false();
 
-        let tokens = string.split(|&: c: char|
+        let tokens = string.split(|c: char|
             !(c == '_' || c == '-' || c.is_alphanumeric())
         );
 
@@ -459,14 +459,14 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
         let Markdown(md) = *self;
         // This is actually common enough to special-case
         if md.len() == 0 { return Ok(()) }
-        render(fmt, md.as_slice(), false)
+        render(fmt, md, false)
     }
 }
 
 impl<'a> fmt::Display for MarkdownWithToc<'a> {
     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
         let MarkdownWithToc(md) = *self;
-        render(fmt, md.as_slice(), true)
+        render(fmt, md, true)
     }
 }
 
@@ -510,7 +510,7 @@ pub fn plain_summary_line(md: &str) -> String {
         hoedown_document_render(document, ob, md.as_ptr(),
                                 md.len() as libc::size_t);
         hoedown_document_free(document);
-        let plain_slice = slice::from_raw_buf(&(*ob).data, (*ob).size as uint);
+        let plain_slice = (*ob).as_bytes();
         let plain = match str::from_utf8(plain_slice) {
             Ok(s) => s.to_string(),
             Err(_) => "".to_string(),
@@ -555,7 +555,7 @@ fn t(s: &str,
     #[test]
     fn issue_17736() {
         let markdown = "# title";
-        format!("{}", Markdown(markdown.as_slice()));
+        format!("{}", Markdown(markdown));
     }
 
     #[test]
index 6247c6dad1496dd23b3e2a9fce432e2427621e94..b30b251e8ba6f1aceb29a1d8051a2a7d74121778 100644 (file)
@@ -50,6 +50,7 @@
 
 use serialize::json;
 use serialize::json::ToJson;
+use syntax::abi;
 use syntax::ast;
 use syntax::ast_util;
 use rustc::util::nodemap::NodeSet;
@@ -447,7 +448,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> old_io::IoResult<Stri
             path = "";
         } else {
             lastpath = item.path.to_string();
-            path = item.path.as_slice();
+            path = &item.path;
         };
 
         if i > 0 {
@@ -525,8 +526,7 @@ fn collect(path: &Path, krate: &str,
                 if !line.starts_with(key) {
                     continue
                 }
-                if line.starts_with(
-                        format!("{}['{}']", key, krate).as_slice()) {
+                if line.starts_with(&format!("{}['{}']", key, krate)) {
                     continue
                 }
                 ret.push(line.to_string());
@@ -537,8 +537,7 @@ fn collect(path: &Path, krate: &str,
 
     // Update the search index
     let dst = cx.dst.join("search-index.js");
-    let all_indexes = try!(collect(&dst, krate.name.as_slice(),
-                                   "searchIndex"));
+    let all_indexes = try!(collect(&dst, &krate.name, "searchIndex"));
     let mut w = try!(File::create(&dst));
     try!(writeln!(&mut w, "var searchIndex = {{}};"));
     try!(writeln!(&mut w, "{}", search_index));
@@ -565,13 +564,13 @@ fn collect(path: &Path, krate: &str,
 
         let mut mydst = dst.clone();
         for part in &remote_path[..remote_path.len() - 1] {
-            mydst.push(part.as_slice());
+            mydst.push(part);
             try!(mkdir(&mydst));
         }
         mydst.push(format!("{}.{}.js",
                            remote_item_type.to_static_str(),
                            remote_path[remote_path.len() - 1]));
-        let all_implementors = try!(collect(&mydst, krate.name.as_slice(),
+        let all_implementors = try!(collect(&mydst, &krate.name,
                                             "implementors"));
 
         try!(mkdir(&mydst.dir_path()));
@@ -611,7 +610,7 @@ fn render_sources(cx: &mut Context,
     info!("emitting source files");
     let dst = cx.dst.join("src");
     try!(mkdir(&dst));
-    let dst = dst.join(krate.name.as_slice());
+    let dst = dst.join(&krate.name);
     try!(mkdir(&dst));
     let mut folder = SourceCollector {
         dst: dst,
@@ -662,7 +661,7 @@ fn clean_srcpath<F>(src_root: &Path, src: &[u8], mut f: F) where
             if ".." == c {
                 f("up");
             } else {
-                f(c.as_slice())
+                f(c)
             }
         }
     }
@@ -672,7 +671,7 @@ fn clean_srcpath<F>(src_root: &Path, src: &[u8], mut f: F) where
 /// rendering in to the specified source destination.
 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
     // See if there's documentation generated into the local directory
-    let local_location = dst.join(e.name.as_slice());
+    let local_location = dst.join(&e.name);
     if local_location.is_dir() {
         return Local;
     }
@@ -715,9 +714,7 @@ fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
             // entire crate. The other option is maintaining this mapping on a
             // per-file basis, but that's probably not worth it...
             self.cx
-                .include_sources = match self.emit_source(item.source
-                                                              .filename
-                                                              .as_slice()) {
+                .include_sources = match self.emit_source(&item.source .filename) {
                 Ok(()) => true,
                 Err(e) => {
                     println!("warning: source code was requested to be rendered, \
@@ -750,7 +747,7 @@ fn emit_source(&mut self, filename: &str) -> old_io::IoResult<()> {
                        filename.ends_with("macros>") => return Ok(()),
             Err(e) => return Err(e)
         };
-        let contents = str::from_utf8(contents.as_slice()).unwrap();
+        let contents = str::from_utf8(&contents).unwrap();
 
         // Remove the utf-8 BOM if any
         let contents = if contents.starts_with("\u{feff}") {
@@ -776,10 +773,10 @@ fn emit_source(&mut self, filename: &str) -> old_io::IoResult<()> {
         let title = format!("{} -- source", cur.filename_display());
         let desc = format!("Source to the Rust file `{}`.", filename);
         let page = layout::Page {
-            title: title.as_slice(),
+            title: &title,
             ty: "source",
-            root_path: root_path.as_slice(),
-            description: desc.as_slice(),
+            root_path: &root_path,
+            description: &desc,
             keywords: get_basic_keywords(),
         };
         try!(layout::render(&mut w as &mut Writer, &self.cx.layout,
@@ -865,13 +862,13 @@ fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
                             Some(&(ref fqp, ItemType::Struct)) |
                             Some(&(ref fqp, ItemType::Enum)) =>
                                 Some(&fqp[..fqp.len() - 1]),
-                            Some(..) => Some(self.stack.as_slice()),
+                            Some(..) => Some(&*self.stack),
                             None => None
                         };
                         ((Some(*last), path), true)
                     }
                 }
-                _ => ((None, Some(self.stack.as_slice())), false)
+                _ => ((None, Some(&*self.stack)), false)
             };
             let hidden_field = match item.inner {
                 clean::StructFieldItem(clean::HiddenStructField) => true,
@@ -1059,7 +1056,7 @@ fn recurse<T, F>(&mut self, s: String, f: F) -> T where
             panic!("Unexpected empty destination: {:?}", self.current);
         }
         let prev = self.dst.clone();
-        self.dst.push(s.as_slice());
+        self.dst.push(&s);
         self.root_path.push_str("../");
         self.current.push(s);
 
@@ -1103,9 +1100,9 @@ fn krate(mut self, mut krate: clean::Crate,
                                this.layout.krate);
             let page = layout::Page {
                 ty: "mod",
-                root_path: this.root_path.as_slice(),
-                title: title.as_slice(),
-                description: desc.as_slice(),
+                root_path: &this.root_path,
+                title: &title,
+                description: &desc,
                 keywords: get_basic_keywords(),
             };
             let html_dst = &this.dst.join("stability.html");
@@ -1151,7 +1148,7 @@ fn render(w: old_io::File, cx: &Context, it: &clean::Item,
                 if title.len() > 0 {
                     title.push_str("::");
                 }
-                title.push_str(it.name.as_ref().unwrap().as_slice());
+                title.push_str(it.name.as_ref().unwrap());
             }
             title.push_str(" - Rust");
             let tyname = shortty(it).to_static_str();
@@ -1169,10 +1166,10 @@ fn render(w: old_io::File, cx: &Context, it: &clean::Item,
             let keywords = make_item_keywords(it);
             let page = layout::Page {
                 ty: tyname,
-                root_path: cx.root_path.as_slice(),
-                title: title.as_slice(),
-                description: desc.as_slice(),
-                keywords: keywords.as_slice(),
+                root_path: &cx.root_path,
+                title: &title,
+                description: &desc,
+                keywords: &keywords,
             };
 
             markdown::reset_headers();
@@ -1191,11 +1188,11 @@ fn render(w: old_io::File, cx: &Context, it: &clean::Item,
                 match cache().paths.get(&it.def_id) {
                     Some(&(ref names, _)) => {
                         for name in &names[..names.len() - 1] {
-                            url.push_str(name.as_slice());
+                            url.push_str(name);
                             url.push_str("/");
                         }
-                        url.push_str(item_path(it).as_slice());
-                        try!(layout::redirect(&mut writer, url.as_slice()));
+                        url.push_str(&item_path(it));
+                        try!(layout::redirect(&mut writer, &url));
                     }
                     None => {}
                 }
@@ -1378,17 +1375,17 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
             _ => false,
         };
         if !is_primitive {
-            let cur = self.cx.current.as_slice();
+            let cur = &self.cx.current;
             let amt = if self.ismodule() { cur.len() - 1 } else { cur.len() };
             for (i, component) in cur.iter().enumerate().take(amt) {
                 try!(write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
                             repeat("../").take(cur.len() - i - 1)
                                          .collect::<String>(),
-                            component.as_slice()));
+                            component));
             }
         }
         try!(write!(fmt, "<a class='{}' href=''>{}</a>",
-                    shortty(self.item), self.item.name.as_ref().unwrap().as_slice()));
+                    shortty(self.item), self.item.name.as_ref().unwrap()));
 
         // Write stability level
         try!(write!(fmt, "<wbr>{}", Stability(&self.item.stability)));
@@ -1433,7 +1430,7 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
 
         match self.item.inner {
             clean::ModuleItem(ref m) => {
-                item_module(fmt, self.cx, self.item, m.items.as_slice())
+                item_module(fmt, self.cx, self.item, &m.items)
             }
             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
                 item_function(fmt, self.item, f),
@@ -1467,7 +1464,7 @@ fn item_path(item: &clean::Item) -> String {
 fn full_path(cx: &Context, item: &clean::Item) -> String {
     let mut s = cx.current.connect("::");
     s.push_str("::");
-    s.push_str(item.name.as_ref().unwrap().as_slice());
+    s.push_str(item.name.as_ref().unwrap());
     return s
 }
 
@@ -1580,12 +1577,12 @@ fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: uint, idx2: uint) -> Ordering {
                     Some(ref src) => {
                         try!(write!(w, "<tr><td><code>{}extern crate \"{}\" as {};",
                                     VisSpace(myitem.visibility),
-                                    src.as_slice(),
-                                    name.as_slice()))
+                                    src,
+                                    name))
                     }
                     None => {
                         try!(write!(w, "<tr><td><code>{}extern crate {};",
-                                    VisSpace(myitem.visibility), name.as_slice()))
+                                    VisSpace(myitem.visibility), name))
                     }
                 }
                 try!(write!(w, "</code></td></tr>"));
@@ -1625,7 +1622,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         let Initializer(s) = *self;
         if s.len() == 0 { return Ok(()); }
         try!(write!(f, "<code> = </code>"));
-        write!(f, "<code>{}</code>", s.as_slice())
+        write!(f, "<code>{}</code>", s)
     }
 }
 
@@ -1634,9 +1631,9 @@ fn item_constant(w: &mut fmt::Formatter, it: &clean::Item,
     try!(write!(w, "<pre class='rust const'>{vis}const \
                     {name}: {typ}{init}</pre>",
            vis = VisSpace(it.visibility),
-           name = it.name.as_ref().unwrap().as_slice(),
+           name = it.name.as_ref().unwrap(),
            typ = c.type_,
-           init = Initializer(c.expr.as_slice())));
+           init = Initializer(&c.expr)));
     document(w, it)
 }
 
@@ -1646,9 +1643,9 @@ fn item_static(w: &mut fmt::Formatter, it: &clean::Item,
                     {name}: {typ}{init}</pre>",
            vis = VisSpace(it.visibility),
            mutability = MutableSpace(s.mutability),
-           name = it.name.as_ref().unwrap().as_slice(),
+           name = it.name.as_ref().unwrap(),
            typ = s.type_,
-           init = Initializer(s.expr.as_slice())));
+           init = Initializer(&s.expr)));
     document(w, it)
 }
 
@@ -1658,7 +1655,7 @@ fn item_function(w: &mut fmt::Formatter, it: &clean::Item,
                     {name}{generics}{decl}{where_clause}</pre>",
            vis = VisSpace(it.visibility),
            unsafety = UnsafetySpace(f.unsafety),
-           name = it.name.as_ref().unwrap().as_slice(),
+           name = it.name.as_ref().unwrap(),
            generics = f.generics,
            where_clause = WhereClause(&f.generics),
            decl = f.decl));
@@ -1675,7 +1672,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
         bounds.push_str(": ");
         for (i, p) in t.bounds.iter().enumerate() {
             if i > 0 { bounds.push_str(" + "); }
-            bounds.push_str(format!("{}", *p).as_slice());
+            bounds.push_str(&format!("{}", *p));
         }
     }
 
@@ -1683,7 +1680,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
     try!(write!(w, "<pre class='rust trait'>{}{}trait {}{}{}{} ",
                   VisSpace(it.visibility),
                   UnsafetySpace(t.unsafety),
-                  it.name.as_ref().unwrap().as_slice(),
+                  it.name.as_ref().unwrap(),
                   t.generics,
                   bounds,
                   WhereClause(&t.generics)));
@@ -1813,27 +1810,34 @@ fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
 }
 
 fn render_method(w: &mut fmt::Formatter, meth: &clean::Item) -> fmt::Result {
-    fn method(w: &mut fmt::Formatter, it: &clean::Item, unsafety: ast::Unsafety,
-           g: &clean::Generics, selfty: &clean::SelfTy,
-           d: &clean::FnDecl) -> fmt::Result {
-        write!(w, "{}fn <a href='#{ty}.{name}' class='fnname'>{name}</a>\
+    fn method(w: &mut fmt::Formatter, it: &clean::Item,
+              unsafety: ast::Unsafety, abi: abi::Abi,
+              g: &clean::Generics, selfty: &clean::SelfTy,
+              d: &clean::FnDecl) -> fmt::Result {
+        use syntax::abi::Abi;
+
+        write!(w, "{}{}fn <a href='#{ty}.{name}' class='fnname'>{name}</a>\
                    {generics}{decl}{where_clause}",
                match unsafety {
                    ast::Unsafety::Unsafe => "unsafe ",
                    _ => "",
                },
+               match abi {
+                   Abi::Rust => String::new(),
+                   a => format!("extern {} ", a.to_string())
+               },
                ty = shortty(it),
-               name = it.name.as_ref().unwrap().as_slice(),
+               name = it.name.as_ref().unwrap(),
                generics = *g,
                decl = Method(selfty, d),
                where_clause = WhereClause(g))
     }
     match meth.inner {
         clean::TyMethodItem(ref m) => {
-            method(w, meth, m.unsafety, &m.generics, &m.self_, &m.decl)
+            method(w, meth, m.unsafety, m.abi, &m.generics, &m.self_, &m.decl)
         }
         clean::MethodItem(ref m) => {
-            method(w, meth, m.unsafety, &m.generics, &m.self_, &m.decl)
+            method(w, meth, m.unsafety, m.abi, &m.generics, &m.self_, &m.decl)
         }
         clean::AssociatedTypeItem(ref typ) => {
             assoc_type(w, meth, typ)
@@ -1849,7 +1853,7 @@ fn item_struct(w: &mut fmt::Formatter, it: &clean::Item,
                        it,
                        Some(&s.generics),
                        s.struct_type,
-                       s.fields.as_slice(),
+                       &s.fields,
                        "",
                        true));
     try!(write!(w, "</pre>"));
@@ -1869,7 +1873,7 @@ fn item_struct(w: &mut fmt::Formatter, it: &clean::Item,
                 try!(write!(w, "<tr><td id='structfield.{name}'>\
                                   {stab}<code>{name}</code></td><td>",
                             stab = ConciseStability(&field.stability),
-                            name = field.name.as_ref().unwrap().as_slice()));
+                            name = field.name.as_ref().unwrap()));
                 try!(document(w, field));
                 try!(write!(w, "</td></tr>"));
             }
@@ -1883,7 +1887,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
              e: &clean::Enum) -> fmt::Result {
     try!(write!(w, "<pre class='rust enum'>{}enum {}{}{}",
                   VisSpace(it.visibility),
-                  it.name.as_ref().unwrap().as_slice(),
+                  it.name.as_ref().unwrap(),
                   e.generics,
                   WhereClause(&e.generics)));
     if e.variants.len() == 0 && !e.variants_stripped {
@@ -1892,7 +1896,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
         try!(write!(w, " {{\n"));
         for v in &e.variants {
             try!(write!(w, "    "));
-            let name = v.name.as_ref().unwrap().as_slice();
+            let name = v.name.as_ref().unwrap();
             match v.inner {
                 clean::VariantItem(ref var) => {
                     match var.kind {
@@ -1912,7 +1916,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
                                                v,
                                                None,
                                                s.struct_type,
-                                               s.fields.as_slice(),
+                                               &s.fields,
                                                "    ",
                                                false));
                         }
@@ -1936,7 +1940,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
         for variant in &e.variants {
             try!(write!(w, "<tr><td id='variant.{name}'>{stab}<code>{name}</code></td><td>",
                           stab = ConciseStability(&variant.stability),
-                          name = variant.name.as_ref().unwrap().as_slice()));
+                          name = variant.name.as_ref().unwrap()));
             try!(document(w, variant));
             match variant.inner {
                 clean::VariantItem(ref var) => {
@@ -1957,8 +1961,8 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
                                 try!(write!(w, "<tr><td \
                                                   id='variant.{v}.field.{f}'>\
                                                   <code>{f}</code></td><td>",
-                                              v = variant.name.as_ref().unwrap().as_slice(),
-                                              f = field.name.as_ref().unwrap().as_slice()));
+                                              v = variant.name.as_ref().unwrap(),
+                                              f = field.name.as_ref().unwrap()));
                                 try!(document(w, field));
                                 try!(write!(w, "</td></tr>"));
                             }
@@ -1987,7 +1991,7 @@ fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
     try!(write!(w, "{}{}{}",
                   VisSpace(it.visibility),
                   if structhead {"struct "} else {""},
-                  it.name.as_ref().unwrap().as_slice()));
+                  it.name.as_ref().unwrap()));
     match g {
         Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
         None => {}
@@ -2004,7 +2008,7 @@ fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
                     clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
                         try!(write!(w, "    {}{}: {},\n{}",
                                       VisSpace(field.visibility),
-                                      field.name.as_ref().unwrap().as_slice(),
+                                      field.name.as_ref().unwrap(),
                                       *ty,
                                       tab));
                     }
@@ -2091,7 +2095,7 @@ fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result {
     match i.dox {
         Some(ref dox) => {
             try!(write!(w, "<div class='docblock'>{}</div>",
-                          Markdown(dox.as_slice())));
+                          Markdown(dox)));
         }
         None => {}
     }
@@ -2179,7 +2183,7 @@ fn render_default_methods(w: &mut fmt::Formatter,
 fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item,
                 t: &clean::Typedef) -> fmt::Result {
     try!(write!(w, "<pre class='rust typedef'>type {}{} = {};</pre>",
-                  it.name.as_ref().unwrap().as_slice(),
+                  it.name.as_ref().unwrap(),
                   t.generics,
                   t.type_));
 
@@ -2205,7 +2209,7 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
         fn block(w: &mut fmt::Formatter, short: &str, longty: &str,
                  cur: &clean::Item, cx: &Context) -> fmt::Result {
             let items = match cx.sidebar.get(short) {
-                Some(items) => items.as_slice(),
+                Some(items) => items,
                 None => return Ok(())
             };
             try!(write!(w, "<div class='block {}'><h2>{}</h2>", short, longty));
@@ -2219,12 +2223,12 @@ fn block(w: &mut fmt::Formatter, short: &str, longty: &str,
                        class = class,
                        href = if curty == "mod" {"../"} else {""},
                        path = if short == "mod" {
-                           format!("{}/index.html", name.as_slice())
+                           format!("{}/index.html", name)
                        } else {
-                           format!("{}.{}.html", short, name.as_slice())
+                           format!("{}.{}.html", short, name)
                        },
-                       title = Escape(doc.as_ref().unwrap().as_slice()),
-                       name = name.as_slice()));
+                       title = Escape(doc.as_ref().unwrap()),
+                       name = name));
             }
             try!(write!(w, "</div>"));
             Ok(())
@@ -2255,16 +2259,16 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
             try!(write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols));
         }
         try!(write!(fmt, "</pre>"));
-        try!(write!(fmt, "{}", highlight::highlight(s.as_slice(), None, None)));
+        try!(write!(fmt, "{}", highlight::highlight(s, None, None)));
         Ok(())
     }
 }
 
 fn item_macro(w: &mut fmt::Formatter, it: &clean::Item,
               t: &clean::Macro) -> fmt::Result {
-    try!(w.write_str(highlight::highlight(t.source.as_slice(),
+    try!(w.write_str(&highlight::highlight(&t.source,
                                           Some("macro"),
-                                          None).as_slice()));
+                                          None)));
     document(w, it)
 }
 
index 7790c7d6a50f7262d2990c31c0d45488ec626015..ecef4c9bf7226c182aa08dee218074609a6387d1 100644 (file)
@@ -145,8 +145,7 @@ pub fn push<'a>(&'a mut self, level: u32, name: String, id: String) -> &'a str {
                     (0, &self.top_level)
                 }
                 Some(entry) => {
-                    sec_number = String::from_str(entry.sec_number
-                                                       .as_slice());
+                    sec_number = String::from_str(&entry.sec_number);
                     sec_number.push_str(".");
                     (entry.level, &entry.children)
                 }
@@ -158,7 +157,7 @@ pub fn push<'a>(&'a mut self, level: u32, name: String, id: String) -> &'a str {
                 sec_number.push_str("0.");
             }
             let number = toc.count_entries_with_level(level);
-            sec_number.push_str(format!("{}", number + 1).as_slice())
+            sec_number.push_str(&format!("{}", number + 1))
         }
 
         self.chain.push(TocEntry {
@@ -172,7 +171,7 @@ pub fn push<'a>(&'a mut self, level: u32, name: String, id: String) -> &'a str {
         // get the thing we just pushed, so we can borrow the string
         // out of it with the right lifetime
         let just_inserted = self.chain.last_mut().unwrap();
-        just_inserted.sec_number.as_slice()
+        &just_inserted.sec_number
     }
 }
 
index f4b8bbd5f8a518772bd64d88473e428ba94b2d24..40e9703c03ffbf1a31ace44d3d685de6923730c3 100644 (file)
@@ -178,12 +178,12 @@ pub fn opts() -> Vec<getopts::OptGroup> {
 
 pub fn usage(argv0: &str) {
     println!("{}",
-             getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
-                            opts().as_slice()));
+             getopts::usage(&format!("{} [options] <input>", argv0),
+                            &opts()));
 }
 
 pub fn main_args(args: &[String]) -> int {
-    let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
+    let matches = match getopts::getopts(args.tail(), &opts()) {
         Ok(m) => m,
         Err(err) => {
             println!("{}", err);
@@ -191,7 +191,7 @@ pub fn main_args(args: &[String]) -> int {
         }
     };
     if matches.opt_present("h") || matches.opt_present("help") {
-        usage(args[0].as_slice());
+        usage(&args[0]);
         return 0;
     } else if matches.opt_present("version") {
         rustc_driver::version("rustdoc", &matches);
@@ -217,11 +217,11 @@ pub fn main_args(args: &[String]) -> int {
         println!("only one input file may be specified");
         return 1;
     }
-    let input = matches.free[0].as_slice();
+    let input = &matches.free[0];
 
     let mut libs = SearchPaths::new();
     for s in &matches.opt_strs("L") {
-        libs.add_path(s.as_slice());
+        libs.add_path(s);
     }
     let externs = match parse_externs(&matches) {
         Ok(ex) => ex,
@@ -244,9 +244,9 @@ pub fn main_args(args: &[String]) -> int {
     let cfgs = matches.opt_strs("cfg");
 
     let external_html = match ExternalHtml::load(
-            matches.opt_strs("html-in-header").as_slice(),
-            matches.opt_strs("html-before-content").as_slice(),
-            matches.opt_strs("html-after-content").as_slice()) {
+            &matches.opt_strs("html-in-header"),
+            &matches.opt_strs("html-before-content"),
+            &matches.opt_strs("html-after-content")) {
         Some(eh) => eh,
         None => return 3
     };
@@ -274,7 +274,7 @@ pub fn main_args(args: &[String]) -> int {
     };
     let Output { krate, json_plugins, passes, } = out;
     info!("going to format");
-    match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
+    match matches.opt_str("w").as_ref().map(|s| &**s) {
         Some("html") | None => {
             match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc")),
                                     passes.into_iter().collect()) {
@@ -303,7 +303,7 @@ pub fn main_args(args: &[String]) -> int {
 fn acquire_input(input: &str,
                  externs: core::Externs,
                  matches: &getopts::Matches) -> Result<Output, String> {
-    match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
+    match matches.opt_str("r").as_ref().map(|s| &**s) {
         Some("rust") => Ok(rust_input(input, externs, matches)),
         Some("json") => json_input(input),
         Some(s) => Err(format!("unknown input format: {}", s)),
@@ -357,7 +357,7 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche
     // First, parse the crate and extract all relevant information.
     let mut paths = SearchPaths::new();
     for s in &matches.opt_strs("L") {
-        paths.add_path(s.as_slice());
+        paths.add_path(s);
     }
     let cfgs = matches.opt_strs("cfg");
     let triple = matches.opt_str("target");
@@ -365,7 +365,7 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche
     let cr = Path::new(cratefile);
     info!("starting to run rustc");
 
-    let (mut krate, analysis) = std::thread::Thread::scoped(move |:| {
+    let (mut krate, analysis) = std::thread::Thread::scoped(move || {
         use rustc::session::config::Input;
 
         let cr = cr;
@@ -512,7 +512,7 @@ fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
     // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
     // straight to the Rust JSON representation.
     let crate_json_str = format!("{}", json::as_json(&krate));
-    let crate_json = match json::from_str(crate_json_str.as_slice()) {
+    let crate_json = match json::from_str(&crate_json_str) {
         Ok(j) => j,
         Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
     };
index 365fb78cfae63cecbcf7073000fae4f7d12bce5d..d64d9becc0c7c459f2ac2ebcb9e6132bc834bcb7 100644 (file)
@@ -49,7 +49,7 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches,
     let mut css = String::new();
     for name in &matches.opt_strs("markdown-css") {
         let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
-        css.push_str(s.as_slice())
+        css.push_str(&s)
     }
 
     let input_str = load_or_return!(input, 1, 2);
@@ -69,13 +69,13 @@ pub fn render(input: &str, mut output: Path, matches: &getopts::Matches,
         Ok(f) => f
     };
 
-    let (metadata, text) = extract_leading_metadata(input_str.as_slice());
+    let (metadata, text) = extract_leading_metadata(&input_str);
     if metadata.len() == 0 {
         let _ = writeln!(&mut old_io::stderr(),
                          "invalid markdown file: expecting initial line with `% ...TITLE...`");
         return 5;
     }
-    let title = metadata[0].as_slice();
+    let title = metadata[0];
 
     reset_headers();
 
@@ -141,8 +141,8 @@ pub fn test(input: &str, libs: SearchPaths, externs: core::Externs,
     let input_str = load_or_return!(input, 1, 2);
 
     let mut collector = Collector::new(input.to_string(), libs, externs, true);
-    find_testable_code(input_str.as_slice(), &mut collector);
+    find_testable_code(&input_str, &mut collector);
     test_args.insert(0, "rustdoctest".to_string());
-    testing::test_main(test_args.as_slice(), collector.tests);
+    testing::test_main(&test_args, collector.tests);
     0
 }
index e1c6bf1f4cfdd341322a65e128377234f0df2f99..4e023039de7c8de81fe265b627f6f03e322f0d34 100644 (file)
@@ -260,7 +260,7 @@ fn fold_item(&mut self, i: Item) -> Option<Item> {
                     &clean::NameValue(ref x, ref s)
                             if "doc" == *x => {
                         avec.push(clean::NameValue("doc".to_string(),
-                                                   unindent(s.as_slice())))
+                                                   unindent(s)))
                     }
                     x => avec.push(x.clone())
                 }
@@ -284,7 +284,7 @@ fn fold_item(&mut self, i: Item) -> Option<Item> {
                 match *attr {
                     clean::NameValue(ref x, ref s)
                             if "doc" == *x => {
-                        docstr.push_str(s.as_slice());
+                        docstr.push_str(s);
                         docstr.push('\n');
                     },
                     _ => ()
@@ -352,14 +352,14 @@ pub fn unindent(s: &str) -> String {
 
     if lines.len() >= 1 {
         let mut unindented = vec![ lines[0].trim().to_string() ];
-        unindented.push_all(lines.tail().iter().map(|&line| {
+        unindented.push_all(&lines.tail().iter().map(|&line| {
             if line.chars().all(|c| c.is_whitespace()) {
                 line.to_string()
             } else {
                 assert!(line.len() >= min_indent);
                 line[min_indent..].to_string()
             }
-        }).collect::<Vec<_>>().as_slice());
+        }).collect::<Vec<_>>());
         unindented.connect("\n")
     } else {
         s.to_string()
@@ -373,14 +373,14 @@ mod unindent_tests {
     #[test]
     fn should_unindent() {
         let s = "    line1\n    line2".to_string();
-        let r = unindent(s.as_slice());
+        let r = unindent(&s);
         assert_eq!(r, "line1\nline2");
     }
 
     #[test]
     fn should_unindent_multiple_paragraphs() {
         let s = "    line1\n\n    line2".to_string();
-        let r = unindent(s.as_slice());
+        let r = unindent(&s);
         assert_eq!(r, "line1\n\nline2");
     }
 
@@ -389,7 +389,7 @@ fn should_leave_multiple_indent_levels() {
         // Line 2 is indented another level beyond the
         // base indentation and should be preserved
         let s = "    line1\n\n        line2".to_string();
-        let r = unindent(s.as_slice());
+        let r = unindent(&s);
         assert_eq!(r, "line1\n\n    line2");
     }
 
@@ -401,14 +401,14 @@ fn should_ignore_first_line_indent() {
         // #[doc = "Start way over here
         //          and continue here"]
         let s = "line1\n    line2".to_string();
-        let r = unindent(s.as_slice());
+        let r = unindent(&s);
         assert_eq!(r, "line1\nline2");
     }
 
     #[test]
     fn should_not_ignore_first_line_indent_in_a_single_line_para() {
         let s = "line1\n\n    line2".to_string();
-        let r = unindent(s.as_slice());
+        let r = unindent(&s);
         assert_eq!(r, "line1\n\n    line2");
     }
 }
index a2afba091f4a1f8aaf3ffc4248ac73741f14585c..b65b2841aa0e5ce0ad6c874b17288fcef9a70057 100644 (file)
@@ -88,7 +88,7 @@ fn libname(mut n: String) -> String {
 #[cfg(all(not(target_os="windows"), not(target_os="macos")))]
 fn libname(n: String) -> String {
     let mut i = String::from_str("lib");
-    i.push_str(n.as_slice());
+    i.push_str(&n);
     i.push_str(".so");
     i
 }
index 29abea009e547f2580a9b2a9e76d804ac06c9e33..e43c3a6da3ac70893479bb7bbcb86698eae4b32e 100644 (file)
@@ -21,9 +21,9 @@
 use std::collections::{HashSet, HashMap};
 use testing;
 use rustc::session::{self, config};
+use rustc::session::config::get_unstable_features_setting;
 use rustc::session::search_paths::{SearchPaths, PathKind};
-use rustc_driver::get_unstable_features_setting;
-use rustc_driver::driver;
+use rustc_driver::{driver, Compilation};
 use syntax::ast;
 use syntax::codemap::{CodeMap, dummy_spanned};
 use syntax::diagnostic;
@@ -68,7 +68,7 @@ pub fn run(input: &str,
 
     let mut cfg = config::build_configuration(&sess);
     cfg.extend(cfgs.into_iter().map(|cfg_| {
-        let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
+        let cfg_ = token::intern_and_get_ident(&cfg_);
         P(dummy_spanned(ast::MetaWord(cfg_)))
     }));
     let krate = driver::phase_1_parse_input(&sess, cfg, &input);
@@ -105,7 +105,7 @@ pub fn run(input: &str,
 
     test_args.insert(0, "rustdoctest".to_string());
 
-    testing::test_main(test_args.as_slice(),
+    testing::test_main(&test_args,
                        collector.tests.into_iter().collect());
     0
 }
@@ -148,7 +148,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths,
     let w1 = old_io::ChanWriter::new(tx);
     let w2 = w1.clone();
     let old = old_io::stdio::set_stderr(box w1);
-    Thread::spawn(move |:| {
+    Thread::spawn(move || {
         let mut p = old_io::ChanReader::new(rx);
         let mut err = match old {
             Some(old) => {
@@ -178,7 +178,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths,
     let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
     let mut control = driver::CompileController::basic();
     if no_run {
-        control.after_analysis.stop = true;
+        control.after_analysis.stop = Compilation::Stop;
     }
     driver::compile_input(sess, cfg, &input, &out, &None, None, control);
 
@@ -194,9 +194,9 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths,
     let newpath = {
         let mut path = DynamicLibrary::search_path();
         path.insert(0, libdir.clone());
-        DynamicLibrary::create_path(path.as_slice())
+        DynamicLibrary::create_path(&path)
     };
-    cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
+    cmd.env(DynamicLibrary::envvar(), newpath);
 
     match cmd.output() {
         Err(e) => panic!("couldn't run the test: {}{}", e,
@@ -208,7 +208,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths,
                 panic!("test executable succeeded when it should have failed");
             } else if !should_fail && !out.status.success() {
                 panic!("test executable failed:\n{:?}",
-                      str::from_utf8(out.error.as_slice()));
+                      str::from_utf8(&out.error));
             }
         }
     }
@@ -228,8 +228,8 @@ pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main:
         match cratename {
             Some(cratename) => {
                 if s.contains(cratename) {
-                    prog.push_str(format!("extern crate {};\n",
-                                          cratename).as_slice());
+                    prog.push_str(&format!("extern crate {};\n",
+                                           cratename));
                 }
             }
             None => {}
@@ -239,7 +239,7 @@ pub fn maketest(s: &str, cratename: Option<&str>, lints: bool, dont_insert_main:
         prog.push_str(s);
     } else {
         prog.push_str("fn main() {\n    ");
-        prog.push_str(s.replace("\n", "\n    ").as_slice());
+        prog.push_str(&s.replace("\n", "\n    "));
         prog.push_str("\n}");
     }
 
@@ -275,7 +275,7 @@ pub fn new(cratename: String, libs: SearchPaths, externs: core::Externs,
     pub fn add_test(&mut self, test: String,
                     should_fail: bool, no_run: bool, should_ignore: bool, as_test_harness: bool) {
         let name = if self.use_headers {
-            let s = self.current_header.as_ref().map(|s| s.as_slice()).unwrap_or("");
+            let s = self.current_header.as_ref().map(|s| &**s).unwrap_or("");
             format!("{}_{}", s, self.cnt)
         } else {
             format!("{}_{}", self.names.connect("::"), self.cnt)
@@ -292,8 +292,8 @@ pub fn add_test(&mut self, test: String,
                 should_fail: testing::ShouldFail::No, // compiler failures are test failures
             },
             testfn: testing::DynTestFn(Thunk::new(move|| {
-                runtest(test.as_slice(),
-                        cratename.as_slice(),
+                runtest(&test,
+                        &cratename,
                         libs,
                         externs,
                         should_fail,
index 5bcda778cbbb0d4284a3c924be7f4015985198f0..ac1a02854124afda82d3183550ebd9e7c63a6933 100644 (file)
@@ -237,7 +237,7 @@ pub fn visit_item(&mut self, item: &ast::Item,
             ast::ItemExternCrate(ref p) => {
                 let path = match *p {
                     None => None,
-                    Some((ref x, _)) => Some(x.get().to_string()),
+                    Some((ref x, _)) => Some(x.to_string()),
                 };
                 om.extern_crates.push(ExternCrate {
                     name: name,
@@ -253,7 +253,7 @@ pub fn visit_item(&mut self, item: &ast::Item,
                     let please_inline = item.attrs.iter().any(|item| {
                         match item.meta_item_list() {
                             Some(list) => {
-                                list.iter().any(|i| i.name().get() == "inline")
+                                list.iter().any(|i| &i.name()[] == "inline")
                             }
                             None => false,
                         }
index be7abfe6aca3b7a8038fdac57c4590877c1684b6..53d3b069467d348e6ecc76c9509641758c944d52 100644 (file)
@@ -136,7 +136,7 @@ impl<
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
         let mut bits = 0;
         for item in self {
-            bits |= item.to_uint();
+            bits |= item.to_usize();
         }
         s.emit_uint(bits)
     }
@@ -150,7 +150,7 @@ fn decode<D: Decoder>(d: &mut D) -> Result<EnumSet<T>, D::Error> {
         let mut set = EnumSet::new();
         for bit in 0..uint::BITS {
             if bits & (1 << bit) != 0 {
-                set.insert(CLike::from_uint(1 << bit));
+                set.insert(CLike::from_usize(1 << bit));
             }
         }
         Ok(set)
index 4f62cca3c68c285fe1c70ff190c8cfe5cba1c6a5..b8383577987539a03e281c9c21b9179472074748 100644 (file)
@@ -2061,7 +2061,7 @@ pub fn from_reader(rdr: &mut old_io::Reader) -> Result<Json, BuilderError> {
         Ok(c)  => c,
         Err(e) => return Err(io_error_to_error(e))
     };
-    let s = match str::from_utf8(contents.as_slice()).ok() {
+    let s = match str::from_utf8(&contents).ok() {
         Some(s) => s,
         _       => return Err(SyntaxError(NotUtf8, 0, 0))
     };
@@ -3550,7 +3550,7 @@ enum Enum {
         map.insert(Enum::Foo, 0);
         let result = json::encode(&map).unwrap();
         assert_eq!(&result[], r#"{"Foo":0}"#);
-        let decoded: HashMap<Enum, _> = json::decode(result.as_slice()).unwrap();
+        let decoded: HashMap<Enum, _> = json::decode(&result).unwrap();
         assert_eq!(map, decoded);
     }
 
@@ -3591,7 +3591,7 @@ fn assert_stream_equal(src: &str,
                 None => { break; }
             };
             let (ref expected_evt, ref expected_stack) = expected[i];
-            if !parser.stack().is_equal_to(expected_stack.as_slice()) {
+            if !parser.stack().is_equal_to(expected_stack) {
                 panic!("Parser stack is not equal to {:?}", expected_stack);
             }
             assert_eq!(&evt, expected_evt);
@@ -4022,6 +4022,6 @@ fn bench_streaming_large(b: &mut Bencher) {
     #[bench]
     fn bench_large(b: &mut Bencher) {
         let src = big_json();
-        b.iter( || { let _ = from_str(src.as_slice()); });
+        b.iter( || { let _ = from_str(&src); });
     }
 }
index 274c669d8dfc2ce902dafc027b35275a7006a6fd..892747e79ed45e80b7509b357920d24c688972af 100644 (file)
@@ -421,7 +421,7 @@ fn test_eq_ignore_ascii_case() {
             let lower = if 'A' as u32 <= c && c <= 'Z' as u32 { c + 'a' as u32 - 'A' as u32 }
                         else { c };
             assert!((from_u32(i).unwrap()).to_string().eq_ignore_ascii_case(
-                    (from_u32(lower).unwrap()).to_string().as_slice()));
+                    &from_u32(lower).unwrap().to_string()));
             i += 1;
         }
     }
index ce02648b8f29d884a389185115f02e46302cc362..ca506e8c36f50a7111063c15c152eacd226f25e1 100644 (file)
@@ -21,7 +21,7 @@ fn new_drop(b : &mut Bencher) {
     use super::map::HashMap;
 
     b.iter(|| {
-        let m : HashMap<int, int> = HashMap::new();
+        let m : HashMap<i32, i32> = HashMap::new();
         assert_eq!(m.len(), 0);
     })
 }
index 63270610472485cc708a04200fd758aa3f180919..710f021d9125e6205e1149d2fe8ccc12da1ff697 100644 (file)
@@ -45,9 +45,9 @@
 };
 use super::state::HashState;
 
-const INITIAL_LOG2_CAP: uint = 5;
+const INITIAL_LOG2_CAP: usize = 5;
 #[unstable(feature = "std_misc")]
-pub const INITIAL_CAPACITY: uint = 1 << INITIAL_LOG2_CAP; // 2^5
+pub const INITIAL_CAPACITY: usize = 1 << INITIAL_LOG2_CAP; // 2^5
 
 /// The default behavior of HashMap implements a load factor of 90.9%.
 /// This behavior is characterized by the following condition:
@@ -62,7 +62,7 @@ fn new() -> DefaultResizePolicy {
     }
 
     #[inline]
-    fn min_capacity(&self, usable_size: uint) -> uint {
+    fn min_capacity(&self, usable_size: usize) -> usize {
         // Here, we are rephrasing the logic by specifying the lower limit
         // on capacity:
         //
@@ -72,7 +72,7 @@ fn min_capacity(&self, usable_size: uint) -> uint {
 
     /// An inverse of `min_capacity`, approximately.
     #[inline]
-    fn usable_capacity(&self, cap: uint) -> uint {
+    fn usable_capacity(&self, cap: usize) -> usize {
         // As the number of entries approaches usable capacity,
         // min_capacity(size) must be smaller than the internal capacity,
         // so that the map is not resized:
@@ -90,7 +90,7 @@ fn usable_capacity(&self, cap: uint) -> uint {
 fn test_resize_policy() {
     use prelude::v1::*;
     let rp = DefaultResizePolicy;
-    for n in 0u..1000 {
+    for n in 0..1000 {
         assert!(rp.min_capacity(rp.usable_capacity(n)) <= n);
         assert!(rp.usable_capacity(rp.min_capacity(n)) <= n);
     }
@@ -287,9 +287,9 @@ fn test_resize_policy() {
 /// // Use a HashMap to store the vikings' health points.
 /// let mut vikings = HashMap::new();
 ///
-/// vikings.insert(Viking::new("Einar", "Norway"), 25u);
-/// vikings.insert(Viking::new("Olaf", "Denmark"), 24u);
-/// vikings.insert(Viking::new("Harald", "Iceland"), 12u);
+/// vikings.insert(Viking::new("Einar", "Norway"), 25);
+/// vikings.insert(Viking::new("Olaf", "Denmark"), 24);
+/// vikings.insert(Viking::new("Harald", "Iceland"), 12);
 ///
 /// // Use derived implementation to print the status of the vikings.
 /// for (viking, health) in vikings.iter() {
@@ -369,7 +369,7 @@ fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V) {
 ///
 /// `hash`, `k`, and `v` are the elements to "robin hood" into the hashtable.
 fn robin_hood<'a, K: 'a, V: 'a>(mut bucket: FullBucketMut<'a, K, V>,
-                        mut ib: uint,
+                        mut ib: usize,
                         mut hash: SafeHash,
                         mut k: K,
                         mut v: V)
@@ -515,7 +515,7 @@ pub fn new() -> HashMap<K, V, RandomState> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(capacity: uint) -> HashMap<K, V, RandomState> {
+    pub fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState> {
         HashMap::with_capacity_and_hash_state(capacity, Default::default())
     }
 }
@@ -537,7 +537,7 @@ impl<K, V, S, H> HashMap<K, V, S>
     ///
     /// let s = RandomState::new();
     /// let mut map = HashMap::with_hash_state(s);
-    /// map.insert(1, 2u);
+    /// map.insert(1, 2);
     /// ```
     #[inline]
     #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
@@ -565,11 +565,11 @@ pub fn with_hash_state(hash_state: S) -> HashMap<K, V, S> {
     ///
     /// let s = RandomState::new();
     /// let mut map = HashMap::with_capacity_and_hash_state(10, s);
-    /// map.insert(1, 2u);
+    /// map.insert(1, 2);
     /// ```
     #[inline]
     #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
-    pub fn with_capacity_and_hash_state(capacity: uint, hash_state: S)
+    pub fn with_capacity_and_hash_state(capacity: usize, hash_state: S)
                                         -> HashMap<K, V, S> {
         let resize_policy = DefaultResizePolicy::new();
         let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity));
@@ -593,7 +593,7 @@ pub fn with_capacity_and_hash_state(capacity: uint, hash_state: S)
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint {
+    pub fn capacity(&self) -> usize {
         self.resize_policy.usable_capacity(self.table.capacity())
     }
 
@@ -603,7 +603,7 @@ pub fn capacity(&self) -> uint {
     ///
     /// # Panics
     ///
-    /// Panics if the new allocation size overflows `uint`.
+    /// Panics if the new allocation size overflows `usize`.
     ///
     /// # Example
     ///
@@ -613,7 +613,7 @@ pub fn capacity(&self) -> uint {
     /// map.reserve(10);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve(&mut self, additional: uint) {
+    pub fn reserve(&mut self, additional: usize) {
         let new_size = self.len().checked_add(additional).expect("capacity overflow");
         let min_cap = self.resize_policy.min_capacity(new_size);
 
@@ -631,7 +631,7 @@ pub fn reserve(&mut self, additional: uint) {
     ///   1) Make sure the new capacity is enough for all the elements, accounting
     ///      for the load factor.
     ///   2) Ensure new_capacity is a power of two or zero.
-    fn resize(&mut self, new_capacity: uint) {
+    fn resize(&mut self, new_capacity: usize) {
         assert!(self.table.size() <= new_capacity);
         assert!(new_capacity.is_power_of_two() || new_capacity == 0);
 
@@ -793,7 +793,7 @@ fn insert_or_replace_with<'a, F>(&'a mut self,
 
             if (ib as int) < robin_ib {
                 // Found a luckier bucket than me. Better steal his spot.
-                return robin_hood(bucket, robin_ib as uint, hash, k, v);
+                return robin_hood(bucket, robin_ib as usize, hash, k, v);
             }
 
             probe = bucket.next();
@@ -929,10 +929,8 @@ fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
     }
 
     /// Gets the given key's corresponding entry in the map for in-place manipulation.
-    #[unstable(feature = "std_misc",
-               reason = "precise API still being fleshed out")]
-    pub fn entry<'a>(&'a mut self, key: K) -> Entry<'a, K, V>
-    {
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub fn entry(&mut self, key: K) -> Entry<K, V> {
         // Gotta resize now.
         self.reserve(1);
 
@@ -949,11 +947,11 @@ pub fn entry<'a>(&'a mut self, key: K) -> Entry<'a, K, V>
     ///
     /// let mut a = HashMap::new();
     /// assert_eq!(a.len(), 0);
-    /// a.insert(1u, "a");
+    /// a.insert(1, "a");
     /// assert_eq!(a.len(), 1);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { self.table.size() }
+    pub fn len(&self) -> usize { self.table.size() }
 
     /// Returns true if the map contains no elements.
     ///
@@ -964,7 +962,7 @@ pub fn len(&self) -> uint { self.table.size() }
     ///
     /// let mut a = HashMap::new();
     /// assert!(a.is_empty());
-    /// a.insert(1u, "a");
+    /// a.insert(1, "a");
     /// assert!(!a.is_empty());
     /// ```
     #[inline]
@@ -980,8 +978,8 @@ pub fn is_empty(&self) -> bool { self.len() == 0 }
     /// use std::collections::HashMap;
     ///
     /// let mut a = HashMap::new();
-    /// a.insert(1u, "a");
-    /// a.insert(2u, "b");
+    /// a.insert(1, "a");
+    /// a.insert(2, "b");
     ///
     /// for (k, v) in a.drain().take(1) {
     ///     assert!(k == 1 || k == 2);
@@ -1011,7 +1009,7 @@ fn last_two<A, B, C>((_, b, c): (A, B, C)) -> (B, C) { (b, c) }
     /// use std::collections::HashMap;
     ///
     /// let mut a = HashMap::new();
-    /// a.insert(1u, "a");
+    /// a.insert(1, "a");
     /// a.clear();
     /// assert!(a.is_empty());
     /// ```
@@ -1033,7 +1031,7 @@ pub fn clear(&mut self) {
     /// use std::collections::HashMap;
     ///
     /// let mut map = HashMap::new();
-    /// map.insert(1u, "a");
+    /// map.insert(1, "a");
     /// assert_eq!(map.get(&1), Some(&"a"));
     /// assert_eq!(map.get(&2), None);
     /// ```
@@ -1056,7 +1054,7 @@ pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
     /// use std::collections::HashMap;
     ///
     /// let mut map = HashMap::new();
-    /// map.insert(1u, "a");
+    /// map.insert(1, "a");
     /// assert_eq!(map.contains_key(&1), true);
     /// assert_eq!(map.contains_key(&2), false);
     /// ```
@@ -1079,7 +1077,7 @@ pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
     /// use std::collections::HashMap;
     ///
     /// let mut map = HashMap::new();
-    /// map.insert(1u, "a");
+    /// map.insert(1, "a");
     /// match map.get_mut(&1) {
     ///     Some(x) => *x = "b",
     ///     None => (),
@@ -1102,7 +1100,7 @@ pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
     /// use std::collections::HashMap;
     ///
     /// let mut map = HashMap::new();
-    /// assert_eq!(map.insert(37u, "a"), None);
+    /// assert_eq!(map.insert(37, "a"), None);
     /// assert_eq!(map.is_empty(), false);
     ///
     /// map.insert(37, "b");
@@ -1134,7 +1132,7 @@ pub fn insert(&mut self, k: K, v: V) -> Option<V> {
     /// use std::collections::HashMap;
     ///
     /// let mut map = HashMap::new();
-    /// map.insert(1u, "a");
+    /// map.insert(1, "a");
     /// assert_eq!(map.remove(&1), Some("a"));
     /// assert_eq!(map.remove(&1), None);
     /// ```
@@ -1188,7 +1186,7 @@ fn search_entry_hashed<'a, K: Eq, V>(table: &'a mut RawTable<K,V>, hash: SafeHas
             return Vacant(VacantEntry {
                 hash: hash,
                 key: k,
-                elem: NeqElem(bucket, robin_ib as uint),
+                elem: NeqElem(bucket, robin_ib as usize),
             });
         }
 
@@ -1269,8 +1267,6 @@ impl<K, V, S, H, Q: ?Sized> IndexMut<Q> for HashMap<K, V, S>
           S: HashState<Hasher=H>,
           H: hash::Hasher<Output=u64>
 {
-    type Output = V;
-
     #[inline]
     fn index_mut<'a>(&'a mut self, index: &Q) -> &'a mut V {
         self.get_mut(index).expect("no entry found for key")
@@ -1371,7 +1367,7 @@ pub enum Entry<'a, K: 'a, V: 'a> {
 enum VacantEntryState<K, V, M> {
     /// The index is occupied, but the key to insert has precedence,
     /// and will kick the current one out on insertion.
-    NeqElem(FullBucket<K, V, M>, uint),
+    NeqElem(FullBucket<K, V, M>, usize),
     /// The index is genuinely vacant.
     NoElem(EmptyBucket<K, V, M>),
 }
@@ -1496,26 +1492,28 @@ pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, K, V>> {
     }
 }
 
-#[unstable(feature = "std_misc",
-           reason = "matches collection reform v2 specification, waiting for dust to settle")]
 impl<'a, K, V> OccupiedEntry<'a, K, V> {
     /// Gets a reference to the value in the entry.
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn get(&self) -> &V {
         self.elem.read().1
     }
 
     /// Gets a mutable reference to the value in the entry.
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn get_mut(&mut self) -> &mut V {
         self.elem.read_mut().1
     }
 
     /// Converts the OccupiedEntry into a mutable reference to the value in the entry
     /// with a lifetime bound to the map itself
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn into_mut(self) -> &'a mut V {
         self.elem.into_mut_refs().1
     }
 
     /// Sets the value of the entry, and returns the entry's old value
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn insert(&mut self, mut value: V) -> V {
         let old_value = self.get_mut();
         mem::swap(&mut value, old_value);
@@ -1523,16 +1521,16 @@ pub fn insert(&mut self, mut value: V) -> V {
     }
 
     /// Takes the value out of the entry, and returns it
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn remove(self) -> V {
         pop_internal(self.elem).1
     }
 }
 
-#[unstable(feature = "std_misc",
-           reason = "matches collection reform v2 specification, waiting for dust to settle")]
 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
     /// Sets the value of the entry with the VacantEntry's key,
     /// and returns a mutable reference to it
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub fn insert(self, value: V) -> &'a mut V {
         match self.elem {
             NeqElem(bucket, ib) => {
@@ -1580,7 +1578,6 @@ fn extend<T: Iterator<Item=(K, V)>>(&mut self, iter: T) {
 /// `Hasher`, but the hashers created by two different `RandomState`
 /// instances are unlikely to produce the same result for the same values.
 #[derive(Clone)]
-#[allow(missing_copy_implementations)]
 #[unstable(feature = "std_misc",
            reason = "hashing an hash maps may be altered")]
 pub struct RandomState {
@@ -1623,7 +1620,6 @@ fn default() -> RandomState {
 /// This is the default hasher used in a `HashMap` to hash keys. Types do not
 /// typically declare an ability to explicitly hash into this particular type,
 /// but rather in a `H: hash::Writer` type parameter.
-#[allow(missing_copy_implementations)]
 #[unstable(feature = "std_misc",
            reason = "hashing an hash maps may be altered")]
 pub struct Hasher { inner: SipHasher }
@@ -1674,11 +1670,11 @@ fn test_insert() {
 
     #[derive(Hash, PartialEq, Eq)]
     struct Dropable {
-        k: uint
+        k: usize
     }
 
     impl Dropable {
-        fn new(k: uint) -> Dropable {
+        fn new(k: usize) -> Dropable {
             DROP_VECTOR.with(|slot| {
                 slot.borrow_mut()[k] += 1;
             });
@@ -1711,24 +1707,24 @@ fn test_drops() {
             let mut m = HashMap::new();
 
             DROP_VECTOR.with(|v| {
-                for i in 0u..200 {
+                for i in 0..200 {
                     assert_eq!(v.borrow()[i], 0);
                 }
             });
 
-            for i in 0u..100 {
+            for i in 0..100 {
                 let d1 = Dropable::new(i);
                 let d2 = Dropable::new(i+100);
                 m.insert(d1, d2);
             }
 
             DROP_VECTOR.with(|v| {
-                for i in 0u..200 {
+                for i in 0..200 {
                     assert_eq!(v.borrow()[i], 1);
                 }
             });
 
-            for i in 0u..50 {
+            for i in 0..50 {
                 let k = Dropable::new(i);
                 let v = m.remove(&k);
 
@@ -1741,12 +1737,12 @@ fn test_drops() {
             }
 
             DROP_VECTOR.with(|v| {
-                for i in 0u..50 {
+                for i in 0..50 {
                     assert_eq!(v.borrow()[i], 0);
                     assert_eq!(v.borrow()[i+100], 0);
                 }
 
-                for i in 50u..100 {
+                for i in 50..100 {
                     assert_eq!(v.borrow()[i], 1);
                     assert_eq!(v.borrow()[i+100], 1);
                 }
@@ -1754,7 +1750,7 @@ fn test_drops() {
         }
 
         DROP_VECTOR.with(|v| {
-            for i in 0u..200 {
+            for i in 0..200 {
                 assert_eq!(v.borrow()[i], 0);
             }
         });
@@ -1770,19 +1766,19 @@ fn test_move_iter_drops() {
             let mut hm = HashMap::new();
 
             DROP_VECTOR.with(|v| {
-                for i in 0u..200 {
+                for i in 0..200 {
                     assert_eq!(v.borrow()[i], 0);
                 }
             });
 
-            for i in 0u..100 {
+            for i in 0..100 {
                 let d1 = Dropable::new(i);
                 let d2 = Dropable::new(i+100);
                 hm.insert(d1, d2);
             }
 
             DROP_VECTOR.with(|v| {
-                for i in 0u..200 {
+                for i in 0..200 {
                     assert_eq!(v.borrow()[i], 1);
                 }
             });
@@ -1797,7 +1793,7 @@ fn test_move_iter_drops() {
             let mut half = hm.into_iter().take(50);
 
             DROP_VECTOR.with(|v| {
-                for i in 0u..200 {
+                for i in 0..200 {
                     assert_eq!(v.borrow()[i], 1);
                 }
             });
@@ -1805,11 +1801,11 @@ fn test_move_iter_drops() {
             for _ in half.by_ref() {}
 
             DROP_VECTOR.with(|v| {
-                let nk = (0u..100).filter(|&i| {
+                let nk = (0..100).filter(|&i| {
                     v.borrow()[i] == 1
                 }).count();
 
-                let nv = (0u..100).filter(|&i| {
+                let nv = (0..100).filter(|&i| {
                     v.borrow()[i+100] == 1
                 }).count();
 
@@ -1819,7 +1815,7 @@ fn test_move_iter_drops() {
         };
 
         DROP_VECTOR.with(|v| {
-            for i in 0u..200 {
+            for i in 0..200 {
                 assert_eq!(v.borrow()[i], 0);
             }
         });
@@ -1964,7 +1960,7 @@ fn test_pop() {
     #[test]
     fn test_iterate() {
         let mut m = HashMap::with_capacity(4);
-        for i in 0u..32 {
+        for i in 0..32 {
             assert!(m.insert(i, i*2).is_none());
         }
         assert_eq!(m.len(), 32);
@@ -1981,8 +1977,8 @@ fn test_iterate() {
     #[test]
     fn test_keys() {
         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
-        let map = vec.into_iter().collect::<HashMap<int, char>>();
-        let keys = map.keys().map(|&k| k).collect::<Vec<int>>();
+        let map: HashMap<_, _> = vec.into_iter().collect();
+        let keys: Vec<_> = map.keys().cloned().collect();
         assert_eq!(keys.len(), 3);
         assert!(keys.contains(&1));
         assert!(keys.contains(&2));
@@ -1992,8 +1988,8 @@ fn test_keys() {
     #[test]
     fn test_values() {
         let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
-        let map = vec.into_iter().collect::<HashMap<int, char>>();
-        let values = map.values().map(|&v| v).collect::<Vec<char>>();
+        let map: HashMap<_, _> = vec.into_iter().collect();
+        let values: Vec<_> = map.values().cloned().collect();
         assert_eq!(values.len(), 3);
         assert!(values.contains(&'a'));
         assert!(values.contains(&'b'));
@@ -2031,8 +2027,8 @@ fn test_eq() {
 
     #[test]
     fn test_show() {
-        let mut map: HashMap<int, int> = HashMap::new();
-        let empty: HashMap<int, int> = HashMap::new();
+        let mut map = HashMap::new();
+        let empty: HashMap<i32, i32> = HashMap::new();
 
         map.insert(1, 2);
         map.insert(3, 4);
@@ -2051,7 +2047,7 @@ fn test_expand() {
         assert_eq!(m.len(), 0);
         assert!(m.is_empty());
 
-        let mut i = 0u;
+        let mut i = 0;
         let old_cap = m.table.capacity();
         while old_cap == m.table.capacity() {
             m.insert(i, i);
@@ -2079,7 +2075,7 @@ fn test_behavior_resize_policy() {
 
         assert_eq!(cap, initial_cap * 2);
 
-        let mut i = 0u;
+        let mut i = 0;
         for _ in 0..cap * 3 / 4 {
             m.insert(i, i);
             i += 1;
@@ -2121,21 +2117,21 @@ fn test_behavior_resize_policy() {
     #[test]
     fn test_reserve_shrink_to_fit() {
         let mut m = HashMap::new();
-        m.insert(0u, 0u);
+        m.insert(0, 0);
         m.remove(&0);
         assert!(m.capacity() >= m.len());
-        for i in 0us..128 {
+        for i in 0..128 {
             m.insert(i, i);
         }
         m.reserve(256);
 
         let usable_cap = m.capacity();
-        for i in 128us..128+256 {
+        for i in 128..(128 + 256) {
             m.insert(i, i);
             assert_eq!(m.capacity(), usable_cap);
         }
 
-        for i in 100us..128+256 {
+        for i in 100..(128 + 256) {
             assert_eq!(m.remove(&i), Some(i));
         }
         m.shrink_to_fit();
@@ -2144,7 +2140,7 @@ fn test_reserve_shrink_to_fit() {
         assert!(!m.is_empty());
         assert!(m.capacity() >= m.len());
 
-        for i in 0us..100 {
+        for i in 0..100 {
             assert_eq!(m.remove(&i), Some(i));
         }
         m.shrink_to_fit();
@@ -2159,7 +2155,7 @@ fn test_reserve_shrink_to_fit() {
     fn test_from_iter() {
         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
 
-        let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
+        let map: HashMap<_, _> = xs.iter().cloned().collect();
 
         for &(k, v) in &xs {
             assert_eq!(map.get(&k), Some(&v));
@@ -2170,7 +2166,7 @@ fn test_from_iter() {
     fn test_size_hint() {
         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
 
-        let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
+        let map: HashMap<_, _>  = xs.iter().cloned().collect();
 
         let mut iter = map.iter();
 
@@ -2183,7 +2179,7 @@ fn test_size_hint() {
     fn test_iter_len() {
         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
 
-        let map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
+        let map: HashMap<_, _>  = xs.iter().cloned().collect();
 
         let mut iter = map.iter();
 
@@ -2196,7 +2192,7 @@ fn test_iter_len() {
     fn test_mut_size_hint() {
         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
 
-        let mut map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
+        let mut map: HashMap<_, _>  = xs.iter().cloned().collect();
 
         let mut iter = map.iter_mut();
 
@@ -2209,7 +2205,7 @@ fn test_mut_size_hint() {
     fn test_iter_mut_len() {
         let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];
 
-        let mut map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
+        let mut map: HashMap<_, _>  = xs.iter().cloned().collect();
 
         let mut iter = map.iter_mut();
 
@@ -2220,7 +2216,7 @@ fn test_iter_mut_len() {
 
     #[test]
     fn test_index() {
-        let mut map: HashMap<int, int> = HashMap::new();
+        let mut map = HashMap::new();
 
         map.insert(1, 2);
         map.insert(2, 1);
@@ -2232,7 +2228,7 @@ fn test_index() {
     #[test]
     #[should_fail]
     fn test_index_nonexistent() {
-        let mut map: HashMap<int, int> = HashMap::new();
+        let mut map = HashMap::new();
 
         map.insert(1, 2);
         map.insert(2, 1);
@@ -2245,7 +2241,7 @@ fn test_index_nonexistent() {
     fn test_entry(){
         let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];
 
-        let mut map: HashMap<int, int> = xs.iter().map(|&x| x).collect();
+        let mut map: HashMap<_, _> = xs.iter().cloned().collect();
 
         // Existing key (insert)
         match map.entry(1) {
@@ -2296,7 +2292,7 @@ fn test_entry(){
     #[test]
     fn test_entry_take_doesnt_corrupt() {
         // Test for #19292
-        fn check(m: &HashMap<int, ()>) {
+        fn check(m: &HashMap<isize, ()>) {
             for k in m.keys() {
                 assert!(m.contains_key(k),
                         "{} is in keys() but not in the map?", k);
@@ -2307,12 +2303,12 @@ fn check(m: &HashMap<int, ()>) {
         let mut rng = weak_rng();
 
         // Populate the map with some items.
-        for _ in 0u..50 {
+        for _ in 0..50 {
             let x = rng.gen_range(-10, 10);
             m.insert(x, ());
         }
 
-        for i in 0u..1000 {
+        for i in 0..1000 {
             let x = rng.gen_range(-10, 10);
             match m.entry(x) {
                 Vacant(_) => {},
index f5877e1dd99d8e6fcb62f3ed608bd598a69af076..e40f17f29e804d898c95390874922f788afe0c35 100644 (file)
 /// #[derive(Hash, Eq, PartialEq, Debug)]
 /// struct Viking<'a> {
 ///     name: &'a str,
-///     power: uint,
+///     power: usize,
 /// }
 ///
 /// let mut vikings = HashSet::new();
 ///
-/// vikings.insert(Viking { name: "Einar", power: 9u });
-/// vikings.insert(Viking { name: "Einar", power: 9u });
-/// vikings.insert(Viking { name: "Olaf", power: 4u });
-/// vikings.insert(Viking { name: "Harald", power: 8u });
+/// vikings.insert(Viking { name: "Einar", power: 9 });
+/// vikings.insert(Viking { name: "Einar", power: 9 });
+/// vikings.insert(Viking { name: "Olaf", power: 4 });
+/// vikings.insert(Viking { name: "Harald", power: 8 });
 ///
 /// // Use derived implementation to print the vikings.
 /// for x in vikings.iter() {
@@ -123,7 +123,7 @@ pub fn new() -> HashSet<T, RandomState> {
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn with_capacity(capacity: uint) -> HashSet<T, RandomState> {
+    pub fn with_capacity(capacity: usize) -> HashSet<T, RandomState> {
         HashSet { map: HashMap::with_capacity(capacity) }
     }
 }
@@ -146,7 +146,7 @@ impl<T, S, H> HashSet<T, S>
     ///
     /// let s = RandomState::new();
     /// let mut set = HashSet::with_hash_state(s);
-    /// set.insert(2u);
+    /// set.insert(2);
     /// ```
     #[inline]
     #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
@@ -169,12 +169,12 @@ pub fn with_hash_state(hash_state: S) -> HashSet<T, S> {
     /// use std::collections::hash_map::RandomState;
     ///
     /// let s = RandomState::new();
-    /// let mut set = HashSet::with_capacity_and_hash_state(10u, s);
+    /// let mut set = HashSet::with_capacity_and_hash_state(10, s);
     /// set.insert(1);
     /// ```
     #[inline]
     #[unstable(feature = "std_misc", reason = "hasher stuff is unclear")]
-    pub fn with_capacity_and_hash_state(capacity: uint, hash_state: S)
+    pub fn with_capacity_and_hash_state(capacity: usize, hash_state: S)
                                         -> HashSet<T, S> {
         HashSet {
             map: HashMap::with_capacity_and_hash_state(capacity, hash_state),
@@ -192,7 +192,7 @@ pub fn with_capacity_and_hash_state(capacity: uint, hash_state: S)
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn capacity(&self) -> uint {
+    pub fn capacity(&self) -> usize {
         self.map.capacity()
     }
 
@@ -202,7 +202,7 @@ pub fn capacity(&self) -> uint {
     ///
     /// # Panics
     ///
-    /// Panics if the new allocation size overflows `uint`.
+    /// Panics if the new allocation size overflows `usize`.
     ///
     /// # Example
     ///
@@ -212,7 +212,7 @@ pub fn capacity(&self) -> uint {
     /// set.reserve(10);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn reserve(&mut self, additional: uint) {
+    pub fn reserve(&mut self, additional: usize) {
         self.map.reserve(additional)
     }
 
@@ -398,11 +398,11 @@ pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
     ///
     /// let mut v = HashSet::new();
     /// assert_eq!(v.len(), 0);
-    /// v.insert(1u);
+    /// v.insert(1);
     /// assert_eq!(v.len(), 1);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> uint { self.map.len() }
+    pub fn len(&self) -> usize { self.map.len() }
 
     /// Returns true if the set contains no elements
     ///
@@ -413,7 +413,7 @@ pub fn len(&self) -> uint { self.map.len() }
     ///
     /// let mut v = HashSet::new();
     /// assert!(v.is_empty());
-    /// v.insert(1u);
+    /// v.insert(1);
     /// assert!(!v.is_empty());
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
@@ -438,7 +438,7 @@ fn first<A, B>((a, _): (A, B)) -> A { a }
     /// use std::collections::HashSet;
     ///
     /// let mut v = HashSet::new();
-    /// v.insert(1u);
+    /// v.insert(1);
     /// v.clear();
     /// assert!(v.is_empty());
     /// ```
@@ -456,7 +456,7 @@ pub fn clear(&mut self) { self.map.clear() }
     /// ```
     /// use std::collections::HashSet;
     ///
-    /// let set: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
+    /// let set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
     /// assert_eq!(set.contains(&1), true);
     /// assert_eq!(set.contains(&4), false);
     /// ```
@@ -475,8 +475,8 @@ pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
     /// ```
     /// use std::collections::HashSet;
     ///
-    /// let a: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
-    /// let mut b: HashSet<uint> = HashSet::new();
+    /// let a: HashSet<_> = [1, 2, 3].iter().cloned().collect();
+    /// let mut b = HashSet::new();
     ///
     /// assert_eq!(a.is_disjoint(&b), true);
     /// b.insert(4);
@@ -496,8 +496,8 @@ pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool {
     /// ```
     /// use std::collections::HashSet;
     ///
-    /// let sup: HashSet<uint> = [1, 2, 3].iter().map(|&x| x).collect();
-    /// let mut set: HashSet<uint> = HashSet::new();
+    /// let sup: HashSet<_> = [1, 2, 3].iter().cloned().collect();
+    /// let mut set = HashSet::new();
     ///
     /// assert_eq!(set.is_subset(&sup), true);
     /// set.insert(2);
@@ -517,8 +517,8 @@ pub fn is_subset(&self, other: &HashSet<T, S>) -> bool {
     /// ```
     /// use std::collections::HashSet;
     ///
-    /// let sub: HashSet<uint> = [1, 2].iter().map(|&x| x).collect();
-    /// let mut set: HashSet<uint> = HashSet::new();
+    /// let sub: HashSet<_> = [1, 2].iter().cloned().collect();
+    /// let mut set = HashSet::new();
     ///
     /// assert_eq!(set.is_superset(&sub), false);
     ///
@@ -545,7 +545,7 @@ pub fn is_superset(&self, other: &HashSet<T, S>) -> bool {
     ///
     /// let mut set = HashSet::new();
     ///
-    /// assert_eq!(set.insert(2u), true);
+    /// assert_eq!(set.insert(2), true);
     /// assert_eq!(set.insert(2), false);
     /// assert_eq!(set.len(), 1);
     /// ```
@@ -566,7 +566,7 @@ pub fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()).is_none(
     ///
     /// let mut set = HashSet::new();
     ///
-    /// set.insert(2u);
+    /// set.insert(2);
     /// assert_eq!(set.remove(&2), true);
     /// assert_eq!(set.remove(&2), false);
     /// ```
@@ -670,10 +670,10 @@ impl<'a, 'b, T, S, H> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
     /// ```
     /// use std::collections::HashSet;
     ///
-    /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
-    /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
+    /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
+    /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
     ///
-    /// let set: HashSet<int> = &a | &b;
+    /// let set = &a | &b;
     ///
     /// let mut i = 0;
     /// let expected = [1, 2, 3, 4, 5];
@@ -703,10 +703,10 @@ impl<'a, 'b, T, S, H> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
     /// ```
     /// use std::collections::HashSet;
     ///
-    /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
-    /// let b: HashSet<int> = vec![2, 3, 4].into_iter().collect();
+    /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
+    /// let b: HashSet<_> = vec![2, 3, 4].into_iter().collect();
     ///
-    /// let set: HashSet<int> = &a & &b;
+    /// let set = &a & &b;
     ///
     /// let mut i = 0;
     /// let expected = [2, 3];
@@ -736,10 +736,10 @@ impl<'a, 'b, T, S, H> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
     /// ```
     /// use std::collections::HashSet;
     ///
-    /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
-    /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
+    /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
+    /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
     ///
-    /// let set: HashSet<int> = &a ^ &b;
+    /// let set = &a ^ &b;
     ///
     /// let mut i = 0;
     /// let expected = [1, 2, 4, 5];
@@ -769,10 +769,10 @@ impl<'a, 'b, T, S, H> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
     /// ```
     /// use std::collections::HashSet;
     ///
-    /// let a: HashSet<int> = vec![1, 2, 3].into_iter().collect();
-    /// let b: HashSet<int> = vec![3, 4, 5].into_iter().collect();
+    /// let a: HashSet<_> = vec![1, 2, 3].into_iter().collect();
+    /// let b: HashSet<_> = vec![3, 4, 5].into_iter().collect();
     ///
-    /// let set: HashSet<int> = &a - &b;
+    /// let set = &a - &b;
     ///
     /// let mut i = 0;
     /// let expected = [1, 2];
@@ -1029,7 +1029,7 @@ fn test_subset_and_superset() {
     #[test]
     fn test_iterate() {
         let mut a = HashSet::new();
-        for i in 0u..32 {
+        for i in 0..32 {
             assert!(a.insert(i));
         }
         let mut observed: u32 = 0;
@@ -1152,7 +1152,7 @@ fn test_union() {
     fn test_from_iter() {
         let xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 
-        let set: HashSet<int> = xs.iter().map(|&x| x).collect();
+        let set: HashSet<_> = xs.iter().cloned().collect();
 
         for x in &xs {
             assert!(set.contains(x));
@@ -1198,8 +1198,8 @@ fn test_eq() {
 
     #[test]
     fn test_show() {
-        let mut set: HashSet<int> = HashSet::new();
-        let empty: HashSet<int> = HashSet::new();
+        let mut set = HashSet::new();
+        let empty = HashSet::<i32>::new();
 
         set.insert(1);
         set.insert(2);
@@ -1212,19 +1212,19 @@ fn test_show() {
 
     #[test]
     fn test_trivial_drain() {
-        let mut s = HashSet::<int>::new();
+        let mut s = HashSet::<i32>::new();
         for _ in s.drain() {}
         assert!(s.is_empty());
         drop(s);
 
-        let mut s = HashSet::<int>::new();
+        let mut s = HashSet::<i32>::new();
         drop(s.drain());
         assert!(s.is_empty());
     }
 
     #[test]
     fn test_drain() {
-        let mut s: HashSet<i32> = (1..100).collect();
+        let mut s: HashSet<_> = (1..100).collect();
 
         // try this a bunch of times to make sure we don't screw up internal state.
         for _ in 0..20 {
index 8952b81690186545d3abae3318e0d75de7def7fa..0bb6bd4cf356a24c93cdcc388068a0d41900a1c5 100644 (file)
@@ -67,8 +67,8 @@
 /// but in general is just a tricked out `Vec<Option<u64, K, V>>`.
 #[unsafe_no_drop_flag]
 pub struct RawTable<K, V> {
-    capacity: uint,
-    size:     uint,
+    capacity: usize,
+    size:     usize,
     hashes:   *mut u64,
     // Because K/V do not appear directly in any of the types in the struct,
     // inform rustc that in fact instances of K and V are reachable from here.
@@ -88,7 +88,7 @@ impl<K,V> Copy for RawBucket<K,V> {}
 
 pub struct Bucket<K, V, M> {
     raw:   RawBucket<K, V>,
-    idx:   uint,
+    idx:   usize,
     table: M
 }
 
@@ -96,13 +96,13 @@ impl<K,V,M:Copy> Copy for Bucket<K,V,M> {}
 
 pub struct EmptyBucket<K, V, M> {
     raw:   RawBucket<K, V>,
-    idx:   uint,
+    idx:   usize,
     table: M
 }
 
 pub struct FullBucket<K, V, M> {
     raw:   RawBucket<K, V>,
-    idx:   uint,
+    idx:   usize,
     table: M
 }
 
@@ -190,7 +190,7 @@ pub fn into_table(self) -> M {
         self.table
     }
     /// Get the raw index.
-    pub fn index(&self) -> uint {
+    pub fn index(&self) -> usize {
         self.idx
     }
 }
@@ -212,21 +212,21 @@ pub fn into_table(self) -> M {
         self.table
     }
     /// Get the raw index.
-    pub fn index(&self) -> uint {
+    pub fn index(&self) -> usize {
         self.idx
     }
 }
 
 impl<K, V, M: Deref<Target=RawTable<K, V>>> Bucket<K, V, M> {
     pub fn new(table: M, hash: SafeHash) -> Bucket<K, V, M> {
-        Bucket::at_index(table, hash.inspect() as uint)
+        Bucket::at_index(table, hash.inspect() as usize)
     }
 
-    pub fn at_index(table: M, ib_index: uint) -> Bucket<K, V, M> {
+    pub fn at_index(table: M, ib_index: usize) -> Bucket<K, V, M> {
         let ib_index = ib_index & (table.capacity() - 1);
         Bucket {
             raw: unsafe {
-               table.first_bucket_raw().offset(ib_index as int)
+               table.first_bucket_raw().offset(ib_index as isize)
             },
             idx: ib_index,
             table: table
@@ -276,7 +276,7 @@ pub fn next(&mut self) {
         // ... and it's zero at all other times.
         let maybe_wraparound_dist = (self.idx ^ (self.idx + 1)) & self.table.capacity();
         // Finally, we obtain the offset 1 or the offset -cap + 1.
-        let dist = 1 - (maybe_wraparound_dist as int);
+        let dist = 1 - (maybe_wraparound_dist as isize);
 
         self.idx += 1;
 
@@ -366,11 +366,11 @@ pub fn into_bucket(self) -> Bucket<K, V, M> {
     ///
     /// In the cited blog posts above, this is called the "distance to
     /// initial bucket", or DIB. Also known as "probe count".
-    pub fn distance(&self) -> uint {
+    pub fn distance(&self) -> usize {
         // Calculates the distance one has to travel when going from
         // `hash mod capacity` onwards to `idx mod capacity`, wrapping around
         // if the destination is not reached before the end of the table.
-        (self.idx - self.hash().inspect() as uint) & (self.table.capacity() - 1)
+        (self.idx - self.hash().inspect() as usize) & (self.table.capacity() - 1)
     }
 
     #[inline]
@@ -503,7 +503,7 @@ pub fn shift(mut self) -> Option<GapThenFull<K, V, M>> {
 /// # Panics
 ///
 /// Panics if `target_alignment` is not a power of two.
-fn round_up_to_next(unrounded: uint, target_alignment: uint) -> uint {
+fn round_up_to_next(unrounded: usize, target_alignment: usize) -> usize {
     assert!(target_alignment.is_power_of_two());
     (unrounded + target_alignment - 1) & !(target_alignment - 1)
 }
@@ -520,10 +520,10 @@ fn test_rounding() {
 
 // Returns a tuple of (key_offset, val_offset),
 // from the start of a mallocated array.
-fn calculate_offsets(hashes_size: uint,
-                     keys_size: uint, keys_align: uint,
-                     vals_align: uint)
-                     -> (uint, uint) {
+fn calculate_offsets(hashes_size: usize,
+                     keys_size: usize, keys_align: usize,
+                     vals_align: usize)
+                     -> (usize, usize) {
     let keys_offset = round_up_to_next(hashes_size, keys_align);
     let end_of_keys = keys_offset + keys_size;
 
@@ -534,10 +534,10 @@ fn calculate_offsets(hashes_size: uint,
 
 // Returns a tuple of (minimum required malloc alignment, hash_offset,
 // array_size), from the start of a mallocated array.
-fn calculate_allocation(hash_size: uint, hash_align: uint,
-                        keys_size: uint, keys_align: uint,
-                        vals_size: uint, vals_align: uint)
-                        -> (uint, uint, uint) {
+fn calculate_allocation(hash_size: usize, hash_align: usize,
+                        keys_size: usize, keys_align: usize,
+                        vals_size: usize, vals_align: usize)
+                        -> (usize, usize, usize) {
     let hash_offset = 0;
     let (_, vals_offset) = calculate_offsets(hash_size,
                                              keys_size, keys_align,
@@ -562,7 +562,7 @@ fn test_offset_calculation() {
 impl<K, V> RawTable<K, V> {
     /// Does not initialize the buckets. The caller should ensure they,
     /// at the very least, set every hash to EMPTY_BUCKET.
-    unsafe fn new_uninitialized(capacity: uint) -> RawTable<K, V> {
+    unsafe fn new_uninitialized(capacity: usize) -> RawTable<K, V> {
         if capacity == 0 {
             return RawTable {
                 size: 0,
@@ -601,7 +601,7 @@ unsafe fn new_uninitialized(capacity: uint) -> RawTable<K, V> {
         let buffer = allocate(size, malloc_alignment);
         if buffer.is_null() { ::alloc::oom() }
 
-        let hashes = buffer.offset(hash_offset as int) as *mut u64;
+        let hashes = buffer.offset(hash_offset as isize) as *mut u64;
 
         RawTable {
             capacity: capacity,
@@ -623,15 +623,15 @@ fn first_bucket_raw(&self) -> RawBucket<K, V> {
         unsafe {
             RawBucket {
                 hash: self.hashes,
-                key:  buffer.offset(keys_offset as int) as *mut K,
-                val:  buffer.offset(vals_offset as int) as *mut V
+                key:  buffer.offset(keys_offset as isize) as *mut K,
+                val:  buffer.offset(vals_offset as isize) as *mut V
             }
         }
     }
 
     /// Creates a new raw table from a given capacity. All buckets are
     /// initially empty.
-    pub fn new(capacity: uint) -> RawTable<K, V> {
+    pub fn new(capacity: usize) -> RawTable<K, V> {
         unsafe {
             let ret = RawTable::new_uninitialized(capacity);
             zero_memory(ret.hashes, capacity);
@@ -640,13 +640,13 @@ pub fn new(capacity: uint) -> RawTable<K, V> {
     }
 
     /// The hashtable's capacity, similar to a vector's.
-    pub fn capacity(&self) -> uint {
+    pub fn capacity(&self) -> usize {
         self.capacity
     }
 
     /// The number of elements ever `put` in the hashtable, minus the number
     /// of elements ever `take`n.
-    pub fn size(&self) -> uint {
+    pub fn size(&self) -> usize {
         self.size
     }
 
@@ -654,7 +654,7 @@ fn raw_buckets(&self) -> RawBuckets<K, V> {
         RawBuckets {
             raw: self.first_bucket_raw(),
             hashes_end: unsafe {
-                self.hashes.offset(self.capacity as int)
+                self.hashes.offset(self.capacity as isize)
             },
             marker: marker::ContravariantLifetime,
         }
@@ -705,7 +705,7 @@ pub fn drain(&mut self) -> Drain<K, V> {
     unsafe fn rev_move_buckets(&mut self) -> RevMoveBuckets<K, V> {
         let raw_bucket = self.first_bucket_raw();
         RevMoveBuckets {
-            raw: raw_bucket.offset(self.capacity as int),
+            raw: raw_bucket.offset(self.capacity as isize),
             hashes_end: raw_bucket.hash,
             elems_left: self.size,
             marker:     marker::ContravariantLifetime,
@@ -758,7 +758,7 @@ fn next(&mut self) -> Option<RawBucket<K, V>> {
 struct RevMoveBuckets<'a, K, V> {
     raw: RawBucket<K, V>,
     hashes_end: *mut u64,
-    elems_left: uint,
+    elems_left: usize,
     marker: marker::ContravariantLifetime<'a>,
 }
 
@@ -791,7 +791,7 @@ fn next(&mut self) -> Option<(K, V)> {
 /// Iterator over shared references to entries in a table.
 pub struct Iter<'a, K: 'a, V: 'a> {
     iter: RawBuckets<'a, K, V>,
-    elems_left: uint,
+    elems_left: usize,
 }
 
 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
@@ -808,7 +808,7 @@ fn clone(&self) -> Iter<'a, K, V> {
 /// Iterator over mutable references to entries in a table.
 pub struct IterMut<'a, K: 'a, V: 'a> {
     iter: RawBuckets<'a, K, V>,
-    elems_left: uint,
+    elems_left: usize,
 }
 
 /// Iterator over the entries in a table, consuming the table.
index 0c55850b32a2dd5d689bd21914e173fb36728059..55924bc73a8d5e2f6b4d9dc65b6425bbc8cccc56 100644 (file)
 //! all the contents of the collection.
 //!
 //! ```
-//! let vec = vec![1u, 2, 3, 4];
+//! let vec = vec![1, 2, 3, 4];
 //! for x in vec.iter() {
 //!    println!("vec contained {}", x);
 //! }
 //! This is great for mutating all the contents of the collection.
 //!
 //! ```
-//! let mut vec = vec![1u, 2, 3, 4];
+//! let mut vec = vec![1, 2, 3, 4];
 //! for x in vec.iter_mut() {
 //!    *x += 1;
 //! }
 //! previous section to do this as efficiently as possible.
 //!
 //! ```
-//! let mut vec1 = vec![1u, 2, 3, 4];
-//! let vec2 = vec![10u, 20, 30, 40];
+//! let mut vec1 = vec![1, 2, 3, 4];
+//! let vec2 = vec![10, 20, 30, 40];
 //! vec1.extend(vec2.into_iter());
 //! ```
 //!
 //! ```
 //! use std::collections::RingBuf;
 //!
-//! let vec = vec![1u, 2, 3, 4];
+//! let vec = vec![1, 2, 3, 4];
 //! let buf: RingBuf<uint> = vec.into_iter().collect();
 //! ```
 //!
 //! iterators as the way to iterate over them in reverse order.
 //!
 //! ```
-//! let vec = vec![1u, 2, 3, 4];
+//! let vec = vec![1, 2, 3, 4];
 //! for x in vec.iter().rev() {
 //!    println!("vec contained {}", x);
 //! }
 //! #### Counting the number of times each character in a string occurs
 //!
 //! ```
-//! use std::collections::btree_map::{BTreeMap, Occupied, Vacant};
+//! use std::collections::btree_map::{BTreeMap, Entry};
 //!
 //! let mut count = BTreeMap::new();
 //! let message = "she sells sea shells by the sea shore";
 //!
 //! for c in message.chars() {
 //!     match count.entry(c) {
-//!         Vacant(entry) => { entry.insert(1u); },
-//!         Occupied(mut entry) => *entry.get_mut() += 1,
+//!         Entry::Vacant(entry) => { entry.insert(1); },
+//!         Entry::Occupied(mut entry) => *entry.get_mut() += 1,
 //!     }
 //! }
 //!
 //! assert_eq!(count.get(&'s'), Some(&8));
 //!
-//! println!("Number of occurences of each character");
+//! println!("Number of occurrences of each character");
 //! for (char, count) in count.iter() {
 //!     println!("{}: {}", char, count);
 //! }
 //! #### Tracking the inebriation of customers at a bar
 //!
 //! ```
-//! use std::collections::btree_map::{BTreeMap, Occupied, Vacant};
+//! use std::collections::btree_map::{BTreeMap, Entry};
 //!
 //! // A client of the bar. They have an id and a blood alcohol level.
 //! struct Person { id: u32, blood_alcohol: f32 };
 //!     // If this is the first time we've seen this customer, initialize them
 //!     // with no blood alcohol. Otherwise, just retrieve them.
 //!     let person = match blood_alcohol.entry(id) {
-//!         Vacant(entry) => entry.insert(Person{id: id, blood_alcohol: 0.0}),
-//!         Occupied(entry) => entry.into_mut(),
+//!         Entry::Vacant(entry) => entry.insert(Person{id: id, blood_alcohol: 0.0}),
+//!         Entry::Occupied(entry) => entry.into_mut(),
 //!     };
 //!
 //!     // Reduce their blood alcohol level. It takes time to order and drink a beer!
index 68ae0f7e5b5f3ace6049fb6e7ae9f43fbf3b8aba..bee9a0d00337b4fa2f9a9130bd5c525ada3cec88 100644 (file)
@@ -22,7 +22,6 @@
 use env;
 use str;
 
-#[allow(missing_copy_implementations)]
 pub struct DynamicLibrary {
     handle: *mut u8
 }
@@ -67,9 +66,9 @@ pub fn open(filename: Option<&Path>) -> Result<DynamicLibrary, String> {
     pub fn prepend_search_path(path: &Path) {
         let mut search_path = DynamicLibrary::search_path();
         search_path.insert(0, path.clone());
-        let newval = DynamicLibrary::create_path(search_path.as_slice());
+        let newval = DynamicLibrary::create_path(&search_path);
         env::set_var(DynamicLibrary::envvar(),
-                     str::from_utf8(newval.as_slice()).unwrap());
+                     str::from_utf8(&newval).unwrap());
     }
 
     /// From a slice of paths, create a new vector which is suitable to be an
index 559a68542efc890492144a2ec5289b739e059b68..e73797bc66c7f377324b8bb1e6e9fca25d808e7b 100644 (file)
@@ -337,7 +337,7 @@ pub fn temp_dir() -> Path {
 ///
 /// # Errors
 ///
-/// Acquring the path to the current executable is a platform-specific operation
+/// Acquiring the path to the current executable is a platform-specific operation
 /// that can fail for a good number of reasons. Some errors can include, but not
 /// be limited to filesystem operations failing or general syscall failures.
 ///
@@ -562,6 +562,38 @@ pub mod consts {
     pub const EXE_EXTENSION: &'static str = "";
 }
 
+/// Constants associated with the current target
+#[cfg(target_os = "openbsd")]
+pub mod consts {
+    pub use super::arch_consts::ARCH;
+
+    pub const FAMILY: &'static str = "unix";
+
+    /// A string describing the specific operating system in use: in this
+    /// case, `dragonfly`.
+    pub const OS: &'static str = "openbsd";
+
+    /// Specifies the filename prefix used for shared libraries on this
+    /// platform: in this case, `lib`.
+    pub const DLL_PREFIX: &'static str = "lib";
+
+    /// Specifies the filename suffix used for shared libraries on this
+    /// platform: in this case, `.so`.
+    pub const DLL_SUFFIX: &'static str = ".so";
+
+    /// Specifies the file extension used for shared libraries on this
+    /// platform that goes after the dot: in this case, `so`.
+    pub const DLL_EXTENSION: &'static str = "so";
+
+    /// Specifies the filename suffix used for executable binaries on this
+    /// platform: in this case, the empty string.
+    pub const EXE_SUFFIX: &'static str = "";
+
+    /// Specifies the file extension, if any, used for executable binaries
+    /// on this platform: in this case, the empty string.
+    pub const EXE_EXTENSION: &'static str = "";
+}
+
 /// Constants associated with the current target
 #[cfg(target_os = "android")]
 pub mod consts {
index 2e55c007b551b32e55a9a3e4430a15f8b32995d9..45089176cba961b97e285456ad2346e2e4787b9d 100644 (file)
@@ -13,7 +13,7 @@
 use libc;
 use mem;
 use ops::Deref;
-use slice::{self, SliceExt, AsSlice};
+use slice::{self, SliceExt};
 use string::String;
 use vec::Vec;
 
@@ -96,12 +96,12 @@ pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
 
     /// Create a view into this C string which includes the trailing nul
     /// terminator at the end of the string.
-    pub fn as_slice_with_nul(&self) -> &[libc::c_char] { self.inner.as_slice() }
+    pub fn as_slice_with_nul(&self) -> &[libc::c_char] { &self.inner }
 
     /// Similar to the `as_slice` method, but returns a `u8` slice instead of a
     /// `libc::c_char` slice.
     pub fn as_bytes(&self) -> &[u8] {
-        unsafe { mem::transmute(self.as_slice()) }
+        unsafe { mem::transmute(&**self) }
     }
 
     /// Equivalent to `as_slice_with_nul` except that the type returned is a
@@ -162,7 +162,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 /// ```
 pub unsafe fn c_str_to_bytes<'a>(raw: &'a *const libc::c_char) -> &'a [u8] {
     let len = libc::strlen(*raw);
-    slice::from_raw_buf(&*(raw as *const _ as *const *const u8), len as uint)
+    slice::from_raw_parts(*(raw as *const _ as *const *const u8), len as usize)
 }
 
 /// Interpret a C string as a byte slice with the nul terminator.
@@ -171,7 +171,7 @@ pub unsafe fn c_str_to_bytes<'a>(raw: &'a *const libc::c_char) -> &'a [u8] {
 /// will include the nul terminator of the string.
 pub unsafe fn c_str_to_bytes_with_nul<'a>(raw: &'a *const libc::c_char) -> &'a [u8] {
     let len = libc::strlen(*raw) + 1;
-    slice::from_raw_buf(&*(raw as *const _ as *const *const u8), len as uint)
+    slice::from_raw_parts(*(raw as *const _ as *const *const u8), len as usize)
 }
 
 #[cfg(test)]
@@ -197,7 +197,7 @@ fn simple() {
         assert_eq!(s.as_bytes(), b"1234");
         assert_eq!(s.as_bytes_with_nul(), b"1234\0");
         unsafe {
-            assert_eq!(s.as_slice(),
+            assert_eq!(&*s,
                        mem::transmute::<_, &[libc::c_char]>(b"1234"));
             assert_eq!(s.as_slice_with_nul(),
                        mem::transmute::<_, &[libc::c_char]>(b"1234\0"));
diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs
deleted file mode 100644 (file)
index 47f5d64..0000000
+++ /dev/null
@@ -1,436 +0,0 @@
-// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-//
-// ignore-lexer-test FIXME #15679
-
-//! Utilities for formatting and printing strings
-//!
-//! This module contains the runtime support for the `format!` syntax extension.
-//! This macro is implemented in the compiler to emit calls to this module in
-//! order to format arguments at runtime into strings and streams.
-//!
-//! ## Usage
-//!
-//! The `format!` macro is intended to be familiar to those coming from C's
-//! printf/fprintf functions or Python's `str.format` function. In its current
-//! revision, the `format!` macro returns a `String` type which is the result of
-//! the formatting. In the future it will also be able to pass in a stream to
-//! format arguments directly while performing minimal allocations.
-//!
-//! Some examples of the `format!` extension are:
-//!
-//! ```
-//! format!("Hello");                  // => "Hello"
-//! format!("Hello, {}!", "world");    // => "Hello, world!"
-//! format!("The number is {}", 1);   // => "The number is 1"
-//! format!("{:?}", (3, 4));         // => "(3, 4)"
-//! format!("{value}", value=4);      // => "4"
-//! format!("{} {}", 1, 2u);          // => "1 2"
-//! ```
-//!
-//! From these, you can see that the first argument is a format string. It is
-//! required by the compiler for this to be a string literal; it cannot be a
-//! variable passed in (in order to perform validity checking). The compiler
-//! will then parse the format string and determine if the list of arguments
-//! provided is suitable to pass to this format string.
-//!
-//! ### Positional parameters
-//!
-//! Each formatting argument is allowed to specify which value argument it's
-//! referencing, and if omitted it is assumed to be "the next argument". For
-//! example, the format string `{} {} {}` would take three parameters, and they
-//! would be formatted in the same order as they're given. The format string
-//! `{2} {1} {0}`, however, would format arguments in reverse order.
-//!
-//! Things can get a little tricky once you start intermingling the two types of
-//! positional specifiers. The "next argument" specifier can be thought of as an
-//! iterator over the argument. Each time a "next argument" specifier is seen,
-//! the iterator advances. This leads to behavior like this:
-//!
-//! ```rust
-//! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
-//! ```
-//!
-//! The internal iterator over the argument has not been advanced by the time
-//! the first `{}` is seen, so it prints the first argument. Then upon reaching
-//! the second `{}`, the iterator has advanced forward to the second argument.
-//! Essentially, parameters which explicitly name their argument do not affect
-//! parameters which do not name an argument in terms of positional specifiers.
-//!
-//! A format string is required to use all of its arguments, otherwise it is a
-//! compile-time error. You may refer to the same argument more than once in the
-//! format string, although it must always be referred to with the same type.
-//!
-//! ### Named parameters
-//!
-//! Rust itself does not have a Python-like equivalent of named parameters to a
-//! function, but the `format!` macro is a syntax extension which allows it to
-//! leverage named parameters. Named parameters are listed at the end of the
-//! argument list and have the syntax:
-//!
-//! ```text
-//! identifier '=' expression
-//! ```
-//!
-//! For example, the following `format!` expressions all use named argument:
-//!
-//! ```
-//! format!("{argument}", argument = "test");   // => "test"
-//! format!("{name} {}", 1, name = 2);        // => "2 1"
-//! format!("{a} {c} {b}", a="a", b='b', c=3);  // => "a 3 b"
-//! ```
-//!
-//! It is illegal to put positional parameters (those without names) after
-//! arguments which have names. Like with positional parameters, it is illegal
-//! to provide named parameters that are unused by the format string.
-//!
-//! ### Argument types
-//!
-//! Each argument's type is dictated by the format string. It is a requirement
-//! that every argument is only ever referred to by one type. For example, this
-//! is an invalid format string:
-//!
-//! ```text
-//! {0:x} {0:o}
-//! ```
-//!
-//! This is invalid because the first argument is both referred to as a
-//! hexadecimal as well as an
-//! octal.
-//!
-//! There are various parameters which do require a particular type, however.
-//! Namely if the syntax `{:.*}` is used, then the number of characters to print
-//! precedes the actual object being formatted, and the number of characters
-//! must have the type `uint`. Although a `uint` can be printed with `{}`, it is
-//! illegal to reference an argument as such. For example this is another
-//! invalid format string:
-//!
-//! ```text
-//! {:.*} {0}
-//! ```
-//!
-//! ### Formatting traits
-//!
-//! When requesting that an argument be formatted with a particular type, you
-//! are actually requesting that an argument ascribes to a particular trait.
-//! This allows multiple actual types to be formatted via `{:x}` (like `i8` as
-//! well as `int`).  The current mapping of types to traits is:
-//!
-//! * *nothing* ⇒ `Display`
-//! * `?` ⇒ `Debug`
-//! * `o` ⇒ `Octal`
-//! * `x` ⇒ `LowerHex`
-//! * `X` ⇒ `UpperHex`
-//! * `p` ⇒ `Pointer`
-//! * `b` ⇒ `Binary`
-//! * `e` ⇒ `LowerExp`
-//! * `E` ⇒ `UpperExp`
-//!
-//! What this means is that any type of argument which implements the
-//! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations
-//! are provided for these traits for a number of primitive types by the
-//! standard library as well. If no format is specified (as in `{}` or `{:6}`),
-//! then the format trait used is the `Display` trait.
-//!
-//! When implementing a format trait for your own type, you will have to
-//! implement a method of the signature:
-//!
-//! ```rust
-//! # use std::fmt;
-//! # struct Foo; // our custom type
-//! # impl fmt::Display for Foo {
-//! fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
-//! # write!(f, "testing, testing")
-//! # } }
-//! ```
-//!
-//! Your type will be passed as `self` by-reference, and then the function
-//! should emit output into the `f.buf` stream. It is up to each format trait
-//! implementation to correctly adhere to the requested formatting parameters.
-//! The values of these parameters will be listed in the fields of the
-//! `Formatter` struct. In order to help with this, the `Formatter` struct also
-//! provides some helper methods.
-//!
-//! Additionally, the return value of this function is `fmt::Result` which is a
-//! typedef to `Result<(), IoError>` (also known as `IoResult<()>`). Formatting
-//! implementations should ensure that they return errors from `write!`
-//! correctly (propagating errors upward).
-//!
-//! An example of implementing the formatting traits would look
-//! like:
-//!
-//! ```rust
-//! use std::fmt;
-//! use std::f64;
-//! use std::num::Float;
-//!
-//! #[derive(Debug)]
-//! struct Vector2D {
-//!     x: int,
-//!     y: int,
-//! }
-//!
-//! impl fmt::Display for Vector2D {
-//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-//!         // The `f` value implements the `Writer` trait, which is what the
-//!         // write! macro is expecting. Note that this formatting ignores the
-//!         // various flags provided to format strings.
-//!         write!(f, "({}, {})", self.x, self.y)
-//!     }
-//! }
-//!
-//! // Different traits allow different forms of output of a type. The meaning
-//! // of this format is to print the magnitude of a vector.
-//! impl fmt::Binary for Vector2D {
-//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-//!         let magnitude = (self.x * self.x + self.y * self.y) as f64;
-//!         let magnitude = magnitude.sqrt();
-//!
-//!         // Respect the formatting flags by using the helper method
-//!         // `pad_integral` on the Formatter object. See the method documentation
-//!         // for details, and the function `pad` can be used to pad strings.
-//!         let decimals = f.precision().unwrap_or(3);
-//!         let string = f64::to_str_exact(magnitude, decimals);
-//!         f.pad_integral(true, "", string.as_slice())
-//!     }
-//! }
-//!
-//! fn main() {
-//!     let myvector = Vector2D { x: 3, y: 4 };
-//!
-//!     println!("{}", myvector);       // => "(3, 4)"
-//!     println!("{:?}", myvector);     // => "Vector2D {x: 3, y:4}"
-//!     println!("{:10.3b}", myvector); // => "     5.000"
-//! }
-//! ```
-//!
-//! #### fmt::Display vs fmt::Debug
-//!
-//! These two formatting traits have distinct purposes:
-//!
-//! - `fmt::Display` implementations assert that the type can be faithfully
-//!   represented as a UTF-8 string at all times. It is **not** expected that
-//!   all types implement the `Display` trait.
-//! - `fmt::Debug` implementations should be implemented for **all** public types.
-//!   Output will typically represent the internal state as faithfully as possible.
-//!   The purpose of the `Debug` trait is to facilitate debugging Rust code. In
-//!   most cases, using `#[derive(Debug)]` is sufficient and recommended.
-//!
-//! Some examples of the output from both traits:
-//!
-//! ```
-//! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4");
-//! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
-//! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
-//! ```
-//!
-//! ### Related macros
-//!
-//! There are a number of related macros in the `format!` family. The ones that
-//! are currently implemented are:
-//!
-//! ```ignore
-//! format!      // described above
-//! write!       // first argument is a &mut old_io::Writer, the destination
-//! writeln!     // same as write but appends a newline
-//! print!       // the format string is printed to the standard output
-//! println!     // same as print but appends a newline
-//! format_args! // described below.
-//! ```
-//!
-//! #### `write!`
-//!
-//! This and `writeln` are two macros which are used to emit the format string
-//! to a specified stream. This is used to prevent intermediate allocations of
-//! format strings and instead directly write the output. Under the hood, this
-//! function is actually invoking the `write` function defined in this module.
-//! Example usage is:
-//!
-//! ```rust
-//! # #![allow(unused_must_use)]
-//! let mut w = Vec::new();
-//! write!(&mut w, "Hello {}!", "world");
-//! ```
-//!
-//! #### `print!`
-//!
-//! This and `println` emit their output to stdout. Similarly to the `write!`
-//! macro, the goal of these macros is to avoid intermediate allocations when
-//! printing output. Example usage is:
-//!
-//! ```rust
-//! print!("Hello {}!", "world");
-//! println!("I have a newline {}", "character at the end");
-//! ```
-//!
-//! #### `format_args!`
-//! This is a curious macro which is used to safely pass around
-//! an opaque object describing the format string. This object
-//! does not require any heap allocations to create, and it only
-//! references information on the stack. Under the hood, all of
-//! the related macros are implemented in terms of this. First
-//! off, some example usage is:
-//!
-//! ```
-//! use std::fmt;
-//! use std::old_io;
-//!
-//! fmt::format(format_args!("this returns {}", "String"));
-//!
-//! let mut some_writer = old_io::stdout();
-//! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
-//!
-//! fn my_fmt_fn(args: fmt::Arguments) {
-//!     write!(&mut old_io::stdout(), "{}", args);
-//! }
-//! my_fmt_fn(format_args!("or a {} too", "function"));
-//! ```
-//!
-//! The result of the `format_args!` macro is a value of type `fmt::Arguments`.
-//! This structure can then be passed to the `write` and `format` functions
-//! inside this module in order to process the format string.
-//! The goal of this macro is to even further prevent intermediate allocations
-//! when dealing formatting strings.
-//!
-//! For example, a logging library could use the standard formatting syntax, but
-//! it would internally pass around this structure until it has been determined
-//! where output should go to.
-//!
-//! ## Syntax
-//!
-//! The syntax for the formatting language used is drawn from other languages,
-//! so it should not be too alien. Arguments are formatted with python-like
-//! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
-//! `%`. The actual grammar for the formatting syntax is:
-//!
-//! ```text
-//! format_string := <text> [ format <text> ] *
-//! format := '{' [ argument ] [ ':' format_spec ] '}'
-//! argument := integer | identifier
-//!
-//! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
-//! fill := character
-//! align := '<' | '^' | '>'
-//! sign := '+' | '-'
-//! width := count
-//! precision := count | '*'
-//! type := identifier | ''
-//! count := parameter | integer
-//! parameter := integer '$'
-//! ```
-//!
-//! ## Formatting Parameters
-//!
-//! Each argument being formatted can be transformed by a number of formatting
-//! parameters (corresponding to `format_spec` in the syntax above). These
-//! parameters affect the string representation of what's being formatted. This
-//! syntax draws heavily from Python's, so it may seem a bit familiar.
-//!
-//! ### Fill/Alignment
-//!
-//! The fill character is provided normally in conjunction with the `width`
-//! parameter. This indicates that if the value being formatted is smaller than
-//! `width` some extra characters will be printed around it. The extra
-//! characters are specified by `fill`, and the alignment can be one of two
-//! options:
-//!
-//! * `<` - the argument is left-aligned in `width` columns
-//! * `^` - the argument is center-aligned in `width` columns
-//! * `>` - the argument is right-aligned in `width` columns
-//!
-//! ### Sign/#/0
-//!
-//! These can all be interpreted as flags for a particular formatter.
-//!
-//! * '+' - This is intended for numeric types and indicates that the sign
-//!         should always be printed. Positive signs are never printed by
-//!         default, and the negative sign is only printed by default for the
-//!         `Signed` trait. This flag indicates that the correct sign (+ or -)
-//!         should always be printed.
-//! * '-' - Currently not used
-//! * '#' - This flag is indicates that the "alternate" form of printing should
-//!         be used. By default, this only applies to the integer formatting
-//!         traits and performs like:
-//!     * `x` - precedes the argument with a "0x"
-//!     * `X` - precedes the argument with a "0x"
-//!     * `t` - precedes the argument with a "0b"
-//!     * `o` - precedes the argument with a "0o"
-//! * '0' - This is used to indicate for integer formats that the padding should
-//!         both be done with a `0` character as well as be sign-aware. A format
-//!         like `{:08d}` would yield `00000001` for the integer `1`, while the
-//!         same format would yield `-0000001` for the integer `-1`. Notice that
-//!         the negative version has one fewer zero than the positive version.
-//!
-//! ### Width
-//!
-//! This is a parameter for the "minimum width" that the format should take up.
-//! If the value's string does not fill up this many characters, then the
-//! padding specified by fill/alignment will be used to take up the required
-//! space.
-//!
-//! The default fill/alignment for non-numerics is a space and left-aligned. The
-//! defaults for numeric formatters is also a space but with right-alignment. If
-//! the '0' flag is specified for numerics, then the implicit fill character is
-//! '0'.
-//!
-//! The value for the width can also be provided as a `uint` in the list of
-//! parameters by using the `2$` syntax indicating that the second argument is a
-//! `uint` specifying the width.
-//!
-//! ### Precision
-//!
-//! For non-numeric types, this can be considered a "maximum width". If the
-//! resulting string is longer than this width, then it is truncated down to
-//! this many characters and only those are emitted.
-//!
-//! For integral types, this has no meaning currently.
-//!
-//! For floating-point types, this indicates how many digits after the decimal
-//! point should be printed.
-//!
-//! ## Escaping
-//!
-//! The literal characters `{` and `}` may be included in a string by preceding
-//! them with the same character. For example, the `{` character is escaped with
-//! `{{` and the `}` character is escaped with `}}`.
-
-#![unstable(feature = "std_misc")]
-
-use string;
-
-pub use core::fmt::{Formatter, Result, Writer, rt};
-pub use core::fmt::{Show, String, Octal, Binary};
-pub use core::fmt::{Display, Debug};
-pub use core::fmt::{LowerHex, UpperHex, Pointer};
-pub use core::fmt::{LowerExp, UpperExp};
-pub use core::fmt::Error;
-pub use core::fmt::{ArgumentV1, Arguments, write, radix, Radix, RadixFmt};
-
-/// The format function takes a precompiled format string and a list of
-/// arguments, to return the resulting formatted string.
-///
-/// # Arguments
-///
-///   * args - a structure of arguments generated via the `format_args!` macro.
-///
-/// # Example
-///
-/// ```rust
-/// use std::fmt;
-///
-/// let s = fmt::format(format_args!("Hello, {}!", "world"));
-/// assert_eq!(s, "Hello, world!".to_string());
-/// ```
-#[stable(feature = "rust1", since = "1.0.0")]
-pub fn format(args: Arguments) -> string::String {
-    let mut output = string::String::new();
-    let _ = write!(&mut output, "{}", args);
-    output
-}
diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs
new file mode 100644 (file)
index 0000000..45de678
--- /dev/null
@@ -0,0 +1,1501 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Filesystem manipulation operations
+//!
+//! This module contains basic methods to manipulate the contents of the local
+//! filesystem. All methods in this module represent cross-platform filesystem
+//! operations. Extra platform-specific functionality can be found in the
+//! extension traits of `std::os::$platform`.
+
+#![unstable(feature = "fs")]
+
+use core::prelude::*;
+
+use io::{self, Error, ErrorKind, SeekFrom, Seek, Read, Write};
+use path::{AsPath, Path, PathBuf};
+use sys::fs2 as fs_imp;
+use sys_common::{AsInnerMut, FromInner, AsInner};
+use vec::Vec;
+
+/// A reference to an open file on the filesystem.
+///
+/// An instance of a `File` can be read and/or written depending on what options
+/// it was opened with. Files also implement `Seek` to alter the logical cursor
+/// that the file contains internally.
+///
+/// # Example
+///
+/// ```no_run
+/// use std::io::prelude::*;
+/// use std::fs::File;
+///
+/// # fn foo() -> std::io::Result<()> {
+/// let mut f = try!(File::create("foo.txt"));
+/// try!(f.write_all(b"Hello, world!"));
+///
+/// let mut f = try!(File::open("foo.txt"));
+/// let mut s = String::new();
+/// try!(f.read_to_string(&mut s));
+/// assert_eq!(s, "Hello, world!");
+/// # Ok(())
+/// # }
+/// ```
+pub struct File {
+    inner: fs_imp::File,
+    path: PathBuf,
+}
+
+/// Metadata information about a file.
+///
+/// This structure is returned from the `metadata` function or method and
+/// represents known metadata about a file such as its permissions, size,
+/// modification times, etc.
+pub struct Metadata(fs_imp::FileAttr);
+
+/// Iterator over the entries in a directory.
+///
+/// This iterator is returned from the `read_dir` function of this module and
+/// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
+/// information like the entry's path and possibly other metadata can be
+/// learned.
+pub struct ReadDir(fs_imp::ReadDir);
+
+/// Entries returned by the `ReadDir` iterator.
+///
+/// An instance of `DirEntry` represents an entry inside of a directory on the
+/// filesystem. Each entry can be inspected via methods to learn about the full
+/// path or possibly other metadata through per-platform extension traits.
+pub struct DirEntry(fs_imp::DirEntry);
+
+/// An iterator that recursively walks over the contents of a directory.
+pub struct WalkDir {
+    cur: Option<ReadDir>,
+    stack: Vec<io::Result<ReadDir>>,
+}
+
+/// Options and flags which can be used to configure how a file is opened.
+///
+/// This builder exposes the ability to configure how a `File` is opened and
+/// what operations are permitted on the open file. The `File::open` and
+/// `File::create` methods are aliases for commonly used options using this
+/// builder.
+#[derive(Clone)]
+pub struct OpenOptions(fs_imp::OpenOptions);
+
+/// Representation of the various permissions on a file.
+///
+/// This module only currently provides one bit of information, `readonly`,
+/// which is exposed on all currently supported platforms. Unix-specific
+/// functionality, such as mode bits, is available through the
+/// `os::unix::PermissionsExt` trait.
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct Permissions(fs_imp::FilePermissions);
+
+impl File {
+    /// Attempts to open a file in read-only mode.
+    ///
+    /// See the `OpenOptions::open` method for more details.
+    ///
+    /// # Errors
+    ///
+    /// This function will return an error if `path` does not already exist.
+    /// Other errors may also be returned according to `OpenOptions::open`.
+    pub fn open<P: AsPath + ?Sized>(path: &P) -> io::Result<File> {
+        OpenOptions::new().read(true).open(path)
+    }
+
+    /// Creates a open a file in write-only mode.
+    ///
+    /// This method will attempt to open a new file, truncating it if it already
+    /// exists.
+    ///
+    /// See the `OpenOptions::open` function for more details.
+    pub fn create<P: AsPath + ?Sized>(path: &P) -> io::Result<File> {
+        OpenOptions::new().write(true).create(true).truncate(true).open(path)
+    }
+
+    /// Returns the original path that was used to open this file.
+    pub fn path(&self) -> Option<&Path> {
+        Some(&self.path)
+    }
+
+    /// Attempt to sync all OS-internal metadata to disk.
+    ///
+    /// This function will attempt to ensure that all in-core data reaches the
+    /// filesystem before returning.
+    pub fn sync_all(&self) -> io::Result<()> {
+        self.inner.fsync()
+    }
+
+    /// This function is similar to `sync_all`, except that it may not
+    /// synchronize file metadata to the filesystem.
+    ///
+    /// This is intended for use cases that must synchronize content, but don't
+    /// need the metadata on disk. The goal of this method is to reduce disk
+    /// operations.
+    ///
+    /// Note that some platforms may simply implement this in terms of
+    /// `sync_all`.
+    pub fn sync_data(&self) -> io::Result<()> {
+        self.inner.datasync()
+    }
+
+    /// Truncates or extends the underlying file, updating the size of
+    /// this file to become `size`.
+    ///
+    /// If the `size` is less than the current file's size, then the file will
+    /// be shrunk. If it is greater than the current file's size, then the file
+    /// will be extended to `size` and have all of the intermediate data filled
+    /// in with 0s.
+    pub fn set_len(&self, size: u64) -> io::Result<()> {
+        self.inner.truncate(size)
+    }
+
+    /// Queries information about the underlying file.
+    pub fn metadata(&self) -> io::Result<Metadata> {
+        self.inner.file_attr().map(Metadata)
+    }
+}
+
+impl AsInner<fs_imp::File> for File {
+    fn as_inner(&self) -> &fs_imp::File { &self.inner }
+}
+impl Read for File {
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        self.inner.read(buf)
+    }
+}
+impl Write for File {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.inner.write(buf)
+    }
+    fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+}
+impl Seek for File {
+    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
+        self.inner.seek(pos)
+    }
+}
+impl<'a> Read for &'a File {
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        self.inner.read(buf)
+    }
+}
+impl<'a> Write for &'a File {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.inner.write(buf)
+    }
+    fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+}
+impl<'a> Seek for &'a File {
+    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
+        self.inner.seek(pos)
+    }
+}
+
+impl OpenOptions {
+    /// Creates a blank net set of options ready for configuration.
+    ///
+    /// All options are initially set to `false`.
+    pub fn new() -> OpenOptions {
+        OpenOptions(fs_imp::OpenOptions::new())
+    }
+
+    /// Set the option for read access.
+    ///
+    /// This option, when true, will indicate that the file should be
+    /// `read`-able if opened.
+    pub fn read(&mut self, read: bool) -> &mut OpenOptions {
+        self.0.read(read); self
+    }
+
+    /// Set the option for write access.
+    ///
+    /// This option, when true, will indicate that the file should be
+    /// `write`-able if opened.
+    pub fn write(&mut self, write: bool) -> &mut OpenOptions {
+        self.0.write(write); self
+    }
+
+    /// Set the option for the append mode.
+    ///
+    /// This option, when true, means that writes will append to a file instead
+    /// of overwriting previous contents.
+    pub fn append(&mut self, append: bool) -> &mut OpenOptions {
+        self.0.append(append); self
+    }
+
+    /// Set the option for truncating a previous file.
+    ///
+    /// If a file is successfully opened with this option set it will truncate
+    /// the file to 0 length if it already exists.
+    pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
+        self.0.truncate(truncate); self
+    }
+
+    /// Set the option for creating a new file.
+    ///
+    /// This option indicates whether a new file will be created if the file
+    /// does not yet already exist.
+    pub fn create(&mut self, create: bool) -> &mut OpenOptions {
+        self.0.create(create); self
+    }
+
+    /// Open a file at `path` with the options specified by `self`.
+    ///
+    /// # Errors
+    ///
+    /// This function will return an error under a number of different
+    /// circumstances, to include but not limited to:
+    ///
+    /// * Opening a file that does not exist with read access.
+    /// * Attempting to open a file with access that the user lacks
+    ///   permissions for
+    /// * Filesystem-level errors (full disk, etc)
+    pub fn open<P: AsPath + ?Sized>(&self, path: &P) -> io::Result<File> {
+        let path = path.as_path();
+        let inner = try!(fs_imp::File::open(path, &self.0));
+
+        // On *BSD systems, we can open a directory as a file and read from
+        // it: fd=open("/tmp", O_RDONLY); read(fd, buf, N); due to an old
+        // tradition before the introduction of opendir(3).  We explicitly
+        // reject it because there are few use cases.
+        if cfg!(not(any(target_os = "linux", target_os = "android"))) &&
+           try!(inner.file_attr()).is_dir() {
+            Err(Error::new(ErrorKind::InvalidInput, "is a directory", None))
+        } else {
+            Ok(File { path: path.to_path_buf(), inner: inner })
+        }
+    }
+}
+impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
+    fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
+}
+
+impl Metadata {
+    /// Returns whether this metadata is for a directory.
+    pub fn is_dir(&self) -> bool { self.0.is_dir() }
+
+    /// Returns whether this metadata is for a regular file.
+    pub fn is_file(&self) -> bool { self.0.is_file() }
+
+    /// Returns the size of the file, in bytes, this metadata is for.
+    pub fn len(&self) -> u64 { self.0.size() }
+
+    /// Returns the permissions of the file this metadata is for.
+    pub fn permissions(&self) -> Permissions {
+        Permissions(self.0.perm())
+    }
+
+    /// Returns the most recent access time for a file.
+    ///
+    /// The return value is in milliseconds since the epoch.
+    pub fn accessed(&self) -> u64 { self.0.accessed() }
+
+    /// Returns the most recent modification time for a file.
+    ///
+    /// The return value is in milliseconds since the epoch.
+    pub fn modified(&self) -> u64 { self.0.modified() }
+}
+
+impl Permissions {
+    /// Returns whether these permissions describe a readonly file.
+    pub fn readonly(&self) -> bool { self.0.readonly() }
+
+    /// Modify the readonly flag for this set of permissions.
+    ///
+    /// This operation does **not** modify the filesystem. To modify the
+    /// filesystem use the `fs::set_permissions` function.
+    pub fn set_readonly(&mut self, readonly: bool) {
+        self.0.set_readonly(readonly)
+    }
+}
+
+impl FromInner<fs_imp::FilePermissions> for Permissions {
+    fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
+        Permissions(f)
+    }
+}
+
+impl Iterator for ReadDir {
+    type Item = io::Result<DirEntry>;
+
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        self.0.next().map(|entry| entry.map(DirEntry))
+    }
+}
+
+impl DirEntry {
+    /// Returns the full path to the file that this entry represents.
+    ///
+    /// The full path is created by joining the original path to `read_dir` or
+    /// `walk_dir` with the filename of this entry.
+    pub fn path(&self) -> PathBuf { self.0.path() }
+}
+
+/// Remove a file from the underlying filesystem.
+///
+/// # Example
+///
+/// ```rust,no_run
+/// use std::fs;
+///
+/// fs::remove_file("/some/file/path.txt");
+/// ```
+///
+/// Note that, just because an unlink call was successful, it is not
+/// guaranteed that a file is immediately deleted (e.g. depending on
+/// platform, other open file descriptors may prevent immediate removal).
+///
+/// # Errors
+///
+/// This function will return an error if `path` points to a directory, if the
+/// user lacks permissions to remove the file, or if some other filesystem-level
+/// error occurs.
+pub fn remove_file<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    let path = path.as_path();
+    let e = match fs_imp::unlink(path) {
+        Ok(()) => return Ok(()),
+        Err(e) => e,
+    };
+    if !cfg!(windows) { return Err(e) }
+
+    // On unix, a readonly file can be successfully removed. On windows,
+    // however, it cannot. To keep the two platforms in line with
+    // respect to their behavior, catch this case on windows, attempt to
+    // change it to read-write, and then remove the file.
+    if e.kind() != ErrorKind::PermissionDenied { return Err(e) }
+
+    let attr = match metadata(path) { Ok(a) => a, Err(..) => return Err(e) };
+    let mut perms = attr.permissions();
+    if !perms.readonly() { return Err(e) }
+    perms.set_readonly(false);
+
+    if set_permissions(path, perms).is_err() { return Err(e) }
+    if fs_imp::unlink(path).is_ok() { return Ok(()) }
+
+    // Oops, try to put things back the way we found it
+    let _ = set_permissions(path, attr.permissions());
+    Err(e)
+}
+
+/// Given a path, query the file system to get information about a file,
+/// directory, etc.
+///
+/// This function will traverse soft links to query information about the
+/// destination file.
+///
+/// # Example
+///
+/// ```rust,no_run
+/// # fn foo() -> std::io::Result<()> {
+/// use std::fs;
+///
+/// let attr = try!(fs::metadata("/some/file/path.txt"));
+/// // inspect attr ...
+/// # Ok(())
+/// # }
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the user lacks the requisite
+/// permissions to perform a `metadata` call on the given `path` or if there
+/// is no entry in the filesystem at the provided path.
+pub fn metadata<P: AsPath + ?Sized>(path: &P) -> io::Result<Metadata> {
+    fs_imp::stat(path.as_path()).map(Metadata)
+}
+
+/// Rename a file or directory to a new name.
+///
+/// # Example
+///
+/// ```rust,no_run
+/// use std::fs;
+///
+/// fs::rename("foo", "bar");
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the provided `from` doesn't exist, if
+/// the process lacks permissions to view the contents, if `from` and `to`
+/// reside on separate filesystems, or if some other intermittent I/O error
+/// occurs.
+pub fn rename<P: AsPath + ?Sized, Q: AsPath + ?Sized>(from: &P, to: &Q)
+                                                      -> io::Result<()> {
+    fs_imp::rename(from.as_path(), to.as_path())
+}
+
+/// Copies the contents of one file to another. This function will also
+/// copy the permission bits of the original file to the destination file.
+///
+/// This function will **overwrite** the contents of `to`.
+///
+/// Note that if `from` and `to` both point to the same file, then the file
+/// will likely get truncated by this operation.
+///
+/// # Example
+///
+/// ```rust
+/// use std::fs;
+///
+/// fs::copy("foo.txt", "bar.txt");
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error in the following situations, but is not
+/// limited to just these cases:
+///
+/// * The `from` path is not a file
+/// * The `from` file does not exist
+/// * The current process does not have the permission rights to access
+///   `from` or write `to`
+pub fn copy<P: AsPath + ?Sized, Q: AsPath + ?Sized>(from: &P, to: &Q)
+                                                    -> io::Result<u64> {
+    let from = from.as_path();
+    if !from.is_file() {
+        return Err(Error::new(ErrorKind::MismatchedFileTypeForOperation,
+                              "the source path is not an existing file",
+                              None))
+    }
+
+    let mut reader = try!(File::open(from));
+    let mut writer = try!(File::create(to));
+    let perm = try!(reader.metadata()).permissions();
+
+    let ret = try!(io::copy(&mut reader, &mut writer));
+    try!(set_permissions(to, perm));
+    Ok(ret)
+}
+
+/// Creates a new hard link on the filesystem.
+///
+/// The `dst` path will be a link pointing to the `src` path. Note that systems
+/// often require these two paths to both be located on the same filesystem.
+pub fn hard_link<P: AsPath + ?Sized, Q: AsPath + ?Sized>(src: &P, dst: &Q)
+                                                         -> io::Result<()> {
+    fs_imp::link(src.as_path(), dst.as_path())
+}
+
+/// Creates a new soft link on the filesystem.
+///
+/// The `dst` path will be a soft link pointing to the `src` path.
+pub fn soft_link<P: AsPath + ?Sized, Q: AsPath + ?Sized>(src: &P, dst: &Q)
+                                                         -> io::Result<()> {
+    fs_imp::symlink(src.as_path(), dst.as_path())
+}
+
+/// Reads a soft link, returning the file that the link points to.
+///
+/// # Errors
+///
+/// This function will return an error on failure. Failure conditions include
+/// reading a file that does not exist or reading a file that is not a soft
+/// link.
+pub fn read_link<P: AsPath + ?Sized>(path: &P) -> io::Result<PathBuf> {
+    fs_imp::readlink(path.as_path())
+}
+
+/// Create a new, empty directory at the provided path
+///
+/// # Example
+///
+/// ```rust
+/// use std::fs;
+///
+/// fs::create_dir("/some/dir");
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the user lacks permissions to make a
+/// new directory at the provided `path`, or if the directory already exists.
+pub fn create_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    fs_imp::mkdir(path.as_path())
+}
+
+/// Recursively create a directory and all of its parent components if they
+/// are missing.
+///
+/// # Errors
+///
+/// This function will fail if any directory in the path specified by `path`
+/// does not already exist and it could not be created otherwise. The specific
+/// error conditions for when a directory is being created (after it is
+/// determined to not exist) are outlined by `fs::create_dir`.
+pub fn create_dir_all<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    let path = path.as_path();
+    if path.is_dir() { return Ok(()) }
+    match path.parent() {
+        Some(p) if p != path => try!(create_dir_all(p)),
+        _ => {}
+    }
+    create_dir(path)
+}
+
+/// Remove an existing, empty directory
+///
+/// # Example
+///
+/// ```rust
+/// use std::fs;
+///
+/// fs::remove_dir("/some/dir");
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the user lacks permissions to remove
+/// the directory at the provided `path`, or if the directory isn't empty.
+pub fn remove_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    fs_imp::rmdir(path.as_path())
+}
+
+/// Removes a directory at this path, after removing all its contents. Use
+/// carefully!
+///
+/// This function does **not** follow soft links and it will simply remove the
+/// soft link itself.
+///
+/// # Errors
+///
+/// See `file::remove_file` and `fs::remove_dir`
+pub fn remove_dir_all<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    let path = path.as_path();
+    for child in try!(read_dir(path)) {
+        let child = try!(child).path();
+        let stat = try!(lstat(&*child));
+        if stat.is_dir() {
+            try!(remove_dir_all(&*child));
+        } else {
+            try!(remove_file(&*child));
+        }
+    }
+    return remove_dir(path);
+
+    #[cfg(unix)]
+    fn lstat(path: &Path) -> io::Result<fs_imp::FileAttr> { fs_imp::lstat(path) }
+    #[cfg(windows)]
+    fn lstat(path: &Path) -> io::Result<fs_imp::FileAttr> { fs_imp::stat(path) }
+}
+
+/// Returns an iterator over the entries within a directory.
+///
+/// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
+/// be encountered after an iterator is initially constructed.
+///
+/// # Example
+///
+/// ```rust
+/// use std::io;
+/// use std::fs::{self, PathExt, DirEntry};
+/// use std::path::Path;
+///
+/// // one possible implementation of fs::walk_dir only visiting files
+/// fn visit_dirs(dir: &Path, cb: &mut FnMut(DirEntry)) -> io::Result<()> {
+///     if dir.is_dir() {
+///         for entry in try!(fs::read_dir(dir)) {
+///             let entry = try!(entry);
+///             if entry.path().is_dir() {
+///                 try!(visit_dirs(&entry.path(), cb));
+///             } else {
+///                 cb(entry);
+///             }
+///         }
+///     }
+///     Ok(())
+/// }
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the provided `path` doesn't exist, if
+/// the process lacks permissions to view the contents or if the `path` points
+/// at a non-directory file
+pub fn read_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<ReadDir> {
+    fs_imp::readdir(path.as_path()).map(ReadDir)
+}
+
+/// Returns an iterator that will recursively walk the directory structure
+/// rooted at `path`.
+///
+/// The path given will not be iterated over, and this will perform iteration in
+/// some top-down order.  The contents of unreadable subdirectories are ignored.
+///
+/// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
+/// be encountered after an iterator is initially constructed.
+pub fn walk_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<WalkDir> {
+    let start = try!(read_dir(path));
+    Ok(WalkDir { cur: Some(start), stack: Vec::new() })
+}
+
+impl Iterator for WalkDir {
+    type Item = io::Result<DirEntry>;
+
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        loop {
+            if let Some(ref mut cur) = self.cur {
+                match cur.next() {
+                    Some(Err(e)) => return Some(Err(e)),
+                    Some(Ok(next)) => {
+                        let path = next.path();
+                        if path.is_dir() {
+                            self.stack.push(read_dir(&*path));
+                        }
+                        return Some(Ok(next))
+                    }
+                    None => {}
+                }
+            }
+            self.cur = None;
+            match self.stack.pop() {
+                Some(Err(e)) => return Some(Err(e)),
+                Some(Ok(next)) => self.cur = Some(next),
+                None => return None,
+            }
+        }
+    }
+}
+
+/// Utility methods for paths.
+pub trait PathExt {
+    /// Get information on the file, directory, etc at this path.
+    ///
+    /// Consult the `fs::stat` documentation for more info.
+    ///
+    /// This call preserves identical runtime/error semantics with `file::stat`.
+    fn metadata(&self) -> io::Result<Metadata>;
+
+    /// Boolean value indicator whether the underlying file exists on the local
+    /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
+    fn exists(&self) -> bool;
+
+    /// Whether the underlying implementation (be it a file path, or something
+    /// else) points at a "regular file" on the FS. Will return false for paths
+    /// to non-existent locations or directories or other non-regular files
+    /// (named pipes, etc). Follows links when making this determination.
+    fn is_file(&self) -> bool;
+
+    /// Whether the underlying implementation (be it a file path, or something
+    /// else) is pointing at a directory in the underlying FS. Will return
+    /// false for paths to non-existent locations or if the item is not a
+    /// directory (eg files, named pipes, etc). Follows links when making this
+    /// determination.
+    fn is_dir(&self) -> bool;
+}
+
+impl PathExt for Path {
+    fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
+
+    fn exists(&self) -> bool { metadata(self).is_ok() }
+
+    fn is_file(&self) -> bool {
+        metadata(self).map(|s| s.is_file()).unwrap_or(false)
+    }
+    fn is_dir(&self) -> bool {
+        metadata(self).map(|s| s.is_dir()).unwrap_or(false)
+    }
+}
+
+/// Changes the timestamps for a file's last modification and access time.
+///
+/// The file at the path specified will have its last access time set to
+/// `atime` and its modification time set to `mtime`. The times specified should
+/// be in milliseconds.
+pub fn set_file_times<P: AsPath + ?Sized>(path: &P, accessed: u64,
+                                          modified: u64) -> io::Result<()> {
+    fs_imp::utimes(path.as_path(), accessed, modified)
+}
+
+/// Changes the permissions found on a file or a directory.
+///
+/// # Example
+///
+/// ```
+/// # fn foo() -> std::io::Result<()> {
+/// use std::fs;
+///
+/// let mut perms = try!(fs::metadata("foo.txt")).permissions();
+/// perms.set_readonly(true);
+/// try!(fs::set_permissions("foo.txt", perms));
+/// # Ok(())
+/// # }
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the provided `path` doesn't exist, if
+/// the process lacks permissions to change the attributes of the file, or if
+/// some other I/O error is encountered.
+pub fn set_permissions<P: AsPath + ?Sized>(path: &P, perm: Permissions)
+                                           -> io::Result<()> {
+    fs_imp::set_perm(path.as_path(), perm.0)
+}
+
+#[cfg(test)]
+mod tests {
+    use prelude::v1::*;
+    use io::prelude::*;
+
+    use fs::{self, File, OpenOptions};
+    use io::{ErrorKind, SeekFrom};
+    use path::PathBuf;
+    use path::Path as Path2;
+    use os;
+    use rand::{self, StdRng, Rng};
+    use str;
+
+    macro_rules! check { ($e:expr) => (
+        match $e {
+            Ok(t) => t,
+            Err(e) => panic!("{} failed with: {}", stringify!($e), e),
+        }
+    ) }
+
+    macro_rules! error { ($e:expr, $s:expr) => (
+        match $e {
+            Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
+            Err(ref err) => assert!(err.to_string().contains($s.as_slice()),
+                                    format!("`{}` did not contain `{}`", err, $s))
+        }
+    ) }
+
+    pub struct TempDir(PathBuf);
+
+    impl TempDir {
+        fn join(&self, path: &str) -> PathBuf {
+            let TempDir(ref p) = *self;
+            p.join(path)
+        }
+
+        fn path<'a>(&'a self) -> &'a Path2 {
+            let TempDir(ref p) = *self;
+            p
+        }
+    }
+
+    impl Drop for TempDir {
+        fn drop(&mut self) {
+            // Gee, seeing how we're testing the fs module I sure hope that we
+            // at least implement this correctly!
+            let TempDir(ref p) = *self;
+            check!(fs::remove_dir_all(p));
+        }
+    }
+
+    pub fn tmpdir() -> TempDir {
+        let s = os::tmpdir();
+        let p = Path2::new(s.as_str().unwrap());
+        let ret = p.join(&format!("rust-{}", rand::random::<u32>()));
+        check!(fs::create_dir(&ret));
+        TempDir(ret)
+    }
+
+    #[test]
+    fn file_test_io_smoke_test() {
+        let message = "it's alright. have a good time";
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test.txt");
+        {
+            let mut write_stream = check!(File::create(filename));
+            check!(write_stream.write(message.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+            let mut read_buf = [0; 1028];
+            let read_str = match check!(read_stream.read(&mut read_buf)) {
+                -1|0 => panic!("shouldn't happen"),
+                n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
+            };
+            assert_eq!(read_str.as_slice(), message);
+        }
+        check!(fs::remove_file(filename));
+    }
+
+    #[test]
+    fn invalid_path_raises() {
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_that_does_not_exist.txt");
+        let result = File::open(filename);
+
+        if cfg!(unix) {
+            error!(result, "o such file or directory");
+        }
+        // error!(result, "couldn't open path as file");
+        // error!(result, format!("path={}; mode=open; access=read", filename.display()));
+    }
+
+    #[test]
+    fn file_test_iounlinking_invalid_path_should_raise_condition() {
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
+
+        let result = fs::remove_file(filename);
+
+        if cfg!(unix) {
+            error!(result, "o such file or directory");
+        }
+        // error!(result, "couldn't unlink path");
+        // error!(result, format!("path={}", filename.display()));
+    }
+
+    #[test]
+    fn file_test_io_non_positional_read() {
+        let message: &str = "ten-four";
+        let mut read_mem = [0; 8];
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
+        {
+            let mut rw_stream = check!(File::create(filename));
+            check!(rw_stream.write(message.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+            {
+                let read_buf = &mut read_mem[0..4];
+                check!(read_stream.read(read_buf));
+            }
+            {
+                let read_buf = &mut read_mem[4..8];
+                check!(read_stream.read(read_buf));
+            }
+        }
+        check!(fs::remove_file(filename));
+        let read_str = str::from_utf8(&read_mem).unwrap();
+        assert_eq!(read_str, message);
+    }
+
+    #[test]
+    fn file_test_io_seek_and_tell_smoke_test() {
+        let message = "ten-four";
+        let mut read_mem = [0; 4];
+        let set_cursor = 4 as u64;
+        let mut tell_pos_pre_read;
+        let mut tell_pos_post_read;
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
+        {
+            let mut rw_stream = check!(File::create(filename));
+            check!(rw_stream.write(message.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+            check!(read_stream.seek(SeekFrom::Start(set_cursor)));
+            tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
+            check!(read_stream.read(&mut read_mem));
+            tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
+        }
+        check!(fs::remove_file(filename));
+        let read_str = str::from_utf8(&read_mem).unwrap();
+        assert_eq!(read_str, &message[4..8]);
+        assert_eq!(tell_pos_pre_read, set_cursor);
+        assert_eq!(tell_pos_post_read, message.len() as u64);
+    }
+
+    #[test]
+    fn file_test_io_seek_and_write() {
+        let initial_msg =   "food-is-yummy";
+        let overwrite_msg =    "-the-bar!!";
+        let final_msg =     "foo-the-bar!!";
+        let seek_idx = 3;
+        let mut read_mem = [0; 13];
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
+        {
+            let mut rw_stream = check!(File::create(filename));
+            check!(rw_stream.write(initial_msg.as_bytes()));
+            check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
+            check!(rw_stream.write(overwrite_msg.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+            check!(read_stream.read(&mut read_mem));
+        }
+        check!(fs::remove_file(filename));
+        let read_str = str::from_utf8(&read_mem).unwrap();
+        assert!(read_str == final_msg);
+    }
+
+    #[test]
+    fn file_test_io_seek_shakedown() {
+        //                   01234567890123
+        let initial_msg =   "qwer-asdf-zxcv";
+        let chunk_one: &str = "qwer";
+        let chunk_two: &str = "asdf";
+        let chunk_three: &str = "zxcv";
+        let mut read_mem = [0; 4];
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
+        {
+            let mut rw_stream = check!(File::create(filename));
+            check!(rw_stream.write(initial_msg.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+
+            check!(read_stream.seek(SeekFrom::End(-4)));
+            check!(read_stream.read(&mut read_mem));
+            assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
+
+            check!(read_stream.seek(SeekFrom::Current(-9)));
+            check!(read_stream.read(&mut read_mem));
+            assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
+
+            check!(read_stream.seek(SeekFrom::Start(0)));
+            check!(read_stream.read(&mut read_mem));
+            assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
+        }
+        check!(fs::remove_file(filename));
+    }
+
+    #[test]
+    fn file_test_stat_is_correct_on_is_file() {
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
+        {
+            let mut opts = OpenOptions::new();
+            let mut fs = check!(opts.read(true).write(true)
+                                    .create(true).open(filename));
+            let msg = "hw";
+            fs.write(msg.as_bytes()).unwrap();
+
+            let fstat_res = check!(fs.metadata());
+            assert!(fstat_res.is_file());
+        }
+        let stat_res_fn = check!(fs::metadata(filename));
+        assert!(stat_res_fn.is_file());
+        let stat_res_meth = check!(filename.metadata());
+        assert!(stat_res_meth.is_file());
+        check!(fs::remove_file(filename));
+    }
+
+    #[test]
+    fn file_test_stat_is_correct_on_is_dir() {
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_stat_correct_on_is_dir");
+        check!(fs::create_dir(filename));
+        let stat_res_fn = check!(fs::metadata(filename));
+        assert!(stat_res_fn.is_dir());
+        let stat_res_meth = check!(filename.metadata());
+        assert!(stat_res_meth.is_dir());
+        check!(fs::remove_dir(filename));
+    }
+
+    #[test]
+    fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("fileinfo_false_on_dir");
+        check!(fs::create_dir(dir));
+        assert!(dir.is_file() == false);
+        check!(fs::remove_dir(dir));
+    }
+
+    #[test]
+    fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
+        let tmpdir = tmpdir();
+        let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
+        check!(check!(File::create(file)).write(b"foo"));
+        assert!(file.exists());
+        check!(fs::remove_file(file));
+        assert!(!file.exists());
+    }
+
+    #[test]
+    fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("before_and_after_dir");
+        assert!(!dir.exists());
+        check!(fs::create_dir(dir));
+        assert!(dir.exists());
+        assert!(dir.is_dir());
+        check!(fs::remove_dir(dir));
+        assert!(!dir.exists());
+    }
+
+    #[test]
+    fn file_test_directoryinfo_readdir() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("di_readdir");
+        check!(fs::create_dir(dir));
+        let prefix = "foo";
+        for n in range(0, 3) {
+            let f = dir.join(&format!("{}.txt", n));
+            let mut w = check!(File::create(&f));
+            let msg_str = format!("{}{}", prefix, n.to_string());
+            let msg = msg_str.as_bytes();
+            check!(w.write(msg));
+        }
+        let mut files = check!(fs::read_dir(dir));
+        let mut mem = [0u8; 4];
+        for f in files {
+            let f = f.unwrap().path();
+            {
+                let n = f.file_stem().unwrap();
+                check!(check!(File::open(&f)).read(&mut mem));
+                let read_str = str::from_utf8(&mem).unwrap();
+                let expected = format!("{}{}", prefix, n.to_str().unwrap());
+                assert_eq!(expected.as_slice(), read_str);
+            }
+            check!(fs::remove_file(&f));
+        }
+        check!(fs::remove_dir(dir));
+    }
+
+    #[test]
+    fn file_test_walk_dir() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("walk_dir");
+        check!(fs::create_dir(dir));
+
+        let dir1 = &dir.join("01/02/03");
+        check!(fs::create_dir_all(dir1));
+        check!(File::create(&dir1.join("04")));
+
+        let dir2 = &dir.join("11/12/13");
+        check!(fs::create_dir_all(dir2));
+        check!(File::create(&dir2.join("14")));
+
+        let mut files = check!(fs::walk_dir(dir));
+        let mut cur = [0u8; 2];
+        for f in files {
+            let f = f.unwrap().path();
+            let stem = f.file_stem().unwrap().to_str().unwrap();
+            let root = stem.as_bytes()[0] - b'0';
+            let name = stem.as_bytes()[1] - b'0';
+            assert!(cur[root as usize] < name);
+            cur[root as usize] = name;
+        }
+
+        check!(fs::remove_dir_all(dir));
+    }
+
+    #[test]
+    fn mkdir_path_already_exists_error() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("mkdir_error_twice");
+        check!(fs::create_dir(dir));
+        let e = fs::create_dir(dir).err().unwrap();
+        assert_eq!(e.kind(), ErrorKind::PathAlreadyExists);
+    }
+
+    #[test]
+    fn recursive_mkdir() {
+        let tmpdir = tmpdir();
+        let dir = tmpdir.join("d1/d2");
+        check!(fs::create_dir_all(&dir));
+        assert!(dir.is_dir())
+    }
+
+    #[test]
+    fn recursive_mkdir_failure() {
+        let tmpdir = tmpdir();
+        let dir = tmpdir.join("d1");
+        let file = dir.join("f1");
+
+        check!(fs::create_dir_all(&dir));
+        check!(File::create(&file));
+
+        let result = fs::create_dir_all(&file);
+
+        assert!(result.is_err());
+        // error!(result, "couldn't recursively mkdir");
+        // error!(result, "couldn't create directory");
+        // error!(result, "mode=0700");
+        // error!(result, format!("path={}", file.display()));
+    }
+
+    #[test]
+    fn recursive_mkdir_slash() {
+        check!(fs::create_dir_all(&Path2::new("/")));
+    }
+
+    // FIXME(#12795) depends on lstat to work on windows
+    #[cfg(not(windows))]
+    #[test]
+    fn recursive_rmdir() {
+        let tmpdir = tmpdir();
+        let d1 = tmpdir.join("d1");
+        let dt = d1.join("t");
+        let dtt = dt.join("t");
+        let d2 = tmpdir.join("d2");
+        let canary = d2.join("do_not_delete");
+        check!(fs::create_dir_all(&dtt));
+        check!(fs::create_dir_all(&d2));
+        check!(check!(File::create(&canary)).write(b"foo"));
+        check!(fs::soft_link(&d2, &dt.join("d2")));
+        check!(fs::remove_dir_all(&d1));
+
+        assert!(!d1.is_dir());
+        assert!(canary.exists());
+    }
+
+    #[test]
+    fn unicode_path_is_dir() {
+        assert!(Path2::new(".").is_dir());
+        assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
+
+        let tmpdir = tmpdir();
+
+        let mut dirpath = tmpdir.path().to_path_buf();
+        dirpath.push(&format!("test-가一ー你好"));
+        check!(fs::create_dir(&dirpath));
+        assert!(dirpath.is_dir());
+
+        let mut filepath = dirpath;
+        filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
+        check!(File::create(&filepath)); // ignore return; touch only
+        assert!(!filepath.is_dir());
+        assert!(filepath.exists());
+    }
+
+    #[test]
+    fn unicode_path_exists() {
+        assert!(Path2::new(".").exists());
+        assert!(!Path2::new("test/nonexistent-bogus-path").exists());
+
+        let tmpdir = tmpdir();
+        let unicode = tmpdir.path();
+        let unicode = unicode.join(&format!("test-각丁ー再见"));
+        check!(fs::create_dir(&unicode));
+        assert!(unicode.exists());
+        assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
+    }
+
+    #[test]
+    fn copy_file_does_not_exist() {
+        let from = Path2::new("test/nonexistent-bogus-path");
+        let to = Path2::new("test/other-bogus-path");
+
+        match fs::copy(&from, &to) {
+            Ok(..) => panic!(),
+            Err(..) => {
+                assert!(!from.exists());
+                assert!(!to.exists());
+            }
+        }
+    }
+
+    #[test]
+    fn copy_file_ok() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in.txt");
+        let out = tmpdir.join("out.txt");
+
+        check!(check!(File::create(&input)).write(b"hello"));
+        check!(fs::copy(&input, &out));
+        let mut v = Vec::new();
+        check!(check!(File::open(&out)).read_to_end(&mut v));
+        assert_eq!(v.as_slice(), b"hello");
+
+        assert_eq!(check!(input.metadata()).permissions(),
+                   check!(out.metadata()).permissions());
+    }
+
+    #[test]
+    fn copy_file_dst_dir() {
+        let tmpdir = tmpdir();
+        let out = tmpdir.join("out");
+
+        check!(File::create(&out));
+        match fs::copy(&*out, tmpdir.path()) {
+            Ok(..) => panic!(), Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn copy_file_dst_exists() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in");
+        let output = tmpdir.join("out");
+
+        check!(check!(File::create(&input)).write("foo".as_bytes()));
+        check!(check!(File::create(&output)).write("bar".as_bytes()));
+        check!(fs::copy(&input, &output));
+
+        let mut v = Vec::new();
+        check!(check!(File::open(&output)).read_to_end(&mut v));
+        assert_eq!(v, b"foo".to_vec());
+    }
+
+    #[test]
+    fn copy_file_src_dir() {
+        let tmpdir = tmpdir();
+        let out = tmpdir.join("out");
+
+        match fs::copy(tmpdir.path(), &out) {
+            Ok(..) => panic!(), Err(..) => {}
+        }
+        assert!(!out.exists());
+    }
+
+    #[test]
+    fn copy_file_preserves_perm_bits() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in.txt");
+        let out = tmpdir.join("out.txt");
+
+        let attr = check!(check!(File::create(&input)).metadata());
+        let mut p = attr.permissions();
+        p.set_readonly(true);
+        check!(fs::set_permissions(&input, p));
+        check!(fs::copy(&input, &out));
+        assert!(check!(out.metadata()).permissions().readonly());
+    }
+
+    #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
+    #[test]
+    fn symlinks_work() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in.txt");
+        let out = tmpdir.join("out.txt");
+
+        check!(check!(File::create(&input)).write("foobar".as_bytes()));
+        check!(fs::soft_link(&input, &out));
+        // if cfg!(not(windows)) {
+        //     assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
+        //     assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
+        // }
+        assert_eq!(check!(fs::metadata(&out)).len(),
+                   check!(fs::metadata(&input)).len());
+        let mut v = Vec::new();
+        check!(check!(File::open(&out)).read_to_end(&mut v));
+        assert_eq!(v, b"foobar".to_vec());
+    }
+
+    #[cfg(not(windows))] // apparently windows doesn't like symlinks
+    #[test]
+    fn symlink_noexist() {
+        let tmpdir = tmpdir();
+        // symlinks can point to things that don't exist
+        check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
+        assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
+                   tmpdir.join("foo"));
+    }
+
+    #[test]
+    fn readlink_not_symlink() {
+        let tmpdir = tmpdir();
+        match fs::read_link(tmpdir.path()) {
+            Ok(..) => panic!("wanted a failure"),
+            Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn links_work() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in.txt");
+        let out = tmpdir.join("out.txt");
+
+        check!(check!(File::create(&input)).write("foobar".as_bytes()));
+        check!(fs::hard_link(&input, &out));
+        assert_eq!(check!(fs::metadata(&out)).len(),
+                   check!(fs::metadata(&input)).len());
+        assert_eq!(check!(fs::metadata(&out)).len(),
+                   check!(input.metadata()).len());
+        let mut v = Vec::new();
+        check!(check!(File::open(&out)).read_to_end(&mut v));
+        assert_eq!(v, b"foobar".to_vec());
+
+        // can't link to yourself
+        match fs::hard_link(&input, &input) {
+            Ok(..) => panic!("wanted a failure"),
+            Err(..) => {}
+        }
+        // can't link to something that doesn't exist
+        match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
+            Ok(..) => panic!("wanted a failure"),
+            Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn chmod_works() {
+        let tmpdir = tmpdir();
+        let file = tmpdir.join("in.txt");
+
+        check!(File::create(&file));
+        let attr = check!(fs::metadata(&file));
+        assert!(!attr.permissions().readonly());
+        let mut p = attr.permissions();
+        p.set_readonly(true);
+        check!(fs::set_permissions(&file, p.clone()));
+        let attr = check!(fs::metadata(&file));
+        assert!(attr.permissions().readonly());
+
+        match fs::set_permissions(&tmpdir.join("foo"), p) {
+            Ok(..) => panic!("wanted a panic"),
+            Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn sync_doesnt_kill_anything() {
+        let tmpdir = tmpdir();
+        let path = tmpdir.join("in.txt");
+
+        let mut file = check!(File::create(&path));
+        check!(file.sync_all());
+        check!(file.sync_data());
+        check!(file.write(b"foo"));
+        check!(file.sync_all());
+        check!(file.sync_data());
+    }
+
+    #[test]
+    fn truncate_works() {
+        let tmpdir = tmpdir();
+        let path = tmpdir.join("in.txt");
+
+        let mut file = check!(File::create(&path));
+        check!(file.write(b"foo"));
+        check!(file.sync_all());
+
+        // Do some simple things with truncation
+        assert_eq!(check!(file.metadata()).len(), 3);
+        check!(file.set_len(10));
+        assert_eq!(check!(file.metadata()).len(), 10);
+        check!(file.write(b"bar"));
+        check!(file.sync_all());
+        assert_eq!(check!(file.metadata()).len(), 10);
+
+        let mut v = Vec::new();
+        check!(check!(File::open(&path)).read_to_end(&mut v));
+        assert_eq!(v, b"foobar\0\0\0\0".to_vec());
+
+        // Truncate to a smaller length, don't seek, and then write something.
+        // Ensure that the intermediate zeroes are all filled in (we're seeked
+        // past the end of the file).
+        check!(file.set_len(2));
+        assert_eq!(check!(file.metadata()).len(), 2);
+        check!(file.write(b"wut"));
+        check!(file.sync_all());
+        assert_eq!(check!(file.metadata()).len(), 9);
+        let mut v = Vec::new();
+        check!(check!(File::open(&path)).read_to_end(&mut v));
+        assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
+    }
+
+    #[test]
+    fn open_flavors() {
+        use fs::OpenOptions as OO;
+        fn c<T: Clone>(t: &T) -> T { t.clone() }
+
+        let tmpdir = tmpdir();
+
+        let mut r = OO::new(); r.read(true);
+        let mut w = OO::new(); w.write(true);
+        let mut rw = OO::new(); rw.write(true).read(true);
+
+        match r.open(&tmpdir.join("a")) {
+            Ok(..) => panic!(), Err(..) => {}
+        }
+
+        // Perform each one twice to make sure that it succeeds the second time
+        // (where the file exists)
+        check!(c(&w).create(true).open(&tmpdir.join("b")));
+        assert!(tmpdir.join("b").exists());
+        check!(c(&w).create(true).open(&tmpdir.join("b")));
+        check!(w.open(&tmpdir.join("b")));
+
+        check!(c(&rw).create(true).open(&tmpdir.join("c")));
+        assert!(tmpdir.join("c").exists());
+        check!(c(&rw).create(true).open(&tmpdir.join("c")));
+        check!(rw.open(&tmpdir.join("c")));
+
+        check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
+        assert!(tmpdir.join("d").exists());
+        check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
+        check!(c(&w).append(true).open(&tmpdir.join("d")));
+
+        check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
+        assert!(tmpdir.join("e").exists());
+        check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
+        check!(c(&rw).append(true).open(&tmpdir.join("e")));
+
+        check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
+        assert!(tmpdir.join("f").exists());
+        check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
+        check!(c(&w).truncate(true).open(&tmpdir.join("f")));
+
+        check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
+        assert!(tmpdir.join("g").exists());
+        check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
+        check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
+
+        check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
+        check!(r.open(&tmpdir.join("h")));
+        {
+            let mut f = check!(r.open(&tmpdir.join("h")));
+            assert!(f.write("wut".as_bytes()).is_err());
+        }
+        assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
+        {
+            let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
+            check!(f.write("bar".as_bytes()));
+        }
+        assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
+        {
+            let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
+            check!(f.write("bar".as_bytes()));
+        }
+        assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
+    }
+
+    #[test]
+    fn utime() {
+        let tmpdir = tmpdir();
+        let path = tmpdir.join("a");
+        check!(File::create(&path));
+        // These numbers have to be bigger than the time in the day to account
+        // for timezones Windows in particular will fail in certain timezones
+        // with small enough values
+        check!(fs::set_file_times(&path, 100000, 200000));
+        assert_eq!(check!(path.metadata()).accessed(), 100000);
+        assert_eq!(check!(path.metadata()).modified(), 200000);
+    }
+
+    #[test]
+    fn utime_noexist() {
+        let tmpdir = tmpdir();
+
+        match fs::set_file_times(&tmpdir.join("a"), 100, 200) {
+            Ok(..) => panic!(),
+            Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn binary_file() {
+        let mut bytes = [0; 1024];
+        StdRng::new().ok().unwrap().fill_bytes(&mut bytes);
+
+        let tmpdir = tmpdir();
+
+        check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
+        let mut v = Vec::new();
+        check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
+        assert!(v == bytes.as_slice());
+    }
+
+    #[test]
+    fn unlink_readonly() {
+        let tmpdir = tmpdir();
+        let path = tmpdir.join("file");
+        check!(File::create(&path));
+        let mut perm = check!(fs::metadata(&path)).permissions();
+        perm.set_readonly(true);
+        check!(fs::set_permissions(&path, perm));
+        check!(fs::remove_file(&path));
+    }
+}
index 0832206a48b6086bf77b0e5cca1fdb2f87a9c88b..2668baba095b875f7436d5ff675827f577be8518 100644 (file)
@@ -24,7 +24,6 @@
 use fmt;
 use iter::Iterator;
 use marker::Sized;
-use mem;
 use ops::{Drop, FnOnce};
 use option::Option::{self, Some, None};
 use ptr::PtrExt;
@@ -69,8 +68,8 @@ fn with_end_to_cap<F>(v: &mut Vec<u8>, f: F) -> Result<usize>
     unsafe {
         let n = try!(f({
             let base = v.as_mut_ptr().offset(v.len() as isize);
-            black_box(slice::from_raw_mut_buf(mem::copy_lifetime(v, &base),
-                                              v.capacity() - v.len()))
+            black_box(slice::from_raw_parts_mut(base,
+                                                v.capacity() - v.len()))
         }));
 
         // If the closure (typically a `read` implementation) reported that it
@@ -97,7 +96,7 @@ unsafe fn black_box<T>(mut dummy: T) -> T {
 //
 // To this end, we use an RAII guard (to protect against panics) which updates
 // the length of the string when it is dropped. This guard initially truncates
-// the string to the prior length and only afer we've validated that the
+// the string to the prior length and only after we've validated that the
 // new contents are valid UTF-8 do we allow it to set a longer length.
 //
 // The unsafety in this function is twofold:
@@ -664,7 +663,7 @@ impl<T> Take<T> {
     ///
     /// # Note
     ///
-    /// This instance may reach EOF after reading fewer bytes than indiccated by
+    /// This instance may reach EOF after reading fewer bytes than indicated by
     /// this method if the underlying `Read` instance reaches EOF.
     pub fn limit(&self) -> u64 { self.limit }
 }
index 475ada2ff84b891102ba96ada6868fb84b51fc0f..637b1950985fd79f2e9e5c278192aead8c048157 100644 (file)
@@ -22,6 +22,7 @@
 //! contained in this module.
 
 pub use super::{Read, ReadExt, Write, WriteExt, BufRead, BufReadExt};
+pub use fs::PathExt;
 
 // FIXME: pub use as `Seek` when the name isn't in the actual prelude any more
 pub use super::Seek as NewSeek;
index 14e779f9c4a8edad733e408b7baa5a97a17af2df..967789dd41144bcbec8ed4505724581f000b71e4 100644 (file)
 #![cfg_attr(test, feature(test))]
 
 // Don't link to std. We are std.
+#![feature(no_std)]
 #![no_std]
 
 #![deny(missing_docs)]
 extern crate core;
 
 #[macro_use]
-#[macro_reexport(vec)]
+#[macro_reexport(vec, format)]
 extern crate "collections" as core_collections;
 
 #[allow(deprecated)] extern crate "rand" as core_rand;
 #[cfg(not(test))] pub use alloc::boxed;
 pub use alloc::rc;
 
+pub use core_collections::fmt;
 pub use core_collections::slice;
 pub use core_collections::str;
 pub use core_collections::string;
 
 pub mod dynamic_lib;
 pub mod ffi;
-pub mod fmt;
 pub mod old_io;
 pub mod io;
+pub mod fs;
 pub mod os;
 pub mod env;
 pub mod path;
 // can be resolved within libstd.
 #[doc(hidden)]
 mod std {
+    // NOTE: remove after next snapshot
     // mods used for deriving
-    pub use clone;
-    pub use cmp;
-    pub use hash;
-    pub use default;
+    #[cfg(stage0)] pub use clone;
+    #[cfg(stage0)] pub use cmp;
+    #[cfg(stage0)] pub use hash;
+    #[cfg(stage0)] pub use default;
 
     pub use sync; // used for select!()
     pub use error; // used for try!()
@@ -312,5 +315,6 @@ mod std {
 
     pub use boxed; // used for vec![]
     // for-loops
-    pub use iter;
+    // NOTE: remove after next snapshot
+    #[cfg(stage0)] pub use iter;
 }
index e91e8241a55beb0f2946eeb178cc952625060d35..6a2aafcf8f396d985b52883a2c1a938be3c0fbd8 100644 (file)
@@ -70,6 +70,7 @@ macro_rules! panic {
 /// format!("hello {}", "world!");
 /// format!("x = {}, y = {y}", 10, y = 30);
 /// ```
+#[cfg(stage0)] // NOTE: remove after snapshot
 #[macro_export]
 #[stable(feature = "rust1", since = "1.0.0")]
 macro_rules! format {
index a996ad1f5b35d30fbc2ef605363b9b51bf29e9c6..29532cb9b02d09fcc9031f44db9d004c082573c5 100644 (file)
@@ -29,7 +29,7 @@
 pub use core::num::{from_uint, from_u8, from_u16, from_u32, from_u64};
 pub use core::num::{from_f32, from_f64};
 pub use core::num::{FromStrRadix, from_str_radix};
-pub use core::num::{FpCategory};
+pub use core::num::{FpCategory, ParseIntError, ParseFloatError};
 
 use option::Option;
 
index 9c4741b3ce316f0eefa0e06343eda48fe8f223d5..4ae7d3437fd93f689f8bdaeb67257f05c50641aa 100644 (file)
@@ -321,10 +321,10 @@ pub fn float_to_str_bytes_common<T: Float>(
         // cut off the one extra digit, and depending on its value
         // round the remaining ones.
         if limit_digits && dig == digit_count {
-            let ascii2value = |&: chr: u8| {
+            let ascii2value = |chr: u8| {
                 (chr as char).to_digit(radix).unwrap()
             };
-            let value2ascii = |&: val: uint| {
+            let value2ascii = |val: uint| {
                 char::from_digit(val, radix).unwrap() as u8
             };
 
index 586cc1477f8dd6ecc35cd5633330e9d4ef74c7bb..59a437ad916537e23c47992b91b0b72bab8e6464 100644 (file)
@@ -97,7 +97,7 @@ pub fn into_inner(self) -> R { self.inner }
 impl<R: Reader> Buffer for BufferedReader<R> {
     fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> {
         if self.pos == self.cap {
-            self.cap = try!(self.inner.read(self.buf.as_mut_slice()));
+            self.cap = try!(self.inner.read(&mut self.buf));
             self.pos = 0;
         }
         Ok(&self.buf[self.pos..self.cap])
index feb2ef6f4f3ca1d94bba0ad555e7d47b27032f93..d8f9b1bb3feae4cd2c52d15f67f40bfaaddde6f1 100644 (file)
@@ -191,14 +191,14 @@ fn test_rx_reader() {
         let a: &[u8] = &[7,8,6];
         assert_eq!(a, buf);
 
-        match reader.read(buf.as_mut_slice()) {
+        match reader.read(&mut buf) {
             Ok(..) => panic!(),
             Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
         }
         assert_eq!(a, buf);
 
         // Ensure it continues to panic in the same way.
-        match reader.read(buf.as_mut_slice()) {
+        match reader.read(&mut buf) {
             Ok(..) => panic!(),
             Err(e) => assert_eq!(e.kind, old_io::EndOfFile),
         }
index d729c2800ce13c3c134206866b219468fe0155e6..95284f2ca40365b9f828d16ad953316c535372b3 100644 (file)
@@ -24,7 +24,7 @@
 use option::Option::{Some, None};
 use ptr::PtrExt;
 use result::Result::{Ok, Err};
-use slice::{SliceExt, AsSlice};
+use slice::SliceExt;
 
 /// An iterator that reads a single byte on each iteration,
 /// until `.read_byte()` returns `EndOfFile`.
@@ -101,7 +101,7 @@ pub fn u64_to_le_bytes<T, F>(n: u64, size: uint, f: F) -> T where
             n >>= 8;
             i -= 1u;
         }
-        f(bytes.as_slice())
+        f(&bytes)
       }
     }
 }
@@ -140,7 +140,7 @@ pub fn u64_to_be_bytes<T, F>(n: u64, size: uint, f: F) -> T where
             bytes.push((n >> shift) as u8);
             i -= 1u;
         }
-        f(bytes.as_slice())
+        f(&bytes)
       }
     }
 }
@@ -455,7 +455,7 @@ fn test_read_f32() {
         let buf = vec![0x41, 0x02, 0x00, 0x00];
 
         let mut writer = Vec::new();
-        writer.write(buf.as_slice()).unwrap();
+        writer.write(&buf).unwrap();
 
         let mut reader = MemReader::new(writer);
         let f = reader.read_be_f32().unwrap();
@@ -523,7 +523,7 @@ macro_rules! u64_from_be_bytes_bench_impl {
             $b.iter(|| {
                 let mut i = $start_index;
                 while i < data.len() {
-                    sum += u64_from_be_bytes(data.as_slice(), i, $size);
+                    sum += u64_from_be_bytes(&data, i, $size);
                     i += $stride;
                 }
             });
index 67e3fddfd05a5401d10b0ea5b9a175e6dede52a2..4e9c1b360552c4ee21d69146e72cf6261ac2bd9e 100644 (file)
@@ -840,7 +840,7 @@ macro_rules! check { ($e:expr) => (
     macro_rules! error { ($e:expr, $s:expr) => (
         match $e {
             Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
-            Err(ref err) => assert!(err.to_string().contains($s.as_slice()),
+            Err(ref err) => assert!(err.to_string().contains($s),
                                     format!("`{}` did not contain `{}`", err, $s))
         }
     ) }
@@ -892,7 +892,7 @@ fn file_test_io_smoke_test() {
                 -1|0 => panic!("shouldn't happen"),
                 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
             };
-            assert_eq!(read_str.as_slice(), message);
+            assert_eq!(read_str, message);
         }
         check!(unlink(filename));
     }
@@ -907,7 +907,7 @@ fn invalid_path_raises() {
         if cfg!(unix) {
             error!(result, "no such file or directory");
         }
-        error!(result, format!("path={}; mode=open; access=read", filename.display()));
+        error!(result, &format!("path={}; mode=open; access=read", filename.display()));
     }
 
     #[test]
@@ -921,7 +921,7 @@ fn file_test_iounlinking_invalid_path_should_raise_condition() {
         if cfg!(unix) {
             error!(result, "no such file or directory");
         }
-        error!(result, format!("path={}", filename.display()));
+        error!(result, &format!("path={}", filename.display()));
     }
 
     #[test]
@@ -1120,7 +1120,7 @@ fn file_test_directoryinfo_readdir() {
                     None|Some("") => panic!("really shouldn't happen.."),
                     Some(n) => format!("{}{}", prefix, n),
                 };
-                assert_eq!(expected.as_slice(), read_str);
+                assert_eq!(expected, read_str);
             }
             check!(unlink(f));
         }
@@ -1189,7 +1189,7 @@ fn recursive_mkdir_failure() {
         error!(result, "couldn't recursively mkdir");
         error!(result, "couldn't create directory");
         error!(result, "mode=0700");
-        error!(result, format!("path={}", file.display()));
+        error!(result, &format!("path={}", file.display()));
     }
 
     #[test]
@@ -1255,9 +1255,9 @@ fn copy_file_does_not_exist() {
         let to = Path::new("test/other-bogus-path");
 
         error!(copy(&from, &to),
-            format!("couldn't copy path (the source path is not an \
-                    existing file; from={:?}; to={:?})",
-                    from.display(), to.display()));
+            &format!("couldn't copy path (the source path is not an \
+                     existing file; from={:?}; to={:?})",
+                     from.display(), to.display()));
 
         match copy(&from, &to) {
             Ok(..) => panic!(),
@@ -1277,7 +1277,7 @@ fn copy_file_ok() {
         check!(File::create(&input).write(b"hello"));
         check!(copy(&input, &out));
         let contents = check!(File::open(&out).read_to_end());
-        assert_eq!(contents.as_slice(), b"hello");
+        assert_eq!(contents, b"hello");
 
         assert_eq!(check!(input.stat()).perm, check!(out.stat()).perm);
     }
index ddb364a703a3a23186856f323666a41f17dfa580..8f32703f200556b5c48563d9a3f28236ed808e0e 100644 (file)
@@ -17,7 +17,7 @@
 use result::Result::{Err, Ok};
 use old_io;
 use old_io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
-use slice::{self, AsSlice, SliceExt};
+use slice::{self, SliceExt};
 use vec::Vec;
 
 const BUF_CAPACITY: uint = 128;
@@ -92,7 +92,7 @@ pub fn from_vec(buf: Vec<u8>) -> MemWriter {
     /// Acquires an immutable reference to the underlying buffer of this
     /// `MemWriter`.
     #[inline]
-    pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
+    pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf }
 
     /// Unwraps this `MemWriter`, returning the underlying buffer
     #[inline]
@@ -147,7 +147,7 @@ pub fn eof(&self) -> bool { self.pos >= self.buf.len() }
     /// No method is exposed for acquiring a mutable reference to the buffer
     /// because it could corrupt the state of this `MemReader`.
     #[inline]
-    pub fn get_ref<'a>(&'a self) -> &'a [u8] { self.buf.as_slice() }
+    pub fn get_ref<'a>(&'a self) -> &'a [u8] { &self.buf }
 
     /// Unwraps this `MemReader`, returning the underlying buffer
     #[inline]
@@ -407,7 +407,7 @@ fn test_vec_writer() {
         writer.write(&[1, 2, 3]).unwrap();
         writer.write(&[4, 5, 6, 7]).unwrap();
         let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
-        assert_eq!(writer.as_slice(), b);
+        assert_eq!(writer, b);
     }
 
     #[test]
@@ -511,24 +511,24 @@ fn test_mem_reader() {
     #[test]
     fn test_slice_reader() {
         let in_buf = vec![0, 1, 2, 3, 4, 5, 6, 7];
-        let mut reader = &mut in_buf.as_slice();
+        let mut reader = &mut &*in_buf;
         let mut buf = [];
         assert_eq!(reader.read(&mut buf), Ok(0));
         let mut buf = [0];
         assert_eq!(reader.read(&mut buf), Ok(1));
         assert_eq!(reader.len(), 7);
         let b: &[_] = &[0];
-        assert_eq!(buf.as_slice(), b);
+        assert_eq!(buf, b);
         let mut buf = [0; 4];
         assert_eq!(reader.read(&mut buf), Ok(4));
         assert_eq!(reader.len(), 3);
         let b: &[_] = &[1, 2, 3, 4];
-        assert_eq!(buf.as_slice(), b);
+        assert_eq!(buf, b);
         assert_eq!(reader.read(&mut buf), Ok(3));
         let b: &[_] = &[5, 6, 7];
         assert_eq!(&buf[..3], b);
         assert!(reader.read(&mut buf).is_err());
-        let mut reader = &mut in_buf.as_slice();
+        let mut reader = &mut &*in_buf;
         assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3));
         assert_eq!(reader.read_until(3).unwrap(), vec!(4, 5, 6, 7));
         assert!(reader.read(&mut buf).is_err());
@@ -537,7 +537,7 @@ fn test_slice_reader() {
     #[test]
     fn test_buf_reader() {
         let in_buf = vec![0, 1, 2, 3, 4, 5, 6, 7];
-        let mut reader = BufReader::new(in_buf.as_slice());
+        let mut reader = BufReader::new(&in_buf);
         let mut buf = [];
         assert_eq!(reader.read(&mut buf), Ok(0));
         assert_eq!(reader.tell(), Ok(0));
@@ -555,7 +555,7 @@ fn test_buf_reader() {
         let b: &[_] = &[5, 6, 7];
         assert_eq!(&buf[..3], b);
         assert!(reader.read(&mut buf).is_err());
-        let mut reader = BufReader::new(in_buf.as_slice());
+        let mut reader = BufReader::new(&in_buf);
         assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3));
         assert_eq!(reader.read_until(3).unwrap(), vec!(4, 5, 6, 7));
         assert!(reader.read(&mut buf).is_err());
@@ -664,7 +664,7 @@ fn do_bench_mem_writer(b: &mut Bencher, times: uint, len: uint) {
         b.iter(|| {
             let mut wr = MemWriter::new();
             for _ in 0..times {
-                wr.write(src.as_slice()).unwrap();
+                wr.write(&src).unwrap();
             }
 
             let v = wr.into_inner();
@@ -722,7 +722,7 @@ fn bench_mem_reader(b: &mut Bencher) {
                 for _i in 0u..10 {
                     let mut buf = [0 as u8; 10];
                     rdr.read(&mut buf).unwrap();
-                    assert_eq!(buf.as_slice(), [5; 10].as_slice());
+                    assert_eq!(buf, [5; 10]);
                 }
             }
         });
index c9cabe648b994880dd5c6f125767fb91cea41d35..c3e4e7fc80d2e2a308c9bd9d835b00e2077c1d47 100644 (file)
@@ -1076,7 +1076,7 @@ fn write_line(&mut self, s: &str) -> IoResult<()> {
     #[inline]
     fn write_char(&mut self, c: char) -> IoResult<()> {
         let mut buf = [0u8; 4];
-        let n = c.encode_utf8(buf.as_mut_slice()).unwrap_or(0);
+        let n = c.encode_utf8(&mut buf).unwrap_or(0);
         self.write_all(&buf[..n])
     }
 
@@ -1870,7 +1870,7 @@ fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
                     // fall back on good
                     return r.read(buf);
                 }
-                match behavior.as_mut_slice()[0] {
+                match (&mut **behavior)[0] {
                     GoodBehavior(0) => (),
                     GoodBehavior(ref mut x) => {
                         *x -= 1;
index d85251795c887d254af8c696f8e57f9a2c9e5fb4..9c89c943994630f46c1b7633ec24cabe5dc8fb6a 100644 (file)
@@ -323,25 +323,25 @@ fn read_ipv6_addr(&mut self) -> Option<IpAddr> {
     }
 
     fn read_ip_addr(&mut self) -> Option<IpAddr> {
-        let ipv4_addr = |&mut: p: &mut Parser| p.read_ipv4_addr();
-        let ipv6_addr = |&mut: p: &mut Parser| p.read_ipv6_addr();
+        let ipv4_addr = |p: &mut Parser| p.read_ipv4_addr();
+        let ipv6_addr = |p: &mut Parser| p.read_ipv6_addr();
         self.read_or(&mut [box ipv4_addr, box ipv6_addr])
     }
 
     fn read_socket_addr(&mut self) -> Option<SocketAddr> {
-        let ip_addr = |&: p: &mut Parser| {
-            let ipv4_p = |&mut: p: &mut Parser| p.read_ip_addr();
-            let ipv6_p = |&mut: p: &mut Parser| {
-                let open_br = |&: p: &mut Parser| p.read_given_char('[');
-                let ip_addr = |&: p: &mut Parser| p.read_ipv6_addr();
-                let clos_br = |&: p: &mut Parser| p.read_given_char(']');
+        let ip_addr = |p: &mut Parser| {
+            let ipv4_p = |p: &mut Parser| p.read_ip_addr();
+            let ipv6_p = |p: &mut Parser| {
+                let open_br = |p: &mut Parser| p.read_given_char('[');
+                let ip_addr = |p: &mut Parser| p.read_ipv6_addr();
+                let clos_br = |p: &mut Parser| p.read_given_char(']');
                 p.read_seq_3::<char, IpAddr, char, _, _, _>(open_br, ip_addr, clos_br)
                         .map(|t| match t { (_, ip, _) => ip })
             };
             p.read_or(&mut [box ipv4_p, box ipv6_p])
         };
-        let colon = |&: p: &mut Parser| p.read_given_char(':');
-        let port  = |&: p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);
+        let colon = |p: &mut Parser| p.read_given_char(':');
+        let port  = |p: &mut Parser| p.read_number(10, 5, 0x10000).map(|n| n as u16);
 
         // host, colon, port
         self.read_seq_3::<IpAddr, char, u16, _, _, _>(ip_addr, colon, port)
index 27af957e18e18614c591e47fd2911a9672cdd8f2..195d33c41a68e98e02210ccb4ad6eba323315a2d 100644 (file)
@@ -239,8 +239,8 @@ fn get_env_map<'a>(&'a mut self) -> &'a mut EnvMap {
                 // if the env is currently just inheriting from the parent's,
                 // materialize the parent's env into a hashtable.
                 self.env = Some(os::env_as_bytes().into_iter().map(|(k, v)| {
-                    (EnvKey(CString::from_slice(k.as_slice())),
-                     CString::from_slice(v.as_slice()))
+                    (EnvKey(CString::from_slice(&k)),
+                     CString::from_slice(&v))
                 }).collect());
                 self.env.as_mut().unwrap()
             }
@@ -440,7 +440,7 @@ fn program(&self) -> &CString {
         &self.program
     }
     fn args(&self) -> &[CString] {
-        self.args.as_slice()
+        &self.args
     }
     fn env(&self) -> Option<&EnvMap> {
         self.env.as_ref()
@@ -703,7 +703,7 @@ fn read(stream: Option<old_io::PipeStream>) -> Receiver<IoResult<Vec<u8>>> {
             let (tx, rx) = channel();
             match stream {
                 Some(stream) => {
-                    Thread::spawn(move |:| {
+                    Thread::spawn(move || {
                         let mut stream = stream;
                         tx.send(stream.read_to_end()).unwrap();
                     });
@@ -915,7 +915,7 @@ fn test_process_output_fail_to_start() {
     fn test_process_output_output() {
         let ProcessOutput {status, output, error}
              = Command::new("echo").arg("hello").output().unwrap();
-        let output_str = str::from_utf8(output.as_slice()).unwrap();
+        let output_str = str::from_utf8(&output).unwrap();
 
         assert!(status.success());
         assert_eq!(output_str.trim().to_string(), "hello");
@@ -956,7 +956,7 @@ fn test_finish_twice() {
     fn test_wait_with_output_once() {
         let prog = Command::new("echo").arg("hello").spawn().unwrap();
         let ProcessOutput {status, output, error} = prog.wait_with_output().unwrap();
-        let output_str = str::from_utf8(output.as_slice()).unwrap();
+        let output_str = str::from_utf8(&output).unwrap();
 
         assert!(status.success());
         assert_eq!(output_str.trim().to_string(), "hello");
@@ -1049,7 +1049,7 @@ fn test_inherit_env() {
         for &(ref k, ref v) in &r {
             // don't check windows magical empty-named variables
             assert!(k.is_empty() ||
-                    output.contains(format!("{}={}", *k, *v).as_slice()),
+                    output.contains(&format!("{}={}", *k, *v)),
                     "output doesn't contain `{}={}`\n{}",
                     k, v, output);
         }
@@ -1067,12 +1067,12 @@ fn test_inherit_env() {
         for &(ref k, ref v) in &r {
             // don't check android RANDOM variables
             if *k != "RANDOM".to_string() {
-                assert!(output.contains(format!("{}={}",
-                                                *k,
-                                                *v).as_slice()) ||
-                        output.contains(format!("{}=\'{}\'",
-                                                *k,
-                                                *v).as_slice()));
+                assert!(output.contains(&format!("{}={}",
+                                                 *k,
+                                                 *v)) ||
+                        output.contains(&format!("{}=\'{}\'",
+                                                 *k,
+                                                 *v)));
             }
         }
     }
@@ -1091,13 +1091,13 @@ fn test_override_env() {
             None => {}
             Some(val) => {
                 path_val = val;
-                new_env.push(("PATH", path_val.as_slice()))
+                new_env.push(("PATH", &path_val))
             }
         }
 
-        let prog = env_cmd().env_set_all(new_env.as_slice()).spawn().unwrap();
+        let prog = env_cmd().env_set_all(&new_env).spawn().unwrap();
         let result = prog.wait_with_output().unwrap();
-        let output = String::from_utf8_lossy(result.output.as_slice()).to_string();
+        let output = String::from_utf8_lossy(&result.output).to_string();
 
         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
@@ -1107,7 +1107,7 @@ fn test_override_env() {
     fn test_add_to_env() {
         let prog = env_cmd().env("RUN_TEST_NEW_ENV", "123").spawn().unwrap();
         let result = prog.wait_with_output().unwrap();
-        let output = String::from_utf8_lossy(result.output.as_slice()).to_string();
+        let output = String::from_utf8_lossy(&result.output).to_string();
 
         assert!(output.contains("RUN_TEST_NEW_ENV=123"),
                 "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
index 96b979860ae902fe571e226cb00fb3fdeb592a8e..f42cb6ce8c97bf4d9c9f93d1b5ef9a2b5273945a 100644 (file)
@@ -112,7 +112,7 @@ fn test_option_reader() {
         let mut buf = [0, 0];
         reader.read(&mut buf).unwrap();
         let b: &[_] = &[0, 1];
-        assert_eq!(buf.as_slice(), b);
+        assert_eq!(buf, b);
     }
 
     #[test]
index f78e3ac1f14dad01c1a2a4583b01026c70cf8b9d..5ae239014d188145e55a2014b36be610b3f03dba 100644 (file)
@@ -101,7 +101,7 @@ fn read(&mut self, buf: &mut [u8]) -> old_io::IoResult<uint> {
 impl Buffer for ZeroReader {
     fn fill_buf<'a>(&'a mut self) -> old_io::IoResult<&'a [u8]> {
         static DATA: [u8; 64] = [0; 64];
-        Ok(DATA.as_slice())
+        Ok(&DATA)
     }
 
     fn consume(&mut self, _amt: uint) {}
@@ -321,7 +321,7 @@ fn test_limit_reader_overlong_consume() {
     fn test_null_writer() {
         let mut s = NullWriter;
         let buf = vec![0, 0, 0];
-        s.write_all(buf.as_slice()).unwrap();
+        s.write_all(&buf).unwrap();
         s.flush().unwrap();
     }
 
@@ -329,7 +329,7 @@ fn test_null_writer() {
     fn test_zero_reader() {
         let mut s = ZeroReader;
         let mut buf = vec![1, 2, 3];
-        assert_eq!(s.read(buf.as_mut_slice()), Ok(3));
+        assert_eq!(s.read(&mut buf), Ok(3));
         assert_eq!(vec![0, 0, 0], buf);
     }
 
@@ -337,7 +337,7 @@ fn test_zero_reader() {
     fn test_null_reader() {
         let mut r = NullReader;
         let mut buf = vec![0];
-        assert!(r.read(buf.as_mut_slice()).is_err());
+        assert!(r.read(&mut buf).is_err());
     }
 
     #[test]
index 8bcdd89623d8fb91a0e8b10e2f38287f73cece51..6bf2a30b7b184e91aa85fe2b13b1b46173a19b57 100644 (file)
@@ -131,25 +131,25 @@ unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
                 v.push(SEP_BYTE);
                 v.push_all(filename);
                 // FIXME: this is slow
-                self.repr = Path::normalize(v.as_slice());
+                self.repr = Path::normalize(&v);
             }
             None => {
                 self.repr = Path::normalize(filename);
             }
             Some(idx) if &self.repr[idx+1..] == b".." => {
                 let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
-                v.push_all(self.repr.as_slice());
+                v.push_all(&self.repr);
                 v.push(SEP_BYTE);
                 v.push_all(filename);
                 // FIXME: this is slow
-                self.repr = Path::normalize(v.as_slice());
+                self.repr = Path::normalize(&v);
             }
             Some(idx) => {
                 let mut v = Vec::with_capacity(idx + 1 + filename.len());
                 v.push_all(&self.repr[..idx+1]);
                 v.push_all(filename);
                 // FIXME: this is slow
-                self.repr = Path::normalize(v.as_slice());
+                self.repr = Path::normalize(&v);
             }
         }
         self.sepidx = self.repr.rposition_elem(&SEP_BYTE);
@@ -162,11 +162,11 @@ unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
                 self.repr = Path::normalize(path);
             }  else {
                 let mut v = Vec::with_capacity(self.repr.len() + path.len() + 1);
-                v.push_all(self.repr.as_slice());
+                v.push_all(&self.repr);
                 v.push(SEP_BYTE);
                 v.push_all(path);
                 // FIXME: this is slow
-                self.repr = Path::normalize(v.as_slice());
+                self.repr = Path::normalize(&v);
             }
             self.sepidx = self.repr.rposition_elem(&SEP_BYTE);
         }
@@ -176,7 +176,7 @@ unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
 impl GenericPath for Path {
     #[inline]
     fn as_vec<'a>(&'a self) -> &'a [u8] {
-        self.repr.as_slice()
+        &self.repr
     }
 
     fn into_vec(self) -> Vec<u8> {
@@ -185,10 +185,10 @@ fn into_vec(self) -> Vec<u8> {
 
     fn dirname<'a>(&'a self) -> &'a [u8] {
         match self.sepidx {
-            None if b".." == self.repr => self.repr.as_slice(),
+            None if b".." == self.repr => &self.repr,
             None => dot_static,
             Some(0) => &self.repr[..1],
-            Some(idx) if &self.repr[idx+1..] == b".." => self.repr.as_slice(),
+            Some(idx) if &self.repr[idx+1..] == b".." => &self.repr,
             Some(idx) => &self.repr[..idx]
         }
     }
@@ -197,7 +197,7 @@ fn filename<'a>(&'a self) -> Option<&'a [u8]> {
         match self.sepidx {
             None if b"." == self.repr ||
                 b".." == self.repr => None,
-            None => Some(self.repr.as_slice()),
+            None => Some(&self.repr),
             Some(idx) if &self.repr[idx+1..] == b".." => None,
             Some(0) if self.repr[1..].is_empty() => None,
             Some(idx) => Some(&self.repr[idx+1..])
@@ -382,7 +382,7 @@ fn normalize<V: ?Sized + AsSlice<u8>>(v: &V) -> Vec<u8> {
     pub fn components<'a>(&'a self) -> Components<'a> {
         let v = if self.repr[0] == SEP_BYTE {
             &self.repr[1..]
-        } else { self.repr.as_slice() };
+        } else { &*self.repr };
         let is_sep_byte: fn(&u8) -> bool = is_sep_byte; // coerce to fn ptr
         let mut ret = v.split(is_sep_byte);
         if v.is_empty() {
@@ -557,14 +557,14 @@ macro_rules! t {
                 {
                     let path = Path::new($path);
                     let mo = path.display().as_cow();
-                    assert_eq!(mo.as_slice(), $exp);
+                    assert_eq!(mo, $exp);
                 }
             );
             ($path:expr, $exp:expr, filename) => (
                 {
                     let path = Path::new($path);
                     let mo = path.filename_display().as_cow();
-                    assert_eq!(mo.as_slice(), $exp);
+                    assert_eq!(mo, $exp);
                 }
             )
         }
index 2e25403220d8264c99d15083fb5a28f86acf501d..54c070e1b7db83eb507f1da9c290f526ec5f4de9 100644 (file)
@@ -1337,10 +1337,10 @@ fn test_display_str() {
 
         let path = Path::new("foo");
         let mo = path.display().as_cow();
-        assert_eq!(mo.as_slice(), "foo");
+        assert_eq!(mo, "foo");
         let path = Path::new(b"\\");
         let mo = path.filename_display().as_cow();
-        assert_eq!(mo.as_slice(), "");
+        assert_eq!(mo, "");
     }
 
     #[test]
index 64f9e16aee4fd3392220bbaea6b13946d6d97644..1a61769445664f83e14bbab9f4116cb85ac65e9a 100644 (file)
@@ -649,7 +649,7 @@ fn real_args_as_bytes() -> Vec<Vec<u8>> {
 fn real_args() -> Vec<String> {
     real_args_as_bytes().into_iter()
                         .map(|v| {
-                            String::from_utf8_lossy(v.as_slice()).into_owned()
+                            String::from_utf8_lossy(&v).into_owned()
                         }).collect()
 }
 
@@ -671,7 +671,7 @@ fn real_args() -> Vec<String> {
 
         // Push it onto the list.
         let ptr = ptr as *const u16;
-        let buf = slice::from_raw_buf(&ptr, len);
+        let buf = slice::from_raw_parts(ptr, len);
         let opt_s = String::from_utf16(sys::truncate_utf16_at_nul(buf));
         opt_s.ok().expect("CommandLineToArgvW returned invalid UTF-16")
     }).collect();
@@ -759,7 +759,6 @@ pub fn page_size() -> uint {
 ///
 /// The memory map is released (unmapped) when the destructor is run, so don't
 /// let it leave scope by accident if you want it to stick around.
-#[allow(missing_copy_implementations)]
 pub struct MemoryMap {
     data: *mut u8,
     len: uint,
@@ -1289,6 +1288,8 @@ pub mod consts {
 }
 
 #[cfg(target_os = "openbsd")]
+#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
+#[unstable(feature = "os")]
 pub mod consts {
     pub use os::arch_consts::ARCH;
 
@@ -1442,7 +1443,7 @@ fn make_rand_name() -> String {
         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());
+        assert!(getenv(&n).is_none());
         n
     }
 
@@ -1454,27 +1455,27 @@ fn test_num_cpus() {
     #[test]
     fn test_setenv() {
         let n = make_rand_name();
-        setenv(n.as_slice(), "VALUE");
-        assert_eq!(getenv(n.as_slice()), Some("VALUE".to_string()));
+        setenv(&n, "VALUE");
+        assert_eq!(getenv(&n), Some("VALUE".to_string()));
     }
 
     #[test]
     fn test_unsetenv() {
         let n = make_rand_name();
-        setenv(n.as_slice(), "VALUE");
-        unsetenv(n.as_slice());
-        assert_eq!(getenv(n.as_slice()), None);
+        setenv(&n, "VALUE");
+        unsetenv(&n);
+        assert_eq!(getenv(&n), None);
     }
 
     #[test]
     #[ignore]
     fn test_setenv_overwrite() {
         let n = make_rand_name();
-        setenv(n.as_slice(), "1");
-        setenv(n.as_slice(), "2");
-        assert_eq!(getenv(n.as_slice()), Some("2".to_string()));
-        setenv(n.as_slice(), "");
-        assert_eq!(getenv(n.as_slice()), Some("".to_string()));
+        setenv(&n, "1");
+        setenv(&n, "2");
+        assert_eq!(getenv(&n), Some("2".to_string()));
+        setenv(&n, "");
+        assert_eq!(getenv(&n), Some("".to_string()));
     }
 
     // Windows GetEnvironmentVariable requires some extra work to make sure
@@ -1489,9 +1490,9 @@ fn test_getenv_big() {
             i += 1;
         }
         let n = make_rand_name();
-        setenv(n.as_slice(), s.as_slice());
+        setenv(&n, &s);
         debug!("{}", s.clone());
-        assert_eq!(getenv(n.as_slice()), Some(s));
+        assert_eq!(getenv(&n), Some(s));
     }
 
     #[test]
@@ -1524,7 +1525,7 @@ fn test_env_getenv() {
         for p in &e {
             let (n, v) = (*p).clone();
             debug!("{}", n);
-            let v2 = getenv(n.as_slice());
+            let v2 = getenv(&n);
             // MingW seems to set some funky environment variables like
             // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
             // from env() but not visible from getenv().
@@ -1536,10 +1537,10 @@ fn test_env_getenv() {
     fn test_env_set_get_huge() {
         let n = make_rand_name();
         let s = repeat("x").take(10000).collect::<String>();
-        setenv(n.as_slice(), s.as_slice());
-        assert_eq!(getenv(n.as_slice()), Some(s));
-        unsetenv(n.as_slice());
-        assert_eq!(getenv(n.as_slice()), None);
+        setenv(&n, &s);
+        assert_eq!(getenv(&n), Some(s));
+        unsetenv(&n);
+        assert_eq!(getenv(&n), None);
     }
 
     #[test]
@@ -1547,7 +1548,7 @@ fn test_env_setenv() {
         let n = make_rand_name();
 
         let mut e = env();
-        setenv(n.as_slice(), "VALUE");
+        setenv(&n, "VALUE");
         assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
 
         e = env();
@@ -1577,7 +1578,7 @@ fn homedir() {
         assert!(os::homedir().is_none());
 
         if let Some(s) = oldhome {
-            setenv("HOME", s.as_slice());
+            setenv("HOME", s);
         }
     }
 
@@ -1606,10 +1607,10 @@ fn homedir() {
         assert!(os::homedir() == Some(Path::new("/home/MountainView")));
 
         if let Some(s) = oldhome {
-            setenv("HOME", s.as_slice());
+            setenv("HOME", &s);
         }
         if let Some(s) = olduserprofile {
-            setenv("USERPROFILE", s.as_slice());
+            setenv("USERPROFILE", &s);
         }
     }
 
index 3f4f1ec4c0db5f4afe33e516bf98a4ba02630952..776fa27086781028d99ea8d73fb78824f8758e63 100755 (executable)
@@ -922,7 +922,7 @@ pub fn set_file_name<S: ?Sized>(&mut self, file_name: &S) where S: AsOsStr {
     ///
     /// If `self.file_name()` is `None`, does nothing and returns `false`.
     ///
-    /// Otherwise, returns `tru`; if `self.exension()` is `None`, the extension
+    /// Otherwise, returns `true`; if `self.extension()` is `None`, the extension
     /// is added; otherwise it is replaced.
     pub fn set_extension<S: ?Sized + AsOsStr>(&mut self, extension: &S) -> bool {
         if self.file_name().is_none() { return false; }
@@ -999,6 +999,12 @@ fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
     }
 }
 
+impl AsOsStr for PathBuf {
+    fn as_os_str(&self) -> &OsStr {
+        &self.inner[]
+    }
+}
+
 /// A slice of a path (akin to `str`).
 ///
 /// This type supports a number of operations for inspecting a path, including
@@ -1062,7 +1068,7 @@ pub fn to_path_buf(&self) -> PathBuf {
         PathBuf::new(self)
     }
 
-    /// A path is *absolute* if it is indepedent of the current directory.
+    /// A path is *absolute* if it is independent of the current directory.
     ///
     /// * On Unix, a path is absolute if it starts with the root, so
     /// `is_absolute` and `has_root` are equivalent.
index e52d5ada0ef092767896d0dbc53c6e79dd263196..8f9e966cbb2b7a9fbe29a33d8d7ff6fad8cd4b28 100644 (file)
@@ -469,7 +469,7 @@ fn test_fill_bytes_default() {
                        80, 81, 82, 83, 84, 85, 86, 87];
         for &n in &lengths {
             let mut v = repeat(0u8).take(n).collect::<Vec<_>>();
-            r.fill_bytes(v.as_mut_slice());
+            r.fill_bytes(&mut v);
 
             // use this to get nicer error messages.
             for (i, &byte) in v.iter().enumerate() {
@@ -619,8 +619,8 @@ fn test_sample() {
     #[test]
     fn test_std_rng_seeded() {
         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());
+        let mut ra: StdRng = SeedableRng::from_seed(&*s);
+        let mut rb: StdRng = SeedableRng::from_seed(&*s);
         assert!(order::equals(ra.gen_ascii_chars().take(100),
                               rb.gen_ascii_chars().take(100)));
     }
@@ -628,10 +628,10 @@ fn test_std_rng_seeded() {
     #[test]
     fn test_std_rng_reseed() {
         let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
-        let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
+        let mut r: StdRng = SeedableRng::from_seed(&*s);
         let string1 = r.gen_ascii_chars().take(100).collect::<String>();
 
-        r.reseed(s.as_slice());
+        r.reseed(&s);
 
         let string2 = r.gen_ascii_chars().take(100).collect::<String>();
         assert_eq!(string1, string2);
index 797b9332f17dc4cfa134e8f1ab48e02bf7cb1e58..535af08c96c70d70f25245008dddf8f5570a3b1c 100644 (file)
@@ -206,7 +206,6 @@ mod imp {
     /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
     ///
     /// This does not block.
-    #[allow(missing_copy_implementations)]
     pub struct OsRng {
         // dummy field to ensure that this struct cannot be constructed outside of this module
         _dummy: (),
index b3bed4af96248dd4cdf70c25cad961aa7ac8b53f..c2f5133eaf3fe5547a3fd450274d0948d127cee4 100644 (file)
@@ -125,7 +125,7 @@ fn smoke_test() {
             assert!(take() == Some(expected.clone()));
             assert!(take() == None);
 
-            (|&mut:| {
+            (|| {
             }).finally(|| {
                 // Restore the actual global state.
                 match saved_value {
index 81ca5aa0e8a6e3d4bc6aa332f4488daee05e202a..e064663b9e76f3931ed28f1e8ee69b86cb163bb8 100644 (file)
@@ -98,8 +98,8 @@ struct Exception {
 
 /// Invoke a closure, capturing the cause of panic if one occurs.
 ///
-/// This function will return `None` if the closure did not panic, and will
-/// return `Some(cause)` if the closure panics. The `cause` returned is the
+/// This function will return `Ok(())` if the closure did not panic, and will
+/// return `Err(cause)` if the closure panics. The `cause` returned is the
 /// object with which panic was originally invoked.
 ///
 /// This function also is unsafe for a variety of reasons:
@@ -390,13 +390,10 @@ pub mod eabi {
     use libc::{c_void, c_int};
 
     #[repr(C)]
-    #[allow(missing_copy_implementations)]
     pub struct EXCEPTION_RECORD;
     #[repr(C)]
-    #[allow(missing_copy_implementations)]
     pub struct CONTEXT;
     #[repr(C)]
-    #[allow(missing_copy_implementations)]
     pub struct DISPATCHER_CONTEXT;
 
     #[repr(C)]
index 86d21cf72782ed51a3b71db9225c346d1dc52e71..703dca4d29bf95f7293e501a889b328e4c4b1b7e 100644 (file)
@@ -88,7 +88,6 @@ pub fn default_sched_threads() -> uint {
 pub const ENFORCE_SANITY: bool = true || !cfg!(rtopt) || cfg!(rtdebug) ||
                                   cfg!(rtassert);
 
-#[allow(missing_copy_implementations)]
 pub struct Stdio(libc::c_int);
 
 #[allow(non_upper_case_globals)]
index 581e540d3b6ed6686a0ce7aaf60d0fc8088de2ea..cca376f7b6d05397776202005627afd0c6153b7c 100644 (file)
@@ -46,7 +46,6 @@ struct BarrierState {
 ///
 /// Currently this opaque structure only has one method, `.is_leader()`. Only
 /// one thread will receive a result that will return `true` from this function.
-#[allow(missing_copy_implementations)]
 pub struct BarrierWaitResult(bool);
 
 impl Barrier {
index 2ae81ad7dffe2fe2f20a6f4046439c3fbf30c28a..d4d722cab3d929288aaea0d17989036cf21592f2 100644 (file)
@@ -16,7 +16,7 @@
 use sys_common::condvar as sys;
 use sys_common::mutex as sys_mutex;
 use time::Duration;
-use sync::{mutex, MutexGuard};
+use sync::{mutex, MutexGuard, PoisonError};
 
 /// A Condition Variable
 ///
@@ -228,7 +228,7 @@ pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>)
             mutex::guard_poison(&guard).get()
         };
         if poisoned {
-            Err(poison::new_poison_error(guard))
+            Err(PoisonError::new(guard))
         } else {
             Ok(guard)
         }
@@ -249,7 +249,7 @@ pub fn wait_timeout<'a, T>(&'static self, guard: MutexGuard<'a, T>, dur: Duratio
             (mutex::guard_poison(&guard).get(), success)
         };
         if poisoned {
-            Err(poison::new_poison_error((guard, success)))
+            Err(PoisonError::new((guard, success)))
         } else {
             Ok((guard, success))
         }
@@ -276,7 +276,7 @@ pub fn wait_timeout_with<'a, T, F>(&'static self,
         while !f(guard_result
                     .as_mut()
                     .map(|g| &mut **g)
-                    .map_err(|e| poison::new_poison_error(&mut **e.get_mut()))) {
+                    .map_err(|e| PoisonError::new(&mut **e.get_mut()))) {
             let now = SteadyTime::now();
             let consumed = &now - &start;
             let guard = guard_result.unwrap_or_else(|e| e.into_inner());
@@ -284,7 +284,7 @@ pub fn wait_timeout_with<'a, T, F>(&'static self,
                 Ok((new_guard, no_timeout)) => (Ok(new_guard), no_timeout),
                 Err(err) => {
                     let (new_guard, no_timeout) = err.into_inner();
-                    (Err(poison::new_poison_error(new_guard)), no_timeout)
+                    (Err(PoisonError::new(new_guard)), no_timeout)
                 }
             };
             guard_result = new_guard_result;
@@ -292,7 +292,7 @@ pub fn wait_timeout_with<'a, T, F>(&'static self,
                 let result = f(guard_result
                                     .as_mut()
                                     .map(|g| &mut **g)
-                                    .map_err(|e| poison::new_poison_error(&mut **e.get_mut())));
+                                    .map_err(|e| PoisonError::new(&mut **e.get_mut())));
                 return poison::map_result(guard_result, |g| (g, result));
             }
         }
index 8340652d19ae6d8f06e225c66537b5bf90e1bf55..a230e35dac8c3db163a46ba7b4e56713c3f804b0 100644 (file)
@@ -126,7 +126,7 @@ pub fn from_receiver(rx: Receiver<A>) -> Future<A> {
          * waiting for the result to be received on the port.
          */
 
-        Future::from_fn(move |:| {
+        Future::from_fn(move || {
             rx.recv().unwrap()
         })
     }
@@ -143,7 +143,7 @@ pub fn spawn<F>(blk: F) -> Future<A>
 
         let (tx, rx) = channel();
 
-        Thread::spawn(move |:| {
+        Thread::spawn(move || {
             // Don't panic if the other end has hung up
             let _ = tx.send(blk());
         });
index 39c57a21d752ade70be4cf47b70ed3edf2fff240..2e60d684d6823aeb82a8c4248ad9fe8053a809ea 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-//! Multi-producer, single-consumer communication primitives threads
+//! Multi-producer, single-consumer FIFO queue communication primitives.
 //!
 //! This module provides message-based communication over channels, concretely
 //! defined among three types:
index ca667e65e30cc50b06868872b867761f9e22054d..eb45681fa626d6e3018447c676efe23b688ce478 100644 (file)
@@ -45,7 +45,7 @@
 use sync::atomic::{AtomicUsize, Ordering};
 
 // Various states you can find a port in.
-const EMPTY: uint = 0;          // initial state: no data, no blocked reciever
+const EMPTY: uint = 0;          // initial state: no data, no blocked receiver
 const DATA: uint = 1;           // data ready for receiver to take
 const DISCONNECTED: uint = 2;   // channel is disconnected OR upgraded
 // Any other value represents a pointer to a SignalToken value. The
index c80aa56717315d9f5cdb76b0d706ab6983989a72..f0558c33d1ec8d973ba11430443570a0cd176369 100644 (file)
@@ -274,7 +274,7 @@ fn peek() {
 
             // Ensure the borrowchecker works
             match queue.peek() {
-                Some(vec) => match vec.as_slice() {
+                Some(vec) => match &**vec {
                     // Note that `pop` is not allowed here due to borrow
                     [1] => {}
                     _ => return
index 7531d5b058d79686c1e425435fd82cbbb32b569d..74692c1273c2790130597171adfc86a679cd6e8f 100644 (file)
@@ -228,6 +228,17 @@ pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
             Err(TryLockError::WouldBlock)
         }
     }
+
+    /// Determine whether the lock is poisoned.
+    ///
+    /// If another thread is active, the lock can still become poisoned at any
+    /// time.  You should not trust a `false` value for program correctness
+    /// without additional synchronization.
+    #[inline]
+    #[unstable(feature = "std_misc")]
+    pub fn is_poisoned(&self) -> bool {
+        self.inner.poison.get()
+    }
 }
 
 #[unsafe_destructor]
@@ -458,12 +469,14 @@ fn test_arc_condvar_poison() {
     #[test]
     fn test_mutex_arc_poison() {
         let arc = Arc::new(Mutex::new(1));
+        assert!(!arc.is_poisoned());
         let arc2 = arc.clone();
         let _ = Thread::scoped(move|| {
             let lock = arc2.lock().unwrap();
             assert_eq!(*lock, 2);
         }).join();
         assert!(arc.lock().is_err());
+        assert!(arc.is_poisoned());
     }
 
     #[test]
index 18680b96592ce3b9589de4b0a5f7b863bb36def5..a93bd31f5ae38ab58d59ad9569807ca33d747729 100644 (file)
@@ -23,7 +23,7 @@ impl Flag {
     pub fn borrow(&self) -> LockResult<Guard> {
         let ret = Guard { panicking: Thread::panicking() };
         if unsafe { *self.failed.get() } {
-            Err(new_poison_error(ret))
+            Err(PoisonError::new(ret))
         } else {
             Ok(ret)
         }
@@ -42,7 +42,6 @@ pub fn get(&self) -> bool {
     }
 }
 
-#[allow(missing_copy_implementations)]
 pub struct Guard {
     panicking: bool,
 }
@@ -111,6 +110,12 @@ fn description(&self) -> &str {
 }
 
 impl<T> PoisonError<T> {
+    /// Create a `PoisonError`.
+    #[unstable(feature = "std_misc")]
+    pub fn new(guard: T) -> PoisonError<T> {
+        PoisonError { guard: guard }
+    }
+
     /// Consumes this error indicating that a lock is poisoned, returning the
     /// underlying guard to allow access regardless.
     #[unstable(feature = "std_misc")]
@@ -172,15 +177,11 @@ fn cause(&self) -> Option<&Error> {
     }
 }
 
-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)))
+        Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
     }
 }
index 6efbcf894156e887b97264c16be78d9eece25578..c4f1f2ccadddd034038a3e62c77d3e991c642e14 100644 (file)
@@ -237,6 +237,17 @@ pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<T>> {
             Err(TryLockError::WouldBlock)
         }
     }
+
+    /// Determine whether the lock is poisoned.
+    ///
+    /// If another thread is active, the lock can still become poisoned at any
+    /// time.  You should not trust a `false` value for program correctness
+    /// without additional synchronization.
+    #[inline]
+    #[unstable(feature = "std_misc")]
+    pub fn is_poisoned(&self) -> bool {
+        self.inner.poison.get()
+    }
 }
 
 #[unsafe_destructor]
@@ -451,12 +462,14 @@ fn test_rw_arc_poison_wr() {
     #[test]
     fn test_rw_arc_poison_ww() {
         let arc = Arc::new(RwLock::new(1));
+        assert!(!arc.is_poisoned());
         let arc2 = arc.clone();
         let _: Result<uint, _> = Thread::scoped(move|| {
             let _lock = arc2.write().unwrap();
             panic!();
         }).join();
         assert!(arc.write().is_err());
+        assert!(arc.is_poisoned());
     }
 
     #[test]
index 1bfcbcf96f1443cbbd78a721ac6dece674c4c96b..684a46fd6ff5fa51fde077b0540c2c7a604491b5 100644 (file)
@@ -112,7 +112,7 @@ pub fn execute<F>(&self, job: F)
 }
 
 fn spawn_in_pool(jobs: Arc<Mutex<Receiver<Thunk>>>) {
-    Thread::spawn(move |:| {
+    Thread::spawn(move || {
         // Will spawn a new thread on panic unless it is cancelled.
         let sentinel = Sentinel::new(&jobs);
 
index 6f6179a436e914c3c77de9384be7e6b41799ea02..255f474d4f4afb42bca461c9a0fad3f5013dee20 100644 (file)
@@ -95,14 +95,14 @@ pub fn boot<T, F>(&'static self, f: F, helper: fn(helper_signal::signal, Receive
                 let receive = RaceBox(receive);
 
                 let t = f();
-                Thread::spawn(move |:| {
+                Thread::spawn(move || {
                     helper(receive.0, rx, t);
                     let _g = self.lock.lock().unwrap();
                     *self.shutdown.get() = true;
                     self.cond.notify_one()
                 });
 
-                rt::at_exit(move|:| { self.shutdown() });
+                rt::at_exit(move|| { self.shutdown() });
                 *self.initialized.get() = true;
             }
         }
index 6f6b4c58717482522246ca8864b86d6855540871..80fa5f64597e95c8091a1032b56fa9fab45b8a33 100644 (file)
@@ -95,20 +95,30 @@ pub fn keep_going<F>(data: &[u8], mut f: F) -> i64 where
 }
 
 /// A trait for viewing representations from std types
+#[doc(hidden)]
 pub trait AsInner<Inner: ?Sized> {
     fn as_inner(&self) -> &Inner;
 }
 
+/// A trait for viewing representations from std types
+#[doc(hidden)]
+pub trait AsInnerMut<Inner: ?Sized> {
+    fn as_inner_mut(&mut self) -> &mut Inner;
+}
+
 /// A trait for extracting representations from std types
+#[doc(hidden)]
 pub trait IntoInner<Inner> {
     fn into_inner(self) -> Inner;
 }
 
 /// A trait for creating std types from internal representations
+#[doc(hidden)]
 pub trait FromInner<Inner> {
     fn from_inner(inner: Inner) -> Self;
 }
 
+#[doc(hidden)]
 pub trait ProcessConfig<K: BytesContainer, V: BytesContainer> {
     fn program(&self) -> &CString;
     fn args(&self) -> &[CString];
index 833de8adda49dfbb41ce8fb95fa3dbf65a443279..7325e0a5ac8ddfaeb3726aeca06be0c723b5d987 100644 (file)
@@ -723,8 +723,8 @@ fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
 
     pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
         let fd = self.fd();
-        let dolock = |&:| self.lock_nonblocking();
-        let doread = |&mut: nb| unsafe {
+        let dolock = || self.lock_nonblocking();
+        let doread = |nb| unsafe {
             let flags = if nb {c::MSG_DONTWAIT} else {0};
             libc::recv(fd,
                        buf.as_mut_ptr() as *mut libc::c_void,
@@ -736,8 +736,8 @@ pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
 
     pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
         let fd = self.fd();
-        let dolock = |&:| self.lock_nonblocking();
-        let dowrite = |&: nb: bool, buf: *const u8, len: uint| unsafe {
+        let dolock = || self.lock_nonblocking();
+        let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
             let flags = if nb {c::MSG_DONTWAIT} else {0};
             libc::send(fd,
                        buf as *const _,
@@ -871,7 +871,7 @@ pub fn recv_from(&mut self, buf: &mut [u8]) -> IoResult<(uint, SocketAddr)> {
         let mut addrlen: libc::socklen_t =
                 mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;
 
-        let dolock = |&:| self.lock_nonblocking();
+        let dolock = || self.lock_nonblocking();
         let n = try!(read(fd, self.read_deadline, dolock, |nb| unsafe {
             let flags = if nb {c::MSG_DONTWAIT} else {0};
             libc::recvfrom(fd,
@@ -892,8 +892,8 @@ pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
         let dstp = &storage as *const _ as *const libc::sockaddr;
 
         let fd = self.fd();
-        let dolock = |&: | self.lock_nonblocking();
-        let dowrite = |&mut: nb, buf: *const u8, len: uint| unsafe {
+        let dolock = || self.lock_nonblocking();
+        let dowrite = |nb, buf: *const u8, len: uint| unsafe {
             let flags = if nb {c::MSG_DONTWAIT} else {0};
             libc::sendto(fd,
                          buf as *const libc::c_void,
index 7c9758ca9242d88cd28a2685d6a3224c270c5dfe..ce67a584a0a5e0d313588fdd3ff640f937ec8075 100644 (file)
@@ -57,7 +57,7 @@ pub fn stack_guard() -> uint {
 pub fn set(stack_bounds: (uint, uint), stack_guard: uint, thread: Thread) {
     THREAD_INFO.with(|c| assert!(c.borrow().is_none()));
     match thread.name() {
-        Some(name) => unsafe { ::sys::thread::set_name(name.as_slice()); },
+        Some(name) => unsafe { ::sys::thread::set_name(name); },
         None => {}
     }
     THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{
index b30af10986b9952235c200e4de4a81db959d64e8..892004714659d461aa971d5bd14874956b0a1e8b 100644 (file)
@@ -84,7 +84,7 @@ pub fn from_u32(value: u32) -> Option<CodePoint> {
 
     /// Create a new `CodePoint` from a `char`.
     ///
-    /// Since all Unicode scalar values are code points, this always succeds.
+    /// Since all Unicode scalar values are code points, this always succeeds.
     #[inline]
     pub fn from_char(value: char) -> CodePoint {
         CodePoint { value: value as u32 }
@@ -140,7 +140,7 @@ fn deref(&self) -> &Wtf8 {
 impl fmt::Debug for Wtf8Buf {
     #[inline]
     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
-        self.as_slice().fmt(formatter)
+        fmt::Debug::fmt(&**self, formatter)
     }
 }
 
@@ -220,7 +220,7 @@ fn push_code_point_unchecked(&mut self, code_point: CodePoint) {
 
     #[inline]
     pub fn as_slice(&self) -> &Wtf8 {
-        unsafe { mem::transmute(self.bytes.as_slice()) }
+        unsafe { mem::transmute(&*self.bytes) }
     }
 
     /// Reserves capacity for at least `additional` more bytes to be inserted
@@ -309,7 +309,7 @@ pub fn push(&mut self, code_point: CodePoint) {
     /// or if `new_len` is not a code point boundary.
     #[inline]
     pub fn truncate(&mut self, new_len: uint) {
-        assert!(is_code_point_boundary(self.as_slice(), new_len));
+        assert!(is_code_point_boundary(self, new_len));
         self.bytes.truncate(new_len)
     }
 
@@ -771,7 +771,7 @@ fn next(&mut self) -> Option<u16> {
 
         let mut buf = [0u16; 2];
         self.code_points.next().map(|code_point| {
-            let n = encode_utf16_raw(code_point.value, buf.as_mut_slice())
+            let n = encode_utf16_raw(code_point.value, &mut buf)
                 .unwrap_or(0);
             if n == 2 { self.extra = buf[1]; }
             buf[0]
@@ -798,7 +798,7 @@ fn hash(&self, state: &mut S) {
 impl<S: Writer + Hasher> Hash<S> for Wtf8Buf {
     #[inline]
     fn hash(&self, state: &mut S) {
-        state.write(self.bytes.as_slice());
+        state.write(&self.bytes);
         0xfeu8.hash(state)
     }
 }
@@ -843,8 +843,8 @@ fn code_point_from_char() {
 
     #[test]
     fn code_point_to_string() {
-        assert_eq!(format!("{:?}", CodePoint::from_char('a')).as_slice(), "U+0061");
-        assert_eq!(format!("{:?}", CodePoint::from_char('💩')).as_slice(), "U+1F4A9");
+        assert_eq!(format!("{:?}", CodePoint::from_char('a')), "U+0061");
+        assert_eq!(format!("{:?}", CodePoint::from_char('💩')), "U+1F4A9");
     }
 
     #[test]
@@ -865,142 +865,142 @@ fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
 
     #[test]
     fn wtf8buf_new() {
-        assert_eq!(Wtf8Buf::new().bytes.as_slice(), b"");
+        assert_eq!(Wtf8Buf::new().bytes, b"");
     }
 
     #[test]
     fn wtf8buf_from_str() {
-        assert_eq!(Wtf8Buf::from_str("").bytes.as_slice(), b"");
-        assert_eq!(Wtf8Buf::from_str("aé 💩").bytes.as_slice(),
+        assert_eq!(Wtf8Buf::from_str("").bytes, b"");
+        assert_eq!(Wtf8Buf::from_str("aé 💩").bytes,
                    b"a\xC3\xA9 \xF0\x9F\x92\xA9");
     }
 
     #[test]
     fn wtf8buf_from_string() {
-        assert_eq!(Wtf8Buf::from_string(String::from_str("")).bytes.as_slice(), b"");
-        assert_eq!(Wtf8Buf::from_string(String::from_str("aé 💩")).bytes.as_slice(),
+        assert_eq!(Wtf8Buf::from_string(String::from_str("")).bytes, b"");
+        assert_eq!(Wtf8Buf::from_string(String::from_str("aé 💩")).bytes,
                    b"a\xC3\xA9 \xF0\x9F\x92\xA9");
     }
 
     #[test]
     fn wtf8buf_from_wide() {
-        assert_eq!(Wtf8Buf::from_wide(&[]).bytes.as_slice(), b"");
+        assert_eq!(Wtf8Buf::from_wide(&[]).bytes, b"");
         assert_eq!(Wtf8Buf::from_wide(
-                      &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes.as_slice(),
+                      &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes,
                    b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9");
     }
 
     #[test]
     fn wtf8buf_push_str() {
         let mut string = Wtf8Buf::new();
-        assert_eq!(string.bytes.as_slice(), b"");
+        assert_eq!(string.bytes, b"");
         string.push_str("aé 💩");
-        assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+        assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
     }
 
     #[test]
     fn wtf8buf_push_char() {
         let mut string = Wtf8Buf::from_str("aé ");
-        assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 ");
+        assert_eq!(string.bytes, b"a\xC3\xA9 ");
         string.push_char('💩');
-        assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+        assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
     }
 
     #[test]
     fn wtf8buf_push() {
         let mut string = Wtf8Buf::from_str("aé ");
-        assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 ");
+        assert_eq!(string.bytes, b"a\xC3\xA9 ");
         string.push(CodePoint::from_char('💩'));
-        assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+        assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
 
         fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
 
         let mut string = Wtf8Buf::new();
         string.push(c(0xD83D));  // lead
         string.push(c(0xDCA9));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\xF0\x9F\x92\xA9");  // Magic!
+        assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9");  // Magic!
 
         let mut string = Wtf8Buf::new();
         string.push(c(0xD83D));  // lead
         string.push(c(0x20));  // not surrogate
         string.push(c(0xDCA9));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\xED\xA0\xBD \xED\xB2\xA9");
+        assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
 
         let mut string = Wtf8Buf::new();
         string.push(c(0xD800));  // lead
         string.push(c(0xDBFF));  // lead
-        assert_eq!(string.bytes.as_slice(), b"\xED\xA0\x80\xED\xAF\xBF");
+        assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
 
         let mut string = Wtf8Buf::new();
         string.push(c(0xD800));  // lead
         string.push(c(0xE000));  // not surrogate
-        assert_eq!(string.bytes.as_slice(), b"\xED\xA0\x80\xEE\x80\x80");
+        assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
 
         let mut string = Wtf8Buf::new();
         string.push(c(0xD7FF));  // not surrogate
         string.push(c(0xDC00));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\xED\x9F\xBF\xED\xB0\x80");
+        assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
 
         let mut string = Wtf8Buf::new();
         string.push(c(0x61));  // not surrogate, < 3 bytes
         string.push(c(0xDC00));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\x61\xED\xB0\x80");
+        assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
 
         let mut string = Wtf8Buf::new();
         string.push(c(0xDC00));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\xED\xB0\x80");
+        assert_eq!(string.bytes, b"\xED\xB0\x80");
     }
 
     #[test]
     fn wtf8buf_push_wtf8() {
         let mut string = Wtf8Buf::from_str("aé");
-        assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9");
+        assert_eq!(string.bytes, b"a\xC3\xA9");
         string.push_wtf8(Wtf8::from_str(" 💩"));
-        assert_eq!(string.bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+        assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
 
         fn w(value: &[u8]) -> &Wtf8 { unsafe { transmute(value) } }
 
         let mut string = Wtf8Buf::new();
         string.push_wtf8(w(b"\xED\xA0\xBD"));  // lead
         string.push_wtf8(w(b"\xED\xB2\xA9"));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\xF0\x9F\x92\xA9");  // Magic!
+        assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9");  // Magic!
 
         let mut string = Wtf8Buf::new();
         string.push_wtf8(w(b"\xED\xA0\xBD"));  // lead
         string.push_wtf8(w(b" "));  // not surrogate
         string.push_wtf8(w(b"\xED\xB2\xA9"));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\xED\xA0\xBD \xED\xB2\xA9");
+        assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
 
         let mut string = Wtf8Buf::new();
         string.push_wtf8(w(b"\xED\xA0\x80"));  // lead
         string.push_wtf8(w(b"\xED\xAF\xBF"));  // lead
-        assert_eq!(string.bytes.as_slice(), b"\xED\xA0\x80\xED\xAF\xBF");
+        assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
 
         let mut string = Wtf8Buf::new();
         string.push_wtf8(w(b"\xED\xA0\x80"));  // lead
         string.push_wtf8(w(b"\xEE\x80\x80"));  // not surrogate
-        assert_eq!(string.bytes.as_slice(), b"\xED\xA0\x80\xEE\x80\x80");
+        assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
 
         let mut string = Wtf8Buf::new();
         string.push_wtf8(w(b"\xED\x9F\xBF"));  // not surrogate
         string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\xED\x9F\xBF\xED\xB0\x80");
+        assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
 
         let mut string = Wtf8Buf::new();
         string.push_wtf8(w(b"a"));  // not surrogate, < 3 bytes
         string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\x61\xED\xB0\x80");
+        assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
 
         let mut string = Wtf8Buf::new();
         string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
-        assert_eq!(string.bytes.as_slice(), b"\xED\xB0\x80");
+        assert_eq!(string.bytes, b"\xED\xB0\x80");
     }
 
     #[test]
     fn wtf8buf_truncate() {
         let mut string = Wtf8Buf::from_str("aé");
         string.truncate(1);
-        assert_eq!(string.bytes.as_slice(), b"a");
+        assert_eq!(string.bytes, b"a");
     }
 
     #[test]
@@ -1038,15 +1038,15 @@ fn wtf8buf_from_iterator() {
         fn f(values: &[u32]) -> Wtf8Buf {
             values.iter().map(|&c| CodePoint::from_u32(c).unwrap()).collect::<Wtf8Buf>()
         };
-        assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes.as_slice(), b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+        assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
 
-        assert_eq!(f(&[0xD83D, 0xDCA9]).bytes.as_slice(), b"\xF0\x9F\x92\xA9");  // Magic!
-        assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes.as_slice(), b"\xED\xA0\xBD \xED\xB2\xA9");
-        assert_eq!(f(&[0xD800, 0xDBFF]).bytes.as_slice(), b"\xED\xA0\x80\xED\xAF\xBF");
-        assert_eq!(f(&[0xD800, 0xE000]).bytes.as_slice(), b"\xED\xA0\x80\xEE\x80\x80");
-        assert_eq!(f(&[0xD7FF, 0xDC00]).bytes.as_slice(), b"\xED\x9F\xBF\xED\xB0\x80");
-        assert_eq!(f(&[0x61, 0xDC00]).bytes.as_slice(), b"\x61\xED\xB0\x80");
-        assert_eq!(f(&[0xDC00]).bytes.as_slice(), b"\xED\xB0\x80");
+        assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9");  // Magic!
+        assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
+        assert_eq!(f(&[0xD800, 0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
+        assert_eq!(f(&[0xD800, 0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
+        assert_eq!(f(&[0xD7FF, 0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
+        assert_eq!(f(&[0x61, 0xDC00]).bytes, b"\x61\xED\xB0\x80");
+        assert_eq!(f(&[0xDC00]).bytes, b"\xED\xB0\x80");
     }
 
     #[test]
@@ -1058,23 +1058,23 @@ fn c(value: &u32) -> CodePoint { CodePoint::from_u32(*value).unwrap() }
             string
         };
 
-        assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes.as_slice(),
+        assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes,
                    b"a\xC3\xA9 \xF0\x9F\x92\xA9");
 
-        assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes.as_slice(), b"\xF0\x9F\x92\xA9");  // Magic!
-        assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes.as_slice(), b"\xED\xA0\xBD \xED\xB2\xA9");
-        assert_eq!(e(&[0xD800], &[0xDBFF]).bytes.as_slice(), b"\xED\xA0\x80\xED\xAF\xBF");
-        assert_eq!(e(&[0xD800], &[0xE000]).bytes.as_slice(), b"\xED\xA0\x80\xEE\x80\x80");
-        assert_eq!(e(&[0xD7FF], &[0xDC00]).bytes.as_slice(), b"\xED\x9F\xBF\xED\xB0\x80");
-        assert_eq!(e(&[0x61], &[0xDC00]).bytes.as_slice(), b"\x61\xED\xB0\x80");
-        assert_eq!(e(&[], &[0xDC00]).bytes.as_slice(), b"\xED\xB0\x80");
+        assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9");  // Magic!
+        assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
+        assert_eq!(e(&[0xD800], &[0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
+        assert_eq!(e(&[0xD800], &[0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
+        assert_eq!(e(&[0xD7FF], &[0xDC00]).bytes, b"\xED\x9F\xBF\xED\xB0\x80");
+        assert_eq!(e(&[0x61], &[0xDC00]).bytes, b"\x61\xED\xB0\x80");
+        assert_eq!(e(&[], &[0xDC00]).bytes, b"\xED\xB0\x80");
     }
 
     #[test]
     fn wtf8buf_show() {
         let mut string = Wtf8Buf::from_str("aé 💩");
         string.push(CodePoint::from_u32(0xD800).unwrap());
-        assert_eq!(format!("{:?}", string).as_slice(), r#""aé 💩\u{D800}""#);
+        assert_eq!(format!("{:?}", string), r#""aé 💩\u{D800}""#);
     }
 
     #[test]
@@ -1086,7 +1086,7 @@ fn wtf8buf_as_slice() {
     fn wtf8_show() {
         let mut string = Wtf8Buf::from_str("aé 💩");
         string.push(CodePoint::from_u32(0xD800).unwrap());
-        assert_eq!(format!("{:?}", string.as_slice()).as_slice(), r#""aé 💩\u{D800}""#);
+        assert_eq!(format!("{:?}", string), r#""aé 💩\u{D800}""#);
     }
 
     #[test]
index 50a8e6b73e3866ff2b8d66879f97d3d9bbc20de7..cf05733cc18af07040bf705984be954777e43ae9 100644 (file)
 #[cfg(target_os = "linux")]
 pub const _SC_GETPW_R_SIZE_MAX: libc::c_int = 70;
 #[cfg(any(target_os = "macos",
-          target_os = "freebsd"))]
+          target_os = "freebsd",
+          target_os = "dragonfly"))]
 pub const _SC_GETPW_R_SIZE_MAX: libc::c_int = 71;
+#[cfg(target_os = "openbsd")]
+pub const _SC_GETPW_R_SIZE_MAX: libc::c_int = 101;
 #[cfg(target_os = "android")]
 pub const _SC_GETPW_R_SIZE_MAX: libc::c_int = 0x0048;
 
@@ -91,7 +94,9 @@ pub struct passwd {
 
 #[repr(C)]
 #[cfg(any(target_os = "macos",
-          target_os = "freebsd"))]
+          target_os = "freebsd",
+          target_os = "dragonfly",
+          target_os = "openbsd"))]
 pub struct passwd {
     pub pw_name: *mut libc::c_char,
     pub pw_passwd: *mut libc::c_char,
@@ -149,6 +154,9 @@ pub fn getpwuid_r(uid: libc::uid_t,
                       buf: *mut libc::c_char,
                       buflen: libc::size_t,
                       result: *mut *mut passwd) -> libc::c_int;
+
+    pub fn utimes(filename: *const libc::c_char,
+                  times: *const libc::timeval) -> libc::c_int;
 }
 
 #[cfg(any(target_os = "macos", target_os = "ios"))]
index 4a82b2807e7a3c914ab58c220fb694b1c04dc33c..689bbda83222997e9ff060974c49314327e41fe3 100644 (file)
 
 #![unstable(feature = "std_misc")]
 
-use vec::Vec;
-use sys::os_str::Buf;
-use sys_common::{AsInner, IntoInner, FromInner};
 use ffi::{OsStr, OsString};
+use fs::{Permissions, OpenOptions};
+use fs;
 use libc;
+use mem;
+use sys::os_str::Buf;
+use sys_common::{AsInner, AsInnerMut, IntoInner, FromInner};
+use vec::Vec;
 
 use old_io;
 
@@ -54,6 +57,12 @@ fn as_raw_fd(&self) -> Fd {
     }
 }
 
+impl AsRawFd for fs::File {
+    fn as_raw_fd(&self) -> Fd {
+        self.as_inner().fd().raw()
+    }
+}
+
 impl AsRawFd for old_io::pipe::PipeStream {
     fn as_raw_fd(&self) -> Fd {
         self.as_inner().fd()
@@ -123,18 +132,49 @@ fn into_vec(self) -> Vec<u8> {
 
 // Unix-specific extensions to `OsStr`.
 pub trait OsStrExt {
+    fn from_byte_slice(slice: &[u8]) -> &OsStr;
     fn as_byte_slice(&self) -> &[u8];
 }
 
 impl OsStrExt for OsStr {
+    fn from_byte_slice(slice: &[u8]) -> &OsStr {
+        unsafe { mem::transmute(slice) }
+    }
     fn as_byte_slice(&self) -> &[u8] {
         &self.as_inner().inner
     }
 }
 
+// Unix-specific extensions to `Permissions`
+pub trait PermissionsExt {
+    fn set_mode(&mut self, mode: i32);
+}
+
+impl PermissionsExt for Permissions {
+    fn set_mode(&mut self, mode: i32) {
+        *self = FromInner::from_inner(FromInner::from_inner(mode));
+    }
+}
+
+// Unix-specific extensions to `OpenOptions`
+pub trait OpenOptionsExt {
+    /// Set the mode bits that a new file will be created with.
+    ///
+    /// If a new file is created as part of a `File::open_opts` call then this
+    /// specified `mode` will be used as the permission bits for the new file.
+    fn mode(&mut self, mode: i32) -> &mut Self;
+}
+
+impl OpenOptionsExt for OpenOptions {
+    fn mode(&mut self, mode: i32) -> &mut OpenOptions {
+        self.as_inner_mut().mode(mode); self
+    }
+}
+
 /// A prelude for conveniently writing platform-specific code.
 ///
 /// Includes all extension traits, and some important type definitions.
 pub mod prelude {
-    pub use super::{Fd, AsRawFd};
+    #[doc(no_inline)]
+    pub use super::{Fd, AsRawFd, OsStrExt, OsStringExt, PermissionsExt};
 }
diff --git a/src/libstd/sys/unix/fd.rs b/src/libstd/sys/unix/fd.rs
new file mode 100644 (file)
index 0000000..f0943de
--- /dev/null
@@ -0,0 +1,70 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use core::prelude::*;
+use io::prelude::*;
+
+use io;
+use libc::{self, c_int, size_t, c_void};
+use mem;
+use sys::cvt;
+
+pub type fd_t = c_int;
+
+pub struct FileDesc {
+    fd: c_int,
+}
+
+impl FileDesc {
+    pub fn new(fd: c_int) -> FileDesc {
+        FileDesc { fd: fd }
+    }
+
+    pub fn raw(&self) -> c_int { self.fd }
+
+    /// Extract the actual filedescriptor without closing it.
+    pub fn into_raw(self) -> c_int {
+        let fd = self.fd;
+        unsafe { mem::forget(self) };
+        fd
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        let ret = try!(cvt(unsafe {
+            libc::read(self.fd,
+                       buf.as_mut_ptr() as *mut c_void,
+                       buf.len() as size_t)
+        }));
+        Ok(ret as usize)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        let ret = try!(cvt(unsafe {
+            libc::write(self.fd,
+                        buf.as_ptr() as *const c_void,
+                        buf.len() as size_t)
+        }));
+        Ok(ret as usize)
+    }
+}
+
+impl Drop for FileDesc {
+    fn drop(&mut self) {
+        // closing stdio file handles makes no sense, so never do it. Also, note
+        // that errors are ignored when closing a file descriptor. The reason
+        // for this is that if an error occurs we don't actually know if the
+        // file descriptor was closed or not, and if we retried (for something
+        // like EINTR), we might close another valid file descriptor (opened
+        // after we closed ours.
+        if self.fd > libc::STDERR_FILENO {
+            let _ = unsafe { libc::close(self.fd) };
+        }
+    }
+}
diff --git a/src/libstd/sys/unix/fs2.rs b/src/libstd/sys/unix/fs2.rs
new file mode 100644 (file)
index 0000000..070b324
--- /dev/null
@@ -0,0 +1,378 @@
+// Copyright 2013-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 core::prelude::*;
+use io::prelude::*;
+use os::unix::prelude::*;
+
+use ffi::{self, CString, OsString, AsOsStr, OsStr};
+use io::{self, Error, Seek, SeekFrom};
+use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t};
+use mem;
+use path::{Path, PathBuf};
+use ptr;
+use rc::Rc;
+use sys::fd::FileDesc;
+use sys::{c, cvt, cvt_r};
+use sys_common::FromInner;
+use vec::Vec;
+
+pub struct File(FileDesc);
+
+pub struct FileAttr {
+    stat: libc::stat,
+}
+
+pub struct ReadDir {
+    dirp: *mut libc::DIR,
+    root: Rc<PathBuf>,
+}
+
+pub struct DirEntry {
+    buf: Vec<u8>,
+    dirent: *mut libc::dirent_t,
+    root: Rc<PathBuf>,
+}
+
+#[derive(Clone)]
+pub struct OpenOptions {
+    flags: c_int,
+    read: bool,
+    write: bool,
+    mode: mode_t,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct FilePermissions { mode: mode_t }
+
+impl FileAttr {
+    pub fn is_dir(&self) -> bool {
+        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
+    }
+    pub fn is_file(&self) -> bool {
+        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
+    }
+    pub fn size(&self) -> u64 { self.stat.st_size as u64 }
+    pub fn perm(&self) -> FilePermissions {
+        FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
+    }
+
+    pub fn accessed(&self) -> u64 {
+        self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
+    }
+    pub fn modified(&self) -> u64 {
+        self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
+    }
+
+    // times are in milliseconds (currently)
+    fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
+        secs * 1000 + nsecs / 1000000
+    }
+}
+
+impl FilePermissions {
+    pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
+    pub fn set_readonly(&mut self, readonly: bool) {
+        if readonly {
+            self.mode &= !0o222;
+        } else {
+            self.mode |= 0o222;
+        }
+    }
+}
+
+impl FromInner<i32> for FilePermissions {
+    fn from_inner(mode: i32) -> FilePermissions {
+        FilePermissions { mode: mode as mode_t }
+    }
+}
+
+impl Iterator for ReadDir {
+    type Item = io::Result<DirEntry>;
+
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        extern {
+            fn rust_dirent_t_size() -> c_int;
+        }
+
+        let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
+            rust_dirent_t_size() as usize
+        });
+        let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
+
+        let mut entry_ptr = ptr::null_mut();
+        loop {
+            if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr) != 0 } {
+                return Some(Err(Error::last_os_error()))
+            }
+            if entry_ptr.is_null() {
+                return None
+            }
+
+            let entry = DirEntry {
+                buf: buf,
+                dirent: entry_ptr,
+                root: self.root.clone()
+            };
+            if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
+                buf = entry.buf;
+            } else {
+                return Some(Ok(entry))
+            }
+        }
+    }
+}
+
+impl Drop for ReadDir {
+    fn drop(&mut self) {
+        let r = unsafe { libc::closedir(self.dirp) };
+        debug_assert_eq!(r, 0);
+    }
+}
+
+impl DirEntry {
+    pub fn path(&self) -> PathBuf {
+        self.root.join(<OsStr as OsStrExt>::from_byte_slice(self.name_bytes()))
+    }
+
+    fn name_bytes(&self) -> &[u8] {
+        extern {
+            fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
+        }
+        unsafe {
+            let ptr = rust_list_dir_val(self.dirent);
+            ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr))
+        }
+    }
+}
+
+impl OpenOptions {
+    pub fn new() -> OpenOptions {
+        OpenOptions {
+            flags: 0,
+            read: false,
+            write: false,
+            mode: libc::S_IRUSR | libc::S_IWUSR,
+        }
+    }
+
+    pub fn read(&mut self, read: bool) {
+        self.read = read;
+    }
+
+    pub fn write(&mut self, write: bool) {
+        self.write = write;
+    }
+
+    pub fn append(&mut self, append: bool) {
+        self.flag(libc::O_APPEND, append);
+    }
+
+    pub fn truncate(&mut self, truncate: bool) {
+        self.flag(libc::O_TRUNC, truncate);
+    }
+
+    pub fn create(&mut self, create: bool) {
+        self.flag(libc::O_CREAT, create);
+    }
+
+    pub fn mode(&mut self, mode: i32) {
+        self.mode = mode as mode_t;
+    }
+
+    fn flag(&mut self, bit: c_int, on: bool) {
+        if on {
+            self.flags |= bit;
+        } else {
+            self.flags &= !bit;
+        }
+    }
+}
+
+impl File {
+    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
+        let flags = opts.flags | match (opts.read, opts.write) {
+            (true, true) => libc::O_RDWR,
+            (false, true) => libc::O_WRONLY,
+            (true, false) |
+            (false, false) => libc::O_RDONLY,
+        };
+        let path = cstr(path);
+        let fd = try!(cvt_r(|| unsafe {
+            libc::open(path.as_ptr(), flags, opts.mode)
+        }));
+        Ok(File(FileDesc::new(fd)))
+    }
+
+    pub fn file_attr(&self) -> io::Result<FileAttr> {
+        let mut stat: libc::stat = unsafe { mem::zeroed() };
+        try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
+        Ok(FileAttr { stat: stat })
+    }
+
+    pub fn fsync(&self) -> io::Result<()> {
+        try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
+        Ok(())
+    }
+
+    pub fn datasync(&self) -> io::Result<()> {
+        try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
+        return Ok(());
+
+        #[cfg(any(target_os = "macos", target_os = "ios"))]
+        unsafe fn os_datasync(fd: c_int) -> c_int {
+            libc::fcntl(fd, libc::F_FULLFSYNC)
+        }
+        #[cfg(target_os = "linux")]
+        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
+        #[cfg(not(any(target_os = "macos",
+                      target_os = "ios",
+                      target_os = "linux")))]
+        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
+    }
+
+    pub fn truncate(&self, size: u64) -> io::Result<()> {
+        try!(cvt_r(|| unsafe {
+            libc::ftruncate(self.0.raw(), size as libc::off_t)
+        }));
+        Ok(())
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        self.0.read(buf)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        self.0.write(buf)
+    }
+
+    pub fn flush(&self) -> io::Result<()> { Ok(()) }
+
+    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
+        let (whence, pos) = match pos {
+            SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
+            SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
+            SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
+        };
+        let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
+        Ok(n as u64)
+    }
+
+    pub fn fd(&self) -> &FileDesc { &self.0 }
+}
+
+fn cstr(path: &Path) -> CString {
+    CString::from_slice(path.as_os_str().as_byte_slice())
+}
+
+pub fn mkdir(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
+    Ok(())
+}
+
+pub fn readdir(p: &Path) -> io::Result<ReadDir> {
+    let root = Rc::new(p.to_path_buf());
+    let p = cstr(p);
+    unsafe {
+        let ptr = libc::opendir(p.as_ptr());
+        if ptr.is_null() {
+            Err(Error::last_os_error())
+        } else {
+            Ok(ReadDir { dirp: ptr, root: root })
+        }
+    }
+}
+
+pub fn unlink(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
+    let old = cstr(old);
+    let new = cstr(new);
+    try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
+    Ok(())
+}
+
+pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
+    Ok(())
+}
+
+pub fn rmdir(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt_r(|| unsafe {
+        libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
+    }));
+    Ok(())
+}
+
+pub fn readlink(p: &Path) -> io::Result<PathBuf> {
+    let c_path = cstr(p);
+    let p = c_path.as_ptr();
+    let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
+    if len < 0 {
+        len = 1024; // FIXME: read PATH_MAX from C ffi?
+    }
+    let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
+    unsafe {
+        let n = try!(cvt({
+            libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
+        }));
+        buf.set_len(n as usize);
+    }
+    let s: OsString = OsStringExt::from_vec(buf);
+    Ok(PathBuf::new(&s))
+}
+
+pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = cstr(src);
+    let dst = cstr(dst);
+    try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
+    Ok(())
+}
+
+pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = cstr(src);
+    let dst = cstr(dst);
+    try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
+    Ok(())
+}
+
+pub fn stat(p: &Path) -> io::Result<FileAttr> {
+    let p = cstr(p);
+    let mut stat: libc::stat = unsafe { mem::zeroed() };
+    try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
+    Ok(FileAttr { stat: stat })
+}
+
+pub fn lstat(p: &Path) -> io::Result<FileAttr> {
+    let p = cstr(p);
+    let mut stat: libc::stat = unsafe { mem::zeroed() };
+    try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
+    Ok(FileAttr { stat: stat })
+}
+
+pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
+    let p = cstr(p);
+    let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
+    try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));
+    Ok(())
+}
index 427cf21ac70a9cc86021597c2b5570a755fa0875..b5a24278a206edf8a9194c6860c1ef49c85648cc 100644 (file)
@@ -23,6 +23,7 @@
 use num::{Int, SignedInt};
 use num;
 use old_io::{self, IoResult, IoError};
+use io;
 use str;
 use sys_common::mkerr_libc;
 
@@ -39,9 +40,11 @@ macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
 
 pub mod backtrace;
 pub mod c;
-pub mod ext;
 pub mod condvar;
-pub mod fs;
+pub mod ext;
+pub mod fd;
+pub mod fs;  // support for std::old_io
+pub mod fs2; // support for std::fs
 pub mod helper_signal;
 pub mod mutex;
 pub mod os;
@@ -176,6 +179,26 @@ pub fn retry<T, F> (mut f: F) -> T where
     }
 }
 
+pub fn cvt<T: SignedInt>(t: T) -> io::Result<T> {
+    let one: T = Int::one();
+    if t == -one {
+        Err(io::Error::last_os_error())
+    } else {
+        Ok(t)
+    }
+}
+
+pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
+    where T: SignedInt, F: FnMut() -> T
+{
+    loop {
+        match cvt(f()) {
+            Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
+            other => return other,
+        }
+    }
+}
+
 pub fn ms_to_timeval(ms: u64) -> libc::timeval {
     libc::timeval {
         tv_sec: (ms / 1000) as libc::time_t,
index 5004ff713c45f42ffa2d13f3db39194a8b9f8936..b191eda583c9b82d4a57a3ea6da3f35d7d7b9fb0 100644 (file)
@@ -47,13 +47,9 @@ unsafe fn errno_location() -> *const c_int {
     }
 
     #[cfg(target_os = "openbsd")]
-    fn errno_location() -> *const c_int {
-        extern {
-            fn __errno() -> *const c_int;
-        }
-        unsafe {
-            __errno()
-        }
+    unsafe fn errno_location() -> *const c_int {
+        extern { fn __errno() -> *const c_int; }
+        __errno()
     }
 
     #[cfg(any(target_os = "linux", target_os = "android"))]
@@ -197,23 +193,23 @@ pub fn current_exe() -> IoResult<Path> {
 }
 
 #[cfg(target_os = "openbsd")]
-pub fn load_self() -> Option<Vec<u8>> {
+pub fn current_exe() -> IoResult<Path> {
     use sync::{StaticMutex, MUTEX_INIT};
 
     static LOCK: StaticMutex = MUTEX_INIT;
 
     extern {
-        fn rust_load_self() -> *const c_char;
+        fn rust_current_exe() -> *const c_char;
     }
 
     let _guard = LOCK.lock();
 
     unsafe {
-        let v = rust_load_self();
+        let v = rust_current_exe();
         if v.is_null() {
-            None
+            Err(IoError::last_error())
         } else {
-            Some(ffi::c_str_to_bytes(&v).to_vec())
+            Ok(Path::new(ffi::c_str_to_bytes(&v).to_vec()))
         }
     }
 }
@@ -333,7 +329,8 @@ pub fn args() -> Args {
 #[cfg(any(target_os = "linux",
           target_os = "android",
           target_os = "freebsd",
-          target_os = "dragonfly"))]
+          target_os = "dragonfly",
+          target_os = "openbsd"))]
 pub fn args() -> Args {
     use rt;
     let bytes = rt::args::clone().unwrap_or(Vec::new());
index a2c93dea6a4f504283da80a06635a9c99e88d343..023d951dc4f8a8aad9152e24f5fc2d527b859425 100644 (file)
@@ -51,7 +51,7 @@ pub fn from_str(s: &str) -> Buf {
     }
 
     pub fn as_slice(&self) -> &Slice {
-        unsafe { mem::transmute(self.inner.as_slice()) }
+        unsafe { mem::transmute(&*self.inner) }
     }
 
     pub fn into_string(self) -> Result<String, Buf> {
index 16274a2ab0820a0112a90a3cad32288ed3f6beaa..45d5b1506c3aaf13145740f055c5f78075b2d0d3 100644 (file)
@@ -151,8 +151,8 @@ fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
 
     pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
         let fd = self.fd();
-        let dolock = |&:| self.lock_nonblocking();
-        let doread = |&mut: nb| unsafe {
+        let dolock = || self.lock_nonblocking();
+        let doread = |nb| unsafe {
             let flags = if nb {c::MSG_DONTWAIT} else {0};
             libc::recv(fd,
                        buf.as_mut_ptr() as *mut libc::c_void,
@@ -164,8 +164,8 @@ pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
 
     pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
         let fd = self.fd();
-        let dolock = |&: | self.lock_nonblocking();
-        let dowrite = |&: nb: bool, buf: *const u8, len: uint| unsafe {
+        let dolock = || self.lock_nonblocking();
+        let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
             let flags = if nb {c::MSG_DONTWAIT} else {0};
             libc::send(fd,
                        buf as *const _,
index 20f86227e8eaf291d384ae40a0f34dbb39259e71..52a8ac9c338e0d4a58ba1a7f32a4b37af2bbea92 100644 (file)
@@ -84,8 +84,8 @@ unsafe fn set_cloexec(fd: c_int) {
             mem::transmute::<&ProcessConfig<K,V>,&'static ProcessConfig<K,V>>(cfg)
         };
 
-        with_envp(cfg.env(), move|envp: *const c_void| {
-            with_argv(cfg.program(), cfg.args(), move|argv: *const *const libc::c_char| unsafe {
+        with_envp(cfg.env(), move|envp: *const c_void| {
+            with_argv(cfg.program(), cfg.args(), move|argv: *const *const libc::c_char| unsafe {
                 let (input, mut output) = try!(sys::os::pipe());
 
                 // We may use this in the child, so perform allocations before the
@@ -185,7 +185,7 @@ fn fail(output: &mut FileDesc) -> ! {
                 // up /dev/null into that file descriptor. Otherwise, the first file
                 // descriptor opened up in the child would be numbered as one of the
                 // stdio file descriptors, which is likely to wreak havoc.
-                let setup = |&: src: Option<P>, dst: c_int| {
+                let setup = |src: Option<P>, dst: c_int| {
                     let src = match src {
                         None => {
                             let flags = if dst == libc::STDIN_FILENO {
index a3bbf5c5fe795d5c3c3c42abef13178884d90369..dc874c2c7913ce6bf9cc72339fa69d7f7bcdb8a7 100644 (file)
 
 pub use sys_common::wtf8::{Wtf8Buf, EncodeWide};
 
-use sys::os_str::Buf;
-use sys_common::{AsInner, FromInner};
 use ffi::{OsStr, OsString};
+use fs::{self, OpenOptions};
 use libc;
+use sys::os_str::Buf;
+use sys_common::{AsInner, FromInner, AsInnerMut};
 
 use old_io;
 
@@ -43,6 +44,12 @@ fn as_raw_handle(&self) -> Handle {
     }
 }
 
+impl AsRawHandle for fs::File {
+    fn as_raw_handle(&self) -> Handle {
+        self.as_inner().handle().raw()
+    }
+}
+
 impl AsRawHandle for old_io::pipe::PipeStream {
     fn as_raw_handle(&self) -> Handle {
         self.as_inner().handle()
@@ -122,9 +129,57 @@ fn encode_wide(&self) -> EncodeWide {
     }
 }
 
+// Windows-specific extensions to `OpenOptions`
+pub trait OpenOptionsExt {
+    /// Override the `dwDesiredAccess` argument to the call to `CreateFile` with
+    /// the specified value.
+    fn desired_access(&mut self, access: i32) -> &mut Self;
+
+    /// Override the `dwCreationDisposition` argument to the call to
+    /// `CreateFile` with the specified value.
+    ///
+    /// This will override any values of the standard `create` flags, for
+    /// example.
+    fn creation_disposition(&mut self, val: i32) -> &mut Self;
+
+    /// Override the `dwFlagsAndAttributes` argument to the call to
+    /// `CreateFile` with the specified value.
+    ///
+    /// This will override any values of the standard flags on the `OpenOptions`
+    /// structure.
+    fn flags_and_attributes(&mut self, val: i32) -> &mut Self;
+
+    /// Override the `dwShareMode` argument to the call to `CreateFile` with the
+    /// specified value.
+    ///
+    /// This will override any values of the standard flags on the `OpenOptions`
+    /// structure.
+    fn share_mode(&mut self, val: i32) -> &mut Self;
+}
+
+impl OpenOptionsExt for OpenOptions {
+    fn desired_access(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().desired_access(access); self
+    }
+    fn creation_disposition(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().creation_disposition(access); self
+    }
+    fn flags_and_attributes(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().flags_and_attributes(access); self
+    }
+    fn share_mode(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().share_mode(access); self
+    }
+}
+
 /// A prelude for conveniently writing platform-specific code.
 ///
 /// Includes all extension traits, and some important type definitions.
 pub mod prelude {
-    pub use super::{Socket, Handle, AsRawSocket, AsRawHandle, OsStrExt, OsStringExt};
+    #[doc(no_inline)]
+    pub use super::{Socket, Handle, AsRawSocket, AsRawHandle};
+    #[doc(no_inline)]
+    pub use super::{OsStrExt, OsStringExt};
+    #[doc(no_inline)]
+    pub use super::OpenOptionsExt;
 }
diff --git a/src/libstd/sys/windows/fs2.rs b/src/libstd/sys/windows/fs2.rs
new file mode 100644 (file)
index 0000000..74bb509
--- /dev/null
@@ -0,0 +1,428 @@
+// 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 core::prelude::*;
+use io::prelude::*;
+use os::windows::prelude::*;
+
+use default::Default;
+use ffi::{OsString, AsOsStr};
+use io::{self, Error, SeekFrom};
+use libc::{self, HANDLE};
+use mem;
+use path::{Path, PathBuf};
+use ptr;
+use sys::handle::Handle as RawHandle;
+use sys::{c, cvt};
+use vec::Vec;
+
+pub struct File { handle: RawHandle }
+pub struct FileAttr { data: c::WIN32_FILE_ATTRIBUTE_DATA }
+
+pub struct ReadDir {
+    handle: libc::HANDLE,
+    root: PathBuf,
+    first: Option<libc::WIN32_FIND_DATAW>,
+}
+
+pub struct DirEntry { path: PathBuf }
+
+#[derive(Clone, Default)]
+pub struct OpenOptions {
+    create: bool,
+    append: bool,
+    read: bool,
+    write: bool,
+    truncate: bool,
+    desired_access: Option<libc::DWORD>,
+    share_mode: Option<libc::DWORD>,
+    creation_disposition: Option<libc::DWORD>,
+    flags_and_attributes: Option<libc::DWORD>,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct FilePermissions { attrs: libc::DWORD }
+
+impl Iterator for ReadDir {
+    type Item = io::Result<DirEntry>;
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        if let Some(first) = self.first.take() {
+            if let Some(e) = DirEntry::new(&self.root, &first) {
+                return Some(Ok(e));
+            }
+        }
+        unsafe {
+            let mut wfd = mem::zeroed();
+            loop {
+                if libc::FindNextFileW(self.handle, &mut wfd) == 0 {
+                    if libc::GetLastError() ==
+                        c::ERROR_NO_MORE_FILES as libc::DWORD {
+                        return None
+                    } else {
+                        return Some(Err(Error::last_os_error()))
+                    }
+                }
+                if let Some(e) = DirEntry::new(&self.root, &wfd) {
+                    return Some(Ok(e))
+                }
+            }
+        }
+    }
+}
+
+impl Drop for ReadDir {
+    fn drop(&mut self) {
+        let r = unsafe { libc::FindClose(self.handle) };
+        debug_assert!(r != 0);
+    }
+}
+
+impl DirEntry {
+    fn new(root: &Path, wfd: &libc::WIN32_FIND_DATAW) -> Option<DirEntry> {
+        match &wfd.cFileName[0..3] {
+            // check for '.' and '..'
+            [46, 0, ..] |
+            [46, 46, 0, ..] => return None,
+            _ => {}
+        }
+
+        let filename = super::truncate_utf16_at_nul(&wfd.cFileName);
+        let filename: OsString = OsStringExt::from_wide(filename);
+        Some(DirEntry { path: root.join(&filename) })
+    }
+
+    pub fn path(&self) -> PathBuf {
+        self.path.clone()
+    }
+}
+
+impl OpenOptions {
+    pub fn new() -> OpenOptions { Default::default() }
+    pub fn read(&mut self, read: bool) { self.read = read; }
+    pub fn write(&mut self, write: bool) { self.write = write; }
+    pub fn append(&mut self, append: bool) { self.append = append; }
+    pub fn create(&mut self, create: bool) { self.create = create; }
+    pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
+    pub fn creation_disposition(&mut self, val: i32) {
+        self.creation_disposition = Some(val as libc::DWORD);
+    }
+    pub fn flags_and_attributes(&mut self, val: i32) {
+        self.flags_and_attributes = Some(val as libc::DWORD);
+    }
+    pub fn desired_access(&mut self, val: i32) {
+        self.desired_access = Some(val as libc::DWORD);
+    }
+    pub fn share_mode(&mut self, val: i32) {
+        self.share_mode = Some(val as libc::DWORD);
+    }
+
+    fn get_desired_access(&self) -> libc::DWORD {
+        self.desired_access.unwrap_or({
+            let mut base = if self.read {libc::FILE_GENERIC_READ} else {0} |
+                           if self.write {libc::FILE_GENERIC_WRITE} else {0};
+            if self.append {
+                base &= !libc::FILE_WRITE_DATA;
+                base |= libc::FILE_APPEND_DATA;
+            }
+            base
+        })
+    }
+
+    fn get_share_mode(&self) -> libc::DWORD {
+        // libuv has a good comment about this, but the basic idea is that
+        // we try to emulate unix semantics by enabling all sharing by
+        // allowing things such as deleting a file while it's still open.
+        self.share_mode.unwrap_or(libc::FILE_SHARE_READ |
+                                  libc::FILE_SHARE_WRITE |
+                                  libc::FILE_SHARE_DELETE)
+    }
+
+    fn get_creation_disposition(&self) -> libc::DWORD {
+        self.creation_disposition.unwrap_or({
+            match (self.create, self.truncate) {
+                (true, true) => libc::CREATE_ALWAYS,
+                (true, false) => libc::OPEN_ALWAYS,
+                (false, false) => libc::OPEN_EXISTING,
+                (false, true) => {
+                    if self.write && !self.append {
+                        libc::CREATE_ALWAYS
+                    } else {
+                        libc::TRUNCATE_EXISTING
+                    }
+                }
+            }
+        })
+    }
+
+    fn get_flags_and_attributes(&self) -> libc::DWORD {
+        self.flags_and_attributes.unwrap_or(libc::FILE_ATTRIBUTE_NORMAL)
+    }
+}
+
+impl File {
+    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
+        let path = to_utf16(path);
+        let handle = unsafe {
+            libc::CreateFileW(path.as_ptr(),
+                              opts.get_desired_access(),
+                              opts.get_share_mode(),
+                              ptr::null_mut(),
+                              opts.get_creation_disposition(),
+                              opts.get_flags_and_attributes(),
+                              ptr::null_mut())
+        };
+        if handle == libc::INVALID_HANDLE_VALUE {
+            Err(Error::last_os_error())
+        } else {
+            Ok(File { handle: RawHandle::new(handle) })
+        }
+    }
+
+    pub fn fsync(&self) -> io::Result<()> {
+        try!(cvt(unsafe { libc::FlushFileBuffers(self.handle.raw()) }));
+        Ok(())
+    }
+
+    pub fn datasync(&self) -> io::Result<()> { self.fsync() }
+
+    pub fn truncate(&self, size: u64) -> io::Result<()> {
+        let mut info = c::FILE_END_OF_FILE_INFO {
+            EndOfFile: size as libc::LARGE_INTEGER,
+        };
+        let size = mem::size_of_val(&info);
+        try!(cvt(unsafe {
+            c::SetFileInformationByHandle(self.handle.raw(),
+                                          c::FileEndOfFileInfo,
+                                          &mut info as *mut _ as *mut _,
+                                          size as libc::DWORD)
+        }));
+        Ok(())
+    }
+
+    pub fn file_attr(&self) -> io::Result<FileAttr> {
+        unsafe {
+            let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
+            try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
+                                                   &mut info)));
+            Ok(FileAttr {
+                data: c::WIN32_FILE_ATTRIBUTE_DATA {
+                    dwFileAttributes: info.dwFileAttributes,
+                    ftCreationTime: info.ftCreationTime,
+                    ftLastAccessTime: info.ftLastAccessTime,
+                    ftLastWriteTime: info.ftLastWriteTime,
+                    nFileSizeHigh: info.nFileSizeHigh,
+                    nFileSizeLow: info.nFileSizeLow,
+                }
+            })
+        }
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        let mut read = 0;
+        try!(cvt(unsafe {
+            libc::ReadFile(self.handle.raw(),
+                           buf.as_ptr() as libc::LPVOID,
+                           buf.len() as libc::DWORD,
+                           &mut read,
+                           ptr::null_mut())
+        }));
+        Ok(read as usize)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        let mut amt = 0;
+        try!(cvt(unsafe {
+            libc::WriteFile(self.handle.raw(),
+                            buf.as_ptr() as libc::LPVOID,
+                            buf.len() as libc::DWORD,
+                            &mut amt,
+                            ptr::null_mut())
+        }));
+        Ok(amt as usize)
+    }
+
+    pub fn flush(&self) -> io::Result<()> { Ok(()) }
+
+    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
+        let (whence, pos) = match pos {
+            SeekFrom::Start(n) => (libc::FILE_BEGIN, n as i64),
+            SeekFrom::End(n) => (libc::FILE_END, n),
+            SeekFrom::Current(n) => (libc::FILE_CURRENT, n),
+        };
+        let pos = pos as libc::LARGE_INTEGER;
+        let mut newpos = 0;
+        try!(cvt(unsafe {
+            libc::SetFilePointerEx(self.handle.raw(), pos,
+                                   &mut newpos, whence)
+        }));
+        Ok(newpos as u64)
+    }
+
+    pub fn handle(&self) -> &RawHandle { &self.handle }
+}
+
+pub fn to_utf16(s: &Path) -> Vec<u16> {
+    s.as_os_str().encode_wide().chain(Some(0).into_iter()).collect()
+}
+
+impl FileAttr {
+    pub fn is_dir(&self) -> bool {
+        self.data.dwFileAttributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
+    }
+    pub fn is_file(&self) -> bool {
+        !self.is_dir()
+    }
+    pub fn size(&self) -> u64 {
+        ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
+    }
+    pub fn perm(&self) -> FilePermissions {
+        FilePermissions { attrs: self.data.dwFileAttributes }
+    }
+
+    pub fn accessed(&self) -> u64 { self.to_ms(&self.data.ftLastAccessTime) }
+    pub fn modified(&self) -> u64 { self.to_ms(&self.data.ftLastWriteTime) }
+
+    fn to_ms(&self, ft: &libc::FILETIME) -> u64 {
+        // FILETIME is in 100ns intervals and there are 10000 intervals in a
+        // millisecond.
+        let bits = (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32);
+        bits / 10000
+    }
+}
+
+impl FilePermissions {
+    pub fn readonly(&self) -> bool {
+        self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
+    }
+
+    pub fn set_readonly(&mut self, readonly: bool) {
+        if readonly {
+            self.attrs |= c::FILE_ATTRIBUTE_READONLY;
+        } else {
+            self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
+        }
+    }
+}
+
+pub fn mkdir(p: &Path) -> io::Result<()> {
+    let p = to_utf16(p);
+    try!(cvt(unsafe {
+        libc::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
+    }));
+    Ok(())
+}
+
+pub fn readdir(p: &Path) -> io::Result<ReadDir> {
+    let root = p.to_path_buf();
+    let star = p.join("*");
+    let path = to_utf16(&star);
+
+    unsafe {
+        let mut wfd = mem::zeroed();
+        let find_handle = libc::FindFirstFileW(path.as_ptr(), &mut wfd);
+        if find_handle != libc::INVALID_HANDLE_VALUE {
+            Ok(ReadDir { handle: find_handle, root: root, first: Some(wfd) })
+        } else {
+            Err(Error::last_os_error())
+        }
+    }
+}
+
+pub fn unlink(p: &Path) -> io::Result<()> {
+    let p_utf16 = to_utf16(p);
+    try!(cvt(unsafe { libc::DeleteFileW(p_utf16.as_ptr()) }));
+    Ok(())
+}
+
+pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
+    let old = to_utf16(old);
+    let new = to_utf16(new);
+    try!(cvt(unsafe {
+        libc::MoveFileExW(old.as_ptr(), new.as_ptr(),
+                          libc::MOVEFILE_REPLACE_EXISTING)
+    }));
+    Ok(())
+}
+
+pub fn rmdir(p: &Path) -> io::Result<()> {
+    let p = to_utf16(p);
+    try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn readlink(p: &Path) -> io::Result<PathBuf> {
+    use sys::c::compat::kernel32::GetFinalPathNameByHandleW;
+    let mut opts = OpenOptions::new();
+    opts.read(true);
+    let file = try!(File::open(p, &opts));;
+
+    // Specify (sz - 1) because the documentation states that it's the size
+    // without the null pointer
+    //
+    // FIXME: I have a feeling that this reads intermediate symlinks as well.
+    let ret: OsString = try!(super::fill_utf16_buf_new(|buf, sz| unsafe {
+        GetFinalPathNameByHandleW(file.handle.raw(),
+                                  buf as *const u16,
+                                  sz - 1,
+                                  libc::VOLUME_NAME_DOS)
+    }, |s| OsStringExt::from_wide(s)));
+    Ok(PathBuf::new(&ret))
+}
+
+pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
+    use sys::c::compat::kernel32::CreateSymbolicLinkW;
+    let src = to_utf16(src);
+    let dst = to_utf16(dst);
+    try!(cvt(unsafe {
+        CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), 0) as libc::BOOL
+    }));
+    Ok(())
+}
+
+pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = to_utf16(src);
+    let dst = to_utf16(dst);
+    try!(cvt(unsafe {
+        libc::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
+    }));
+    Ok(())
+}
+
+pub fn stat(p: &Path) -> io::Result<FileAttr> {
+    let p = to_utf16(p);
+    unsafe {
+        let mut attr: FileAttr = mem::zeroed();
+        try!(cvt(c::GetFileAttributesExW(p.as_ptr(),
+                                         c::GetFileExInfoStandard,
+                                         &mut attr.data as *mut _ as *mut _)));
+        Ok(attr)
+    }
+}
+
+pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
+    let p = to_utf16(p);
+    unsafe {
+        try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
+        Ok(())
+    }
+}
+
+pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
+    let atime = super::ms_to_filetime(atime);
+    let mtime = super::ms_to_filetime(mtime);
+
+    let mut o = OpenOptions::new();
+    o.write(true);
+    let f = try!(File::open(p, &o));
+    try!(cvt(unsafe {
+        c::SetFileTime(f.handle.raw(), 0 as *const _, &atime, &mtime)
+    }));
+    Ok(())
+}
index 6737eeef12532604554536076e75b641197bdd69..52aa5fb036a9acc338291bdf136f9028b1e12547 100644 (file)
@@ -21,6 +21,7 @@ impl Handle {
     pub fn new(handle: HANDLE) -> Handle {
         Handle(handle)
     }
+    pub fn raw(&self) -> HANDLE { self.0 }
 }
 
 impl Drop for Handle {
index f1af70e2cf7d1eb341bc87ff5bee89d0133bbca1..140bdb1450102f945b69d246360088224336d219 100644 (file)
 use prelude::v1::*;
 
 use ffi::OsStr;
-use io::ErrorKind;
+use io::{self, ErrorKind};
 use libc;
 use mem;
 use old_io::{self, IoResult, IoError};
+use num::Int;
 use os::windows::OsStrExt;
 use sync::{Once, ONCE_INIT};
 
@@ -38,6 +39,7 @@ macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
 pub mod condvar;
 pub mod ext;
 pub mod fs;
+pub mod fs2;
 pub mod handle;
 pub mod helper_signal;
 pub mod mutex;
@@ -248,7 +250,7 @@ fn to_utf16_os(s: &OsStr) -> Vec<u16> {
 // Once the syscall has completed (errors bail out early) the second closure is
 // yielded the data which has been read from the syscall. The return value
 // from this closure is then the return value of the function.
-fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
+fn fill_utf16_buf_base<F1, F2, T>(mut f1: F1, f2: F2) -> Result<T, ()>
     where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
           F2: FnOnce(&[u16]) -> T
 {
@@ -280,7 +282,7 @@ fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
             c::SetLastError(0);
             let k = match f1(buf.as_mut_ptr(), n as libc::DWORD) {
                 0 if libc::GetLastError() == 0 => 0,
-                0 => return Err(IoError::last_error()),
+                0 => return Err(()),
                 n => n,
             } as usize;
             if k == n && libc::GetLastError() ==
@@ -295,6 +297,20 @@ fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
     }
 }
 
+fn fill_utf16_buf<F1, F2, T>(f1: F1, f2: F2) -> IoResult<T>
+    where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
+          F2: FnOnce(&[u16]) -> T
+{
+    fill_utf16_buf_base(f1, f2).map_err(|()| IoError::last_error())
+}
+
+fn fill_utf16_buf_new<F1, F2, T>(f1: F1, f2: F2) -> io::Result<T>
+    where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
+          F2: FnOnce(&[u16]) -> T
+{
+    fill_utf16_buf_base(f1, f2).map_err(|()| io::Error::last_os_error())
+}
+
 fn os2path(s: &[u16]) -> Path {
     // FIXME: this should not be a panicking conversion (aka path reform)
     Path::new(String::from_utf16(s).unwrap())
@@ -307,3 +323,21 @@ pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
         None => v
     }
 }
+
+fn cvt<I: Int>(i: I) -> io::Result<I> {
+    if i == Int::zero() {
+        Err(io::Error::last_os_error())
+    } else {
+        Ok(i)
+    }
+}
+
+fn ms_to_filetime(ms: u64) -> libc::FILETIME {
+    // A FILETIME is a count of 100 nanosecond intervals, so we multiply by
+    // 10000 b/c there are 10000 intervals in 1 ms
+    let ms = ms * 10000;
+    libc::FILETIME {
+        dwLowDateTime: ms as u32,
+        dwHighDateTime: (ms >> 32) as u32,
+    }
+}
index c71e2d057c35117af1cea05e2506f25fdf2f075a..7e684c5234141aad1e15762f0fa6503ba2996ae6 100644 (file)
@@ -109,7 +109,7 @@ fn next(&mut self) -> Option<(OsString, OsString)> {
                 len += 1;
             }
             let p = p as *const u16;
-            let s = slice::from_raw_buf(&p, len as usize);
+            let s = slice::from_raw_parts(p, len as usize);
             self.cur = self.cur.offset(len + 1);
 
             let (k, v) = match s.iter().position(|&b| b == '=' as u16) {
@@ -191,7 +191,7 @@ fn next(&mut self) -> Option<Path> {
     }
 }
 
-#[derive(Show)]
+#[derive(Debug)]
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
@@ -296,7 +296,7 @@ fn next(&mut self) -> Option<OsString> {
 
             // Push it onto the list.
             let ptr = ptr as *const u16;
-            let buf = slice::from_raw_buf(&ptr, len as usize);
+            let buf = slice::from_raw_parts(ptr, len as usize);
             OsStringExt::from_wide(buf)
         })
     }
index 315c41e779a36c7abfce420642b2cebb1c357a99..eab60047aa2bf557ea515fd53903e60d8b6d9bd1 100644 (file)
@@ -169,7 +169,7 @@ pub fn spawn<K, V, C, P>(cfg: &C, in_fd: Option<P>,
             // Similarly to unix, we don't actually leave holes for the stdio file
             // descriptors, but rather open up /dev/null equivalents. These
             // equivalents are drawn from libuv's windows process spawning.
-            let set_fd = |&: fd: &Option<P>, slot: &mut HANDLE,
+            let set_fd = |fd: &Option<P>, slot: &mut HANDLE,
                           is_stdin: bool| {
                 match *fd {
                     None => {
@@ -389,7 +389,7 @@ fn append_arg(cmd: &mut String, arg: &str) {
         }
         let argvec: Vec<char> = arg.chars().collect();
         for i in 0u..argvec.len() {
-            append_char_at(cmd, argvec.as_slice(), i);
+            append_char_at(cmd, &argvec, i);
         }
         if quote {
             cmd.push('"');
@@ -485,10 +485,9 @@ mod tests {
     fn test_make_command_line() {
         fn test_wrapper(prog: &str, args: &[&str]) -> String {
             make_command_line(&CString::from_slice(prog.as_bytes()),
-                              args.iter()
-                                  .map(|a| CString::from_slice(a.as_bytes()))
-                                  .collect::<Vec<CString>>()
-                                  .as_slice())
+                              &args.iter()
+                                   .map(|a| CString::from_slice(a.as_bytes()))
+                                   .collect::<Vec<CString>>())
         }
 
         assert_eq!(
index 54a32e43daf5917909e1b5594b7003f646d71fa4..0c24ab1fa09b4e964f1f424f5c4d117e8e4e93bc 100644 (file)
@@ -191,7 +191,7 @@ unsafe fn unregister_dtor(key: Key) -> bool {
 // # What's up with this callback?
 //
 // The callback specified receives a number of parameters from... someone!
-// (the kernel? the runtime? I'm not qute sure!) There are a few events that
+// (the kernel? the runtime? I'm not quite sure!) There are a few events that
 // this gets invoked for, but we're currently only interested on when a
 // thread or a process "detaches" (exits). The process part happens for the
 // last thread and the thread part happens for any normal thread.
index f02c8e49f4188d1b26c783ffcd20ace768c8e8f7..8a8b53090570cadcd188b6f840b41ffbe81771ed 100644 (file)
@@ -104,7 +104,7 @@ pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
                 _ => (),
             };
             utf16.truncate(num as uint);
-            let utf8 = match String::from_utf16(utf16.as_slice()) {
+            let utf8 = match String::from_utf16(&utf16) {
                 Ok(utf8) => utf8.into_bytes(),
                 Err(..) => return Err(invalid_encoding()),
             };
index c791ee2717b0bf00cb264969443f9419429465ce..eb967c9f4e331f31a9bb5aa88aa7ac5d2f73d179 100644 (file)
 use option::Option::{self, Some, None};
 use result::Result::{Err, Ok};
 use sync::{Mutex, Condvar, Arc};
-use str::Str;
 use string::String;
 use rt::{self, unwind};
 use old_io::{Writer, stdio};
@@ -246,7 +245,7 @@ pub fn scoped<'a, T, F>(self, f: F) -> JoinGuard<'a, T> where
     {
         let my_packet = Packet(Arc::new(UnsafeCell::new(None)));
         let their_packet = Packet(my_packet.0.clone());
-        let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(move |ret| unsafe {
+        let (native, thread) = self.spawn_inner(Thunk::new(f), Thunk::with_arg(move |ret| unsafe {
             *their_packet.0.get() = Some(ret);
         }));
 
@@ -273,7 +272,7 @@ fn spawn_inner<T: Send>(self, f: Thunk<(), T>, finish: Thunk<Result<T>, ()>)
         // because by the time that this function is executing we've already
         // consumed at least a little bit of stack (we don't know the exact byte
         // address at which our stack started).
-        let main = move |:| {
+        let main = move || {
             let something_around_the_top_of_the_stack = 1;
             let addr = &something_around_the_top_of_the_stack as *const int;
             let my_stack_top = addr as uint;
@@ -289,7 +288,7 @@ fn spawn_inner<T: Send>(self, f: Thunk<(), T>, finish: Thunk<Result<T>, ()>)
 
             let mut output = None;
             let f: Thunk<(), T> = if stdout.is_some() || stderr.is_some() {
-                Thunk::new(move |:| {
+                Thunk::new(move || {
                     let _ = stdout.map(stdio::set_stdout);
                     let _ = stderr.map(stdio::set_stderr);
                     f.invoke(())
@@ -452,7 +451,7 @@ pub fn unpark(&self) {
     /// Get the thread's name.
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn name(&self) -> Option<&str> {
-        self.inner.name.as_ref().map(|s| s.as_slice())
+        self.inner.name.as_ref().map(|s| &**s)
     }
 }
 
@@ -574,7 +573,7 @@ fn test_run_basic() {
     fn test_join_success() {
         match Thread::scoped(move|| -> String {
             "Success!".to_string()
-        }).join().as_ref().map(|s| s.as_slice()) {
+        }).join().as_ref().map(|s| &**s) {
             result::Result::Ok("Success!") => (),
             _ => panic!()
         }
index 2e53d0ceecbdfc0b00b1602d34d9b06ca43afd37..0831242f954cf0e95b12ecae70766a3dc991554c 100644 (file)
@@ -24,7 +24,7 @@ impl<R> Thunk<(),R> {
     pub fn new<F>(func: F) -> Thunk<(),R>
         where F : FnOnce() -> R, F : Send
     {
-        Thunk::with_arg(move|()| func())
+        Thunk::with_arg(move|()| func())
     }
 }
 
index 76b8d736aad544dfcac4cee7c941362de4ec344e..42ef3459a0ed7cf931f191e300a7940ca87b21e9 100644 (file)
@@ -232,7 +232,7 @@ pub fn num_nanoseconds(&self) -> Option<i64> {
         secs_part.checked_add(nanos_part as i64)
     }
 
-    /// Add two durations, returning `None` if overflow occured.
+    /// Add two durations, returning `None` if overflow occurred.
     #[unstable(feature = "std_misc")]
     pub fn checked_add(&self, rhs: &Duration) -> Option<Duration> {
         let mut secs = try_opt!(self.secs.checked_add(rhs.secs));
@@ -247,7 +247,7 @@ pub fn checked_add(&self, rhs: &Duration) -> Option<Duration> {
         if d < MIN || d > MAX { None } else { Some(d) }
     }
 
-    /// Subtract two durations, returning `None` if overflow occured.
+    /// Subtract two durations, returning `None` if overflow occurred.
     #[unstable(feature = "std_misc")]
     pub fn checked_sub(&self, rhs: &Duration) -> Option<Duration> {
         let mut secs = try_opt!(self.secs.checked_sub(rhs.secs));
index 34eeedeaa7650bba3e232b1f6fe901982fb1071e..f8793f81b199642e13371c51e2456765afb8f5e7 100644 (file)
@@ -112,13 +112,13 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 impl fmt::Debug for Name {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         let Name(nm) = *self;
-        write!(f, "{:?}({})", token::get_name(*self).get(), nm)
+        write!(f, "{:?}({})", token::get_name(*self), nm)
     }
 }
 
 impl fmt::Display for Name {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        fmt::Display::fmt(token::get_name(*self).get(), f)
+        fmt::Display::fmt(&token::get_name(*self), f)
     }
 }
 
@@ -174,7 +174,7 @@ impl Name {
     pub fn as_str<'a>(&'a self) -> &'a str {
         unsafe {
             // FIXME #12938: can't use copy_lifetime since &str isn't a &T
-            ::std::mem::transmute::<&str,&str>(token::get_name(*self).get())
+            ::std::mem::transmute::<&str,&str>(&token::get_name(*self))
         }
     }
 
@@ -193,7 +193,7 @@ pub fn ident(&self) -> Ident {
 
 impl Encodable for Ident {
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
-        s.emit_str(token::get_ident(*self).get())
+        s.emit_str(&token::get_ident(*self))
     }
 }
 
@@ -443,6 +443,7 @@ pub enum WherePredicate {
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
 pub struct WhereBoundPredicate {
     pub span: Span,
+    pub bound_lifetimes: Vec<LifetimeDef>,
     pub bounded_ty: P<Ty>,
     pub bounds: OwnedSlice<TyParamBound>,
 }
@@ -924,13 +925,13 @@ pub fn get_tt(&self, index: usize) -> TokenTree {
                 let v = [TtToken(sp, token::Dollar),
                          TtToken(sp, token::Ident(token::str_to_ident(var.as_str()),
                                                   token::Plain))];
-                v[index]
+                v[index].clone()
             }
             (&TtToken(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
                 let v = [TtToken(sp, token::SubstNt(name, name_st)),
                          TtToken(sp, token::Colon),
                          TtToken(sp, token::Ident(kind, kind_st))];
-                v[index]
+                v[index].clone()
             }
             (&TtSequence(_, ref seq), _) => {
                 seq.tts[index].clone()
@@ -1535,6 +1536,8 @@ pub struct PolyTraitRef {
 
     /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`
     pub trait_ref: TraitRef,
+
+    pub span: Span,
 }
 
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
index a85b87f47d6ee0d1a9338f262a8344bed2624ff9..1a537c7a5b8f89fdd7f5b3623c3750c6c714eed4 100644 (file)
@@ -179,13 +179,13 @@ pub fn id(self) -> NodeId {
     }
 
     pub fn kind(self) -> visit::FnKind<'a> {
-        let item = |p: ItemFnParts<'a>| -> visit::FnKind<'a> {
+        let item = |p: ItemFnParts<'a>| -> visit::FnKind<'a> {
             visit::FkItemFn(p.ident, p.generics, p.unsafety, p.abi)
         };
-        let closure = |_: ClosureParts| {
+        let closure = |_: ClosureParts| {
             visit::FkFnBlock
         };
-        let method = |m: &'a ast::Method| {
+        let method = |m: &'a ast::Method| {
             visit::FkMethod(m.pe_ident(), m.pe_generics(), m)
         };
         self.handle(item, method, closure)
index c62f76564a7013ada7ba7c1ff4ee0899293d4e66..b8d4c90f74523fdb48c575dd7b13c0079ed7288b 100644 (file)
@@ -27,7 +27,7 @@
 pub fn path_name_i(idents: &[Ident]) -> String {
     // FIXME: Bad copies (#2543 -- same for everything else that says "bad")
     idents.iter().map(|i| {
-        token::get_ident(*i).get().to_string()
+        token::get_ident(*i).to_string()
     }).collect::<Vec<String>>().connect("::")
 }
 
index 301a18892d8e3684d6b6688878550771be4a3f0c..a3afe5780d0d509cf7109e2b4e20bb56f2cf2215 100644 (file)
@@ -44,7 +44,7 @@ pub fn is_used(attr: &Attribute) -> bool {
 
 pub trait AttrMetaMethods {
     fn check_name(&self, name: &str) -> bool {
-        name == self.name().get()
+        name == &self.name()[]
     }
 
     /// Retrieve the name of the meta item, e.g. `foo` in `#[foo]`,
@@ -62,7 +62,7 @@ fn check_name(&self, name: &str) -> bool {
 
 impl AttrMetaMethods for Attribute {
     fn check_name(&self, name: &str) -> bool {
-        let matches = name == self.name().get();
+        let matches = name == &self.name()[];
         if matches {
             mark_used(self);
         }
@@ -142,7 +142,7 @@ fn with_desugared_doc<T, F>(&self, f: F) -> T where
             let meta = mk_name_value_item_str(
                 InternedString::new("doc"),
                 token::intern_and_get_ident(&strip_doc_comment_decoration(
-                        comment.get())[]));
+                        &comment)[]));
             if self.node.style == ast::AttrOuter {
                 f(&mk_attr_outer(self.node.id, meta))
             } else {
@@ -209,7 +209,7 @@ pub fn mk_attr_outer(id: AttrId, item: P<MetaItem>) -> Attribute {
 pub fn mk_sugared_doc_attr(id: AttrId, text: InternedString, lo: BytePos,
                            hi: BytePos)
                            -> Attribute {
-    let style = doc_comment_style(text.get());
+    let style = doc_comment_style(&text);
     let lit = spanned(lo, hi, ast::LitStr(text, ast::CookedStr));
     let attr = Attribute_ {
         id: id,
@@ -326,11 +326,11 @@ pub fn requests_inline(attrs: &[Attribute]) -> bool {
 /// Tests if a cfg-pattern matches the cfg set
 pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::MetaItem) -> bool {
     match cfg.node {
-        ast::MetaList(ref pred, ref mis) if pred.get() == "any" =>
+        ast::MetaList(ref pred, ref mis) if &pred[] == "any" =>
             mis.iter().any(|mi| cfg_matches(diagnostic, cfgs, &**mi)),
-        ast::MetaList(ref pred, ref mis) if pred.get() == "all" =>
+        ast::MetaList(ref pred, ref mis) if &pred[] == "all" =>
             mis.iter().all(|mi| cfg_matches(diagnostic, cfgs, &**mi)),
-        ast::MetaList(ref pred, ref mis) if pred.get() == "not" => {
+        ast::MetaList(ref pred, ref mis) if &pred[] == "not" => {
             if mis.len() != 1 {
                 diagnostic.span_err(cfg.span, "expected 1 cfg-pattern");
                 return false;
@@ -338,7 +338,7 @@ pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::Me
             !cfg_matches(diagnostic, cfgs, &*mis[0])
         }
         ast::MetaList(ref pred, _) => {
-            diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).as_slice());
+            diagnostic.span_err(cfg.span, &format!("invalid predicate `{}`", pred));
             false
         },
         ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg),
@@ -382,7 +382,7 @@ fn find_stability_generic<'a,
 
     'outer: for attr in attrs {
         let tag = attr.name();
-        let tag = tag.get();
+        let tag = &tag[];
         if tag != "deprecated" && tag != "unstable" && tag != "stable" {
             continue // not a stability level
         }
@@ -394,8 +394,8 @@ fn find_stability_generic<'a,
                 let mut feature = None;
                 let mut since = None;
                 let mut reason = None;
-                for meta in metas {
-                    if meta.name().get() == "feature" {
+                for meta in metas.iter() {
+                    if meta.name() == "feature" {
                         match meta.value_str() {
                             Some(v) => feature = Some(v),
                             None => {
@@ -404,7 +404,7 @@ fn find_stability_generic<'a,
                             }
                         }
                     }
-                    if meta.name().get() == "since" {
+                    if &meta.name()[] == "since" {
                         match meta.value_str() {
                             Some(v) => since = Some(v),
                             None => {
@@ -413,7 +413,7 @@ fn find_stability_generic<'a,
                             }
                         }
                     }
-                    if meta.name().get() == "reason" {
+                    if &meta.name()[] == "reason" {
                         match meta.value_str() {
                             Some(v) => reason = Some(v),
                             None => {
@@ -521,11 +521,11 @@ pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec<ReprAt
             for item in items {
                 match item.node {
                     ast::MetaWord(ref word) => {
-                        let hint = match word.get() {
+                        let hint = match &word[] {
                             // Can't use "extern" because it's not a lexical identifier.
                             "C" => Some(ReprExtern),
                             "packed" => Some(ReprPacked),
-                            _ => match int_type_of_word(word.get()) {
+                            _ => match int_type_of_word(&word) {
                                 Some(ity) => Some(ReprInt(item.span, ity)),
                                 None => {
                                     // Not a word we recognize
index 00857d10f439e763e4cdb3af4cbf160d09f0fc39..3231342cb50c8f37524ca7d44ee66fb163d56344 100644 (file)
@@ -437,18 +437,35 @@ pub fn span_to_lines(&self, sp: Span) -> FileLines {
         FileLines {file: lo.file, lines: lines}
     }
 
-    pub fn span_to_snippet(&self, sp: Span) -> Option<String> {
+    pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
+        if sp.lo > sp.hi {
+            return Err(SpanSnippetError::IllFormedSpan(sp));
+        }
+
         let begin = self.lookup_byte_offset(sp.lo);
         let end = self.lookup_byte_offset(sp.hi);
 
-        // FIXME #8256: this used to be an assert but whatever precondition
-        // it's testing isn't true for all spans in the AST, so to allow the
-        // caller to not have to panic (and it can't catch it since the CodeMap
-        // isn't sendable), return None
         if begin.fm.start_pos != end.fm.start_pos {
-            None
+            return Err(SpanSnippetError::DistinctSources(DistinctSources {
+                begin: (begin.fm.name.clone(),
+                        begin.fm.start_pos),
+                end: (end.fm.name.clone(),
+                      end.fm.start_pos)
+            }));
         } else {
-            Some((&begin.fm.src[begin.pos.to_usize()..end.pos.to_usize()]).to_string())
+            let start = begin.pos.to_usize();
+            let limit = end.pos.to_usize();
+            if start > limit || limit > begin.fm.src.len() {
+                return Err(SpanSnippetError::MalformedForCodemap(
+                    MalformedCodemapPositions {
+                        name: begin.fm.name.clone(),
+                        source_len: begin.fm.src.len(),
+                        begin_pos: begin.pos,
+                        end_pos: end.pos,
+                    }));
+            }
+
+            return Ok((&begin.fm.src[start..limit]).to_string())
         }
     }
 
@@ -622,6 +639,27 @@ pub fn span_is_internal(&self, span: Span) -> bool {
     }
 }
 
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub enum SpanSnippetError {
+    IllFormedSpan(Span),
+    DistinctSources(DistinctSources),
+    MalformedForCodemap(MalformedCodemapPositions),
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct DistinctSources {
+    begin: (String, BytePos),
+    end: (String, BytePos)
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct MalformedCodemapPositions {
+    name: String,
+    source_len: usize,
+    begin_pos: BytePos,
+    end_pos: BytePos
+}
+
 #[cfg(test)]
 mod test {
     use super::*;
@@ -773,7 +811,7 @@ fn t8() {
         let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
         let snippet = cm.span_to_snippet(span);
 
-        assert_eq!(snippet, Some("second line".to_string()));
+        assert_eq!(snippet, Ok("second line".to_string()));
     }
 
     #[test]
index 3eaac0fe333e8e3026f69abd6ca6b0f7d8f52653..eb845e463a0f1b8e1da21b4e5ebed7f6559139d7 100644 (file)
@@ -27,7 +27,7 @@ struct Context<F> where F: FnMut(&[ast::Attribute]) -> bool {
 // any items that do not belong in the current configuration
 pub fn strip_unconfigured_items(diagnostic: &SpanHandler, krate: ast::Crate) -> ast::Crate {
     let config = krate.config.clone();
-    strip_items(krate, |attrs| in_cfg(diagnostic, config.as_slice(), attrs))
+    strip_items(krate, |attrs| in_cfg(diagnostic, &config, attrs))
 }
 
 impl<F> fold::Folder for Context<F> where F: FnMut(&[ast::Attribute]) -> bool {
@@ -132,7 +132,7 @@ fn fold_item_underscore<F>(cx: &mut Context<F>, item: ast::Item_) -> ast::Item_
         }
         ast::ItemEnum(def, generics) => {
             let variants = def.variants.into_iter().filter_map(|v| {
-                if !(cx.in_cfg)(v.node.attrs.as_slice()) {
+                if !(cx.in_cfg)(&v.node.attrs) {
                     None
                 } else {
                     Some(v.map(|Spanned {node: ast::Variant_ {id, name, attrs, kind,
@@ -172,7 +172,7 @@ fn fold_struct<F>(cx: &mut Context<F>, def: P<ast::StructDef>) -> P<ast::StructD
     def.map(|ast::StructDef { fields, ctor_id }| {
         ast::StructDef {
             fields: fields.into_iter().filter(|m| {
-                (cx.in_cfg)(m.node.attrs.as_slice())
+                (cx.in_cfg)(&m.node.attrs)
             }).collect(),
             ctor_id: ctor_id,
         }
@@ -223,7 +223,7 @@ fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where
             node: match node {
                 ast::ExprMatch(m, arms, source) => {
                     ast::ExprMatch(m, arms.into_iter()
-                                        .filter(|a| (cx.in_cfg)(a.attrs.as_slice()))
+                                        .filter(|a| (cx.in_cfg)(&a.attrs))
                                         .collect(), source)
                 }
                 _ => node
@@ -236,22 +236,22 @@ fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where
 fn item_in_cfg<F>(cx: &mut Context<F>, item: &ast::Item) -> bool where
     F: FnMut(&[ast::Attribute]) -> bool
 {
-    return (cx.in_cfg)(item.attrs.as_slice());
+    return (cx.in_cfg)(&item.attrs);
 }
 
 fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool where
     F: FnMut(&[ast::Attribute]) -> bool
 {
-    return (cx.in_cfg)(item.attrs.as_slice());
+    return (cx.in_cfg)(&item.attrs);
 }
 
 fn trait_method_in_cfg<F>(cx: &mut Context<F>, meth: &ast::TraitItem) -> bool where
     F: FnMut(&[ast::Attribute]) -> bool
 {
     match *meth {
-        ast::RequiredMethod(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
-        ast::ProvidedMethod(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
-        ast::TypeTraitItem(ref typ) => (cx.in_cfg)(typ.attrs.as_slice()),
+        ast::RequiredMethod(ref meth) => (cx.in_cfg)(&meth.attrs),
+        ast::ProvidedMethod(ref meth) => (cx.in_cfg)(&meth.attrs),
+        ast::TypeTraitItem(ref typ) => (cx.in_cfg)(&typ.attrs),
     }
 }
 
@@ -259,8 +259,8 @@ fn impl_item_in_cfg<F>(cx: &mut Context<F>, impl_item: &ast::ImplItem) -> bool w
     F: FnMut(&[ast::Attribute]) -> bool
 {
     match *impl_item {
-        ast::MethodImplItem(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
-        ast::TypeImplItem(ref typ) => (cx.in_cfg)(typ.attrs.as_slice()),
+        ast::MethodImplItem(ref meth) => (cx.in_cfg)(&meth.attrs),
+        ast::TypeImplItem(ref typ) => (cx.in_cfg)(&typ.attrs),
     }
 }
 
index 9321d3ca3df1141196a45917db933c208d3fb56d..54689a1f77ad2dddcb9e6fa96bdff67b0de08e53 100644 (file)
@@ -18,7 +18,7 @@ macro_rules! register_diagnostic {
 macro_rules! span_fatal {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
         __diagnostic_used!($code);
-        $session.span_fatal_with_code($span, format!($($message)*).as_slice(), stringify!($code))
+        $session.span_fatal_with_code($span, &format!($($message)*), stringify!($code))
     })
 }
 
@@ -26,7 +26,7 @@ macro_rules! span_fatal {
 macro_rules! span_err {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
         __diagnostic_used!($code);
-        $session.span_err_with_code($span, format!($($message)*).as_slice(), stringify!($code))
+        $session.span_err_with_code($span, &format!($($message)*), stringify!($code))
     })
 }
 
@@ -34,21 +34,21 @@ macro_rules! span_err {
 macro_rules! span_warn {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
         __diagnostic_used!($code);
-        $session.span_warn_with_code($span, format!($($message)*).as_slice(), stringify!($code))
+        $session.span_warn_with_code($span, &format!($($message)*), stringify!($code))
     })
 }
 
 #[macro_export]
 macro_rules! span_note {
     ($session:expr, $span:expr, $($message:tt)*) => ({
-        ($session).span_note($span, format!($($message)*).as_slice())
+        ($session).span_note($span, &format!($($message)*))
     })
 }
 
 #[macro_export]
 macro_rules! span_help {
     ($session:expr, $span:expr, $($message:tt)*) => ({
-        ($session).span_help($span, format!($($message)*).as_slice())
+        ($session).span_help($span, &format!($($message)*))
     })
 }
 
index bd5247bbad6a78f9b6e4e2335afd910f0a9b174a..833a6d52acb9798ef77c766aa69ee65535b298e6 100644 (file)
@@ -10,6 +10,7 @@
 
 use std::cell::RefCell;
 use std::collections::BTreeMap;
+
 use ast;
 use ast::{Ident, Name, TokenTree};
 use codemap::Span;
@@ -57,7 +58,7 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,
         match diagnostics.insert(code.name, span) {
             Some(previous_span) => {
                 ecx.span_warn(span, &format!(
-                    "diagnostic code {} already used", token::get_ident(code).get()
+                    "diagnostic code {} already used", &token::get_ident(code)
                 )[]);
                 ecx.span_note(previous_span, "previous invocation");
             },
@@ -68,7 +69,7 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt,
     with_registered_diagnostics(|diagnostics| {
         if !diagnostics.contains_key(&code.name) {
             ecx.span_err(span, &format!(
-                "used diagnostic code {} not registered", token::get_ident(code).get()
+                "used diagnostic code {} not registered", &token::get_ident(code)
             )[]);
         }
     });
@@ -93,12 +94,12 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt,
     with_registered_diagnostics(|diagnostics| {
         if diagnostics.insert(code.name, description).is_some() {
             ecx.span_err(span, &format!(
-                "diagnostic code {} already registered", token::get_ident(*code).get()
+                "diagnostic code {} already registered", &token::get_ident(*code)
             )[]);
         }
     });
     let sym = Ident::new(token::gensym(&(
-        "__register_diagnostic_".to_string() + token::get_ident(*code).get()
+        "__register_diagnostic_".to_string() + &token::get_ident(*code)
     )[]));
     MacItems::new(vec![quote_item!(ecx, mod $sym {}).unwrap()].into_iter())
 }
index 4caef247aebc26f601318c8d4de23ec70cfdfe02..62d48189c43475149b013f223bb2079af97e0199 100644 (file)
@@ -10,6 +10,7 @@
 
 use std::collections::HashMap;
 
+#[derive(Clone)]
 pub struct Registry {
     descriptions: HashMap<&'static str, &'static str>
 }
index 4258eb32fdf0f671b47295596944f12a8f20d567..1ceda2e08dd8219663623d3457689c5ea71114b5 100644 (file)
@@ -102,7 +102,7 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
                     // It's the opposite of '=&' which means that the memory
                     // cannot be shared with any other operand (usually when
                     // a register is clobbered early.)
-                    let output = match constraint.get().slice_shift_char() {
+                    let output = match constraint.slice_shift_char() {
                         Some(('=', _)) => None,
                         Some(('+', operand)) => {
                             Some(token::intern_and_get_ident(&format!(
@@ -129,9 +129,9 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
 
                     let (constraint, _str_style) = p.parse_str();
 
-                    if constraint.get().starts_with("=") {
+                    if constraint.starts_with("=") {
                         cx.span_err(p.last_span, "input operand constraint contains '='");
-                    } else if constraint.get().starts_with("+") {
+                    } else if constraint.starts_with("+") {
                         cx.span_err(p.last_span, "input operand constraint contains '+'");
                     }
 
@@ -213,7 +213,7 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
     MacExpr::new(P(ast::Expr {
         id: ast::DUMMY_NODE_ID,
         node: ast::ExprInlineAsm(ast::InlineAsm {
-            asm: token::intern_and_get_ident(asm.get()),
+            asm: token::intern_and_get_ident(&asm),
             asm_str_style: asm_str_style.unwrap(),
             outputs: outputs,
             inputs: inputs,
index a184cc5c2b296820c3c0fe50772cf6e0bb105cb4..778b2cabea622ef9918c1ce08028ea7151ab4f69 100644 (file)
@@ -544,6 +544,7 @@ pub struct ExtCtxt<'a> {
     pub cfg: ast::CrateConfig,
     pub backtrace: ExpnId,
     pub ecfg: expand::ExpansionConfig,
+    pub use_std: bool,
 
     pub mod_path: Vec<ast::Ident> ,
     pub trace_mac: bool,
@@ -563,6 +564,7 @@ pub fn new(parse_sess: &'a parse::ParseSess, cfg: ast::CrateConfig,
             backtrace: NO_EXPANSION,
             mod_path: Vec::new(),
             ecfg: ecfg,
+            use_std: true,
             trace_mac: false,
             exported_macros: Vec::new(),
             syntax_env: env,
@@ -737,6 +739,9 @@ pub fn set_trace_macros(&mut self, x: bool) {
     pub fn ident_of(&self, st: &str) -> ast::Ident {
         str_to_ident(st)
     }
+    pub fn ident_of_std(&self, st: &str) -> ast::Ident {
+        self.ident_of(if self.use_std { "std" } else { st })
+    }
     pub fn name_of(&self, st: &str) -> ast::Name {
         token::intern(st)
     }
@@ -790,7 +795,7 @@ pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
         cx.span_err(sp, &format!("{} takes 1 argument", name)[]);
     }
     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
-        s.get().to_string()
+        s.to_string()
     })
 }
 
index 53c35ef34cd0d4293ed2803b08a26af76a62f710..6d9a2fdb9f19814092c4173be5ace28cebccb8d0 100644 (file)
@@ -21,7 +21,6 @@
 use parse::token;
 use ptr::P;
 
-
 // Transitional reexports so qquote can find the paths it is looking for
 mod syntax {
     pub use ext;
@@ -71,7 +70,7 @@ fn typaram(&self,
                default: Option<P<ast::Ty>>) -> ast::TyParam;
 
     fn trait_ref(&self, path: ast::Path) -> ast::TraitRef;
-    fn poly_trait_ref(&self, path: ast::Path) -> ast::PolyTraitRef;
+    fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef;
     fn typarambound(&self, path: ast::Path) -> ast::TyParamBound;
     fn lifetime(&self, span: Span, ident: ast::Name) -> ast::Lifetime;
     fn lifetime_def(&self,
@@ -387,7 +386,7 @@ fn ty_option(&self, ty: P<ast::Ty>) -> P<ast::Ty> {
             self.path_all(DUMMY_SP,
                           true,
                           vec!(
-                              self.ident_of("std"),
+                              self.ident_of_std("core"),
                               self.ident_of("option"),
                               self.ident_of("Option")
                           ),
@@ -443,15 +442,16 @@ fn trait_ref(&self, path: ast::Path) -> ast::TraitRef {
         }
     }
 
-    fn poly_trait_ref(&self, path: ast::Path) -> ast::PolyTraitRef {
+    fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef {
         ast::PolyTraitRef {
             bound_lifetimes: Vec::new(),
-            trait_ref: self.trait_ref(path)
+            trait_ref: self.trait_ref(path),
+            span: span,
         }
     }
 
     fn typarambound(&self, path: ast::Path) -> ast::TyParamBound {
-        ast::TraitTyParamBound(self.poly_trait_ref(path), ast::TraitBoundModifier::None)
+        ast::TraitTyParamBound(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None)
     }
 
     fn lifetime(&self, span: Span, name: ast::Name) -> ast::Lifetime {
@@ -576,7 +576,7 @@ fn expr_unary(&self, sp: Span, op: ast::UnOp, e: P<ast::Expr>) -> P<ast::Expr> {
     fn expr_field_access(&self, sp: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr> {
         let field_name = token::get_ident(ident);
         let field_span = Span {
-            lo: sp.lo - Pos::from_usize(field_name.get().len()),
+            lo: sp.lo - Pos::from_usize(field_name.len()),
             hi: sp.hi,
             expn_id: sp.expn_id,
         };
@@ -657,7 +657,7 @@ fn expr_vec(&self, sp: Span, exprs: Vec<P<ast::Expr>>) -> P<ast::Expr> {
     }
     fn expr_vec_ng(&self, sp: Span) -> P<ast::Expr> {
         self.expr_call_global(sp,
-                              vec!(self.ident_of("std"),
+                              vec!(self.ident_of_std("collections"),
                                    self.ident_of("vec"),
                                    self.ident_of("Vec"),
                                    self.ident_of("new")),
@@ -677,7 +677,7 @@ fn expr_cast(&self, sp: Span, expr: P<ast::Expr>, ty: P<ast::Ty>) -> P<ast::Expr
 
     fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
         let some = vec!(
-            self.ident_of("std"),
+            self.ident_of_std("core"),
             self.ident_of("option"),
             self.ident_of("Option"),
             self.ident_of("Some"));
@@ -686,7 +686,7 @@ fn expr_some(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
 
     fn expr_none(&self, sp: Span) -> P<ast::Expr> {
         let none = self.path_global(sp, vec!(
-            self.ident_of("std"),
+            self.ident_of_std("core"),
             self.ident_of("option"),
             self.ident_of("Option"),
             self.ident_of("None")));
@@ -713,7 +713,7 @@ fn expr_fail(&self, span: Span, msg: InternedString) -> P<ast::Expr> {
         self.expr_call_global(
             span,
             vec!(
-                self.ident_of("std"),
+                self.ident_of_std("core"),
                 self.ident_of("rt"),
                 self.ident_of("begin_unwind")),
             vec!(
@@ -729,7 +729,7 @@ fn expr_unreachable(&self, span: Span) -> P<ast::Expr> {
 
     fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
         let ok = vec!(
-            self.ident_of("std"),
+            self.ident_of_std("core"),
             self.ident_of("result"),
             self.ident_of("Result"),
             self.ident_of("Ok"));
@@ -738,7 +738,7 @@ fn expr_ok(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
 
     fn expr_err(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
         let err = vec!(
-            self.ident_of("std"),
+            self.ident_of_std("core"),
             self.ident_of("result"),
             self.ident_of("Result"),
             self.ident_of("Err"));
@@ -746,10 +746,20 @@ fn expr_err(&self, sp: Span, expr: P<ast::Expr>) -> P<ast::Expr> {
     }
 
     fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> {
-        let ok = self.ident_of("Ok");
-        let ok_path = self.path_ident(sp, ok);
-        let err = self.ident_of("Err");
-        let err_path = self.path_ident(sp, err);
+        let ok = vec![
+            self.ident_of_std("core"),
+            self.ident_of("result"),
+            self.ident_of("Result"),
+            self.ident_of("Ok")
+        ];
+        let ok_path = self.path_global(sp, ok);
+        let err = vec![
+            self.ident_of_std("core"),
+            self.ident_of("result"),
+            self.ident_of("Result"),
+            self.ident_of("Err")
+        ];
+        let err_path = self.path_global(sp, err);
 
         let binding_variable = self.ident_of("__try_var");
         let binding_pat = self.pat_ident(sp, binding_variable);
@@ -759,8 +769,9 @@ fn expr_try(&self, sp: Span, head: P<ast::Expr>) -> P<ast::Expr> {
         let ok_pat = self.pat_enum(sp, ok_path, vec!(binding_pat.clone()));
 
         // Err(__try_var)  (pattern and expression resp.)
-        let err_pat = self.pat_enum(sp, err_path, vec!(binding_pat));
-        let err_inner_expr = self.expr_call_ident(sp, err, vec!(binding_expr.clone()));
+        let err_pat = self.pat_enum(sp, err_path.clone(), vec!(binding_pat));
+        let err_inner_expr = self.expr_call(sp, self.expr_path(err_path),
+                                            vec!(binding_expr.clone()));
         // return Err(__try_var)
         let err_expr = self.expr(sp, ast::ExprRet(Some(err_inner_expr)));
 
@@ -809,7 +820,7 @@ fn pat_tuple(&self, span: Span, pats: Vec<P<ast::Pat>>) -> P<ast::Pat> {
 
     fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
         let some = vec!(
-            self.ident_of("std"),
+            self.ident_of_std("core"),
             self.ident_of("option"),
             self.ident_of("Option"),
             self.ident_of("Some"));
@@ -819,7 +830,7 @@ fn pat_some(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
 
     fn pat_none(&self, span: Span) -> P<ast::Pat> {
         let some = vec!(
-            self.ident_of("std"),
+            self.ident_of_std("core"),
             self.ident_of("option"),
             self.ident_of("Option"),
             self.ident_of("None"));
@@ -829,7 +840,7 @@ fn pat_none(&self, span: Span) -> P<ast::Pat> {
 
     fn pat_ok(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
         let some = vec!(
-            self.ident_of("std"),
+            self.ident_of_std("core"),
             self.ident_of("result"),
             self.ident_of("Result"),
             self.ident_of("Ok"));
@@ -839,7 +850,7 @@ fn pat_ok(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
 
     fn pat_err(&self, span: Span, pat: P<ast::Pat>) -> P<ast::Pat> {
         let some = vec!(
-            self.ident_of("std"),
+            self.ident_of_std("core"),
             self.ident_of("result"),
             self.ident_of("Result"),
             self.ident_of("Err"));
index 72da60ffe0941f827a97fb6723de25ddf27fc1b3..7216602071b5c694a65cc88ee2759d0372bc7721 100644 (file)
@@ -34,6 +34,6 @@ pub fn expand_cfg<'cx>(cx: &mut ExtCtxt,
         return DummyResult::expr(sp);
     }
 
-    let matches_cfg = attr::cfg_matches(&cx.parse_sess.span_diagnostic, cx.cfg.as_slice(), &*cfg);
+    let matches_cfg = attr::cfg_matches(&cx.parse_sess.span_diagnostic, &cx.cfg, &*cfg);
     MacExpr::new(cx.expr_bool(sp, matches_cfg))
 }
index a85f12edb228648c672be37ff972662a45d890b9..72eaa3e47bec6cda739043cacdd1c9b6e2a8c709 100644 (file)
@@ -25,7 +25,7 @@ pub fn expand(cx: &mut ExtCtxt, sp: Span, mi: &ast::MetaItem, it: P<ast::Item>)
     };
 
     let mut out = (*it).clone();
-    if attr::cfg_matches(&cx.parse_sess.span_diagnostic, cx.cfg.as_slice(), &**cfg) {
+    if attr::cfg_matches(&cx.parse_sess.span_diagnostic, &cx.cfg, &**cfg) {
         out.attrs.push(cx.attribute(attr.span, attr.clone()));
     }
 
index 4e10cc9aacc08cf1e625f3b10e890d5153fb165f..80d128959eaf3a652632f6748fdddb330a68a4cb 100644 (file)
@@ -32,7 +32,7 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt,
                     ast::LitStr(ref s, _) |
                     ast::LitFloat(ref s, _) |
                     ast::LitFloatUnsuffixed(ref s) => {
-                        accumulator.push_str(s.get());
+                        accumulator.push_str(&s);
                     }
                     ast::LitChar(c) => {
                         accumulator.push(c);
index 1af3ba1d326bc7ae062f565a38ea91e58b83a60b..364cacd735cc73386c45e4ea0e540f277914f795 100644 (file)
@@ -31,7 +31,7 @@ pub fn expand_syntax_ext<'cx>(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]
         } else {
             match *e {
                 ast::TtToken(_, token::Ident(ident, _)) => {
-                    res_str.push_str(token::get_ident(ident).get())
+                    res_str.push_str(&token::get_ident(ident))
                 },
                 _ => {
                     cx.span_err(sp, "concat_idents! requires ident args.");
index 9c85d3d28a7a0039d5b34ade26d4d773a2f11f67..879718a6399f5b21f2e3bb024b35527bd1aa7752 100644 (file)
@@ -24,18 +24,18 @@ pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt,
 {
     let name = match mitem.node {
         MetaWord(ref tname) => {
-            match tname.get() {
+            match &tname[] {
                 "Copy" => "Copy",
                 "Send" | "Sync" => {
                     return cx.span_err(span,
-                                       format!("{} is an unsafe trait and it \
-                                                should be implemented explicitly",
-                                               *tname).as_slice())
+                                       &format!("{} is an unsafe trait and it \
+                                                 should be implemented explicitly",
+                                                *tname))
                 }
                 ref tname => {
                     cx.span_bug(span,
-                                format!("expected built-in trait name but \
-                                         found {}", *tname).as_slice())
+                                &format!("expected built-in trait name but \
+                                          found {}", *tname))
                 }
             }
         },
@@ -45,10 +45,16 @@ pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt,
         }
     };
 
+    let path = Path::new(vec![
+        if cx.use_std { "std" } else { "core" },
+        "marker",
+        name
+    ]);
+
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "marker", name)),
+        path: path,
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: Vec::new(),
index e1dcc887778231d1b8f557b59caa4d424faafc9e..9f009ad4d7869ed6e6721eb46bb70b8730fe8c90 100644 (file)
@@ -29,7 +29,7 @@ pub fn expand_deriving_clone<F>(cx: &mut ExtCtxt,
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "clone", "Clone")),
+        path: path_std!(cx, core::clone::Clone),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
@@ -58,12 +58,12 @@ fn cs_clone(
     let ctor_path;
     let all_fields;
     let fn_path = vec![
-        cx.ident_of("std"),
+        cx.ident_of_std("core"),
         cx.ident_of("clone"),
         cx.ident_of("Clone"),
         cx.ident_of("clone"),
     ];
-    let subcall = |&: field: &FieldInfo| {
+    let subcall = |field: &FieldInfo| {
         let args = vec![cx.expr_addr_of(field.span, field.self_.clone())];
 
         cx.expr_call_global(field.span, fn_path.clone(), args)
index 00971b96e9288759ec9dcdaea150112d278fc772..91212a86958962d08c71761b30545ea7432e15f5 100644 (file)
@@ -70,7 +70,7 @@ macro_rules! md {
                 generics: LifetimeBounds::empty(),
                 explicit_self: borrowed_explicit_self(),
                 args: vec!(borrowed_self()),
-                ret_ty: Literal(Path::new(vec!("bool"))),
+                ret_ty: Literal(path!(bool)),
                 attributes: attrs,
                 combine_substructure: combine_substructure(box |a, b, c| {
                     $f(a, b, c)
@@ -82,7 +82,7 @@ macro_rules! md {
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "cmp", "PartialEq")),
+        path: path_std!(cx, core::cmp::PartialEq),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
index 1f92f8d7b372a3ac92738b41fcfda4de05ac94e8..b109850a6bd23dac42f217f7e4b742bb527dcc7c 100644 (file)
@@ -36,7 +36,7 @@ macro_rules! md {
                 generics: LifetimeBounds::empty(),
                 explicit_self: borrowed_explicit_self(),
                 args: vec!(borrowed_self()),
-                ret_ty: Literal(Path::new(vec!("bool"))),
+                ret_ty: Literal(path!(bool)),
                 attributes: attrs,
                 combine_substructure: combine_substructure(box |cx, span, substr| {
                     cs_op($op, $equal, cx, span, substr)
@@ -45,8 +45,8 @@ macro_rules! md {
         } }
     }
 
-    let ordering_ty = Literal(Path::new(vec!["std", "cmp", "Ordering"]));
-    let ret_ty = Literal(Path::new_(vec!["std", "option", "Option"],
+    let ordering_ty = Literal(path_std!(cx, core::cmp::Ordering));
+    let ret_ty = Literal(Path::new_(pathvec_std!(cx, core::option::Option),
                                     None,
                                     vec![box ordering_ty],
                                     true));
@@ -69,7 +69,7 @@ macro_rules! md {
     let trait_def = TraitDef {
         span: span,
         attributes: vec![],
-        path: Path::new(vec!["std", "cmp", "PartialOrd"]),
+        path: path_std!(cx, core::cmp::PartialOrd),
         additional_bounds: vec![],
         generics: LifetimeBounds::empty(),
         methods: vec![
@@ -107,7 +107,7 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span,
               substr: &Substructure) -> P<Expr> {
     let test_id = cx.ident_of("__test");
     let ordering = cx.path_global(span,
-                                  vec!(cx.ident_of("std"),
+                                  vec!(cx.ident_of_std("core"),
                                        cx.ident_of("cmp"),
                                        cx.ident_of("Ordering"),
                                        cx.ident_of("Equal")));
@@ -115,7 +115,7 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span,
     let equals_expr = cx.expr_some(span, ordering);
 
     let partial_cmp_path = vec![
-        cx.ident_of("std"),
+        cx.ident_of_std("core"),
         cx.ident_of("cmp"),
         cx.ident_of("PartialOrd"),
         cx.ident_of("partial_cmp"),
index 0429db3643bb1a335279fb04c181668906bd04e2..31a754a1254bb486c88936b9674afe9c3d31f7c3 100644 (file)
@@ -46,7 +46,7 @@ fn cs_total_eq_assert(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "cmp", "Eq")),
+        path: path_std!(cx, core::cmp::Eq),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
index e90c1aa6fcee8254a18eea0a04520f8db653380b..2f6f99bc1ee46211bf4959321e2b09ff43d064db 100644 (file)
@@ -30,7 +30,7 @@ pub fn expand_deriving_totalord<F>(cx: &mut ExtCtxt,
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "cmp", "Ord")),
+        path: path_std!(cx, core::cmp::Ord),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
@@ -39,7 +39,7 @@ pub fn expand_deriving_totalord<F>(cx: &mut ExtCtxt,
                 generics: LifetimeBounds::empty(),
                 explicit_self: borrowed_explicit_self(),
                 args: vec!(borrowed_self()),
-                ret_ty: Literal(Path::new(vec!("std", "cmp", "Ordering"))),
+                ret_ty: Literal(path_std!(cx, core::cmp::Ordering)),
                 attributes: attrs,
                 combine_substructure: combine_substructure(box |a, b, c| {
                     cs_cmp(a, b, c)
@@ -65,13 +65,13 @@ pub fn cs_cmp(cx: &mut ExtCtxt, span: Span,
               substr: &Substructure) -> P<Expr> {
     let test_id = cx.ident_of("__test");
     let equals_path = cx.path_global(span,
-                                     vec!(cx.ident_of("std"),
+                                     vec!(cx.ident_of_std("core"),
                                           cx.ident_of("cmp"),
                                           cx.ident_of("Ordering"),
                                           cx.ident_of("Equal")));
 
     let cmp_path = vec![
-        cx.ident_of("std"),
+        cx.ident_of_std("core"),
         cx.ident_of("cmp"),
         cx.ident_of("Ord"),
         cx.ident_of("cmp"),
index 9552dff941d273d1a55ac99e8c96091d186dd7b1..f003a3453e15e578ba88034727b75d4c5654a593 100644 (file)
@@ -49,6 +49,12 @@ fn expand_deriving_decodable_imp<F>(cx: &mut ExtCtxt,
                                     krate: &'static str) where
     F: FnOnce(P<Item>),
 {
+    if !cx.use_std {
+        // FIXME(#21880): lift this requirement.
+        cx.span_err(span, "this trait cannot be derived with #![no_std]");
+        return;
+    }
+
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
@@ -68,7 +74,7 @@ fn expand_deriving_decodable_imp<F>(cx: &mut ExtCtxt,
                 args: vec!(Ptr(box Literal(Path::new_local("__D")),
                             Borrowed(None, MutMutable))),
                 ret_ty: Literal(Path::new_(
-                    vec!("std", "result", "Result"),
+                    pathvec_std!(cx, core::result::Result),
                     None,
                     vec!(box Self, box Literal(Path::new_(
                         vec!["__D", "Error"], None, vec![], false
index 27f3c46c48fceaf3edb4f6ccac496773ac2fc00f..9b76f4b1658f0d47edfb82fadaaf0a32a8c4f735 100644 (file)
@@ -29,7 +29,7 @@ pub fn expand_deriving_default<F>(cx: &mut ExtCtxt,
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "default", "Default")),
+        path: path_std!(cx, core::default::Default),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
@@ -52,12 +52,12 @@ pub fn expand_deriving_default<F>(cx: &mut ExtCtxt,
 
 fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
     let default_ident = vec!(
-        cx.ident_of("std"),
+        cx.ident_of_std("core"),
         cx.ident_of("default"),
         cx.ident_of("Default"),
         cx.ident_of("default")
     );
-    let default_call = |&: span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
+    let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
 
     return match *substr.fields {
         StaticStruct(_, ref summary) => {
index d0b2c2faf3719e2a3a70f921abd0fb0ee0970425..dd6094705995e94a4b70818984235fb81c0dad3b 100644 (file)
@@ -125,6 +125,12 @@ fn expand_deriving_encodable_imp<F>(cx: &mut ExtCtxt,
                                     krate: &'static str) where
     F: FnOnce(P<Item>),
 {
+    if !cx.use_std {
+        // FIXME(#21880): lift this requirement.
+        cx.span_err(span, "this trait cannot be derived with #![no_std]");
+        return;
+    }
+
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
@@ -144,7 +150,7 @@ fn expand_deriving_encodable_imp<F>(cx: &mut ExtCtxt,
                 args: vec!(Ptr(box Literal(Path::new_local("__S")),
                             Borrowed(None, MutMutable))),
                 ret_ty: Literal(Path::new_(
-                    vec!("std", "result", "Result"),
+                    pathvec_std!(cx, core::result::Result),
                     None,
                     vec!(box Tuple(Vec::new()), box Literal(Path::new_(
                         vec!["__S", "Error"], None, vec![], false
index 02982039be0a3bf5a9ed8921bb1407d32d91c205..d9242417e047511fc4cd982a4869e01d86f75a48 100644 (file)
@@ -363,7 +363,7 @@ pub fn expand<F>(&self,
         // generated implementations are linted
         let mut attrs = newitem.attrs.clone();
         attrs.extend(item.attrs.iter().filter(|a| {
-            match a.name().get() {
+            match &a.name()[] {
                 "allow" | "warn" | "deny" | "forbid" => true,
                 _ => false,
             }
@@ -443,6 +443,7 @@ fn create_derived_impl(&self,
                 ast::WherePredicate::BoundPredicate(ref wb) => {
                     ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
                         span: self.span,
+                        bound_lifetimes: wb.bound_lifetimes.clone(),
                         bounded_ty: wb.bounded_ty.clone(),
                         bounds: OwnedSlice::from_vec(wb.bounds.iter().map(|b| b.clone()).collect())
                     })
@@ -957,7 +958,7 @@ fn build_enum_match_tuple(
         // where each tuple has length = self_args.len()
         let mut match_arms: Vec<ast::Arm> = variants.iter().enumerate()
             .map(|(index, variant)| {
-                let mk_self_pat = |&: cx: &mut ExtCtxt, self_arg_name: &str| {
+                let mk_self_pat = |cx: &mut ExtCtxt, self_arg_name: &str| {
                     let (p, idents) = trait_.create_enum_variant_pattern(cx, type_ident,
                                                                          &**variant,
                                                                          self_arg_name,
index 85682d41b5ff65cffcdb971ca178d9d9d10c244e..bbca5c599b1c1199d12695cf1bcea9a61954ebb7 100644 (file)
@@ -247,7 +247,7 @@ pub fn to_generics(&self,
                     mk_ty_param(cx,
                                 span,
                                 *name,
-                                bounds.as_slice(),
+                                bounds,
                                 self_ty,
                                 self_generics)
                 }
index efd9322661862b480226e6c9abb66ff95e1b2a5a..5aa9f9a0c3e761f163b476caeeabd61a5f4cc588 100644 (file)
@@ -25,13 +25,13 @@ pub fn expand_deriving_hash<F>(cx: &mut ExtCtxt,
     F: FnOnce(P<Item>),
 {
 
-    let path = Path::new_(vec!("std", "hash", "Hash"), None,
+    let path = Path::new_(pathvec_std!(cx, core::hash::Hash), None,
                           vec!(box Literal(Path::new_local("__S"))), true);
     let generics = LifetimeBounds {
         lifetimes: Vec::new(),
         bounds: vec!(("__S",
-                      vec!(Path::new(vec!("std", "hash", "Writer")),
-                           Path::new(vec!("std", "hash", "Hasher"))))),
+                      vec!(path_std!(cx, core::hash::Writer),
+                           path_std!(cx, core::hash::Hasher)))),
     };
     let args = Path::new_local("__S");
     let inline = cx.meta_word(span, InternedString::new("inline"));
@@ -66,10 +66,10 @@ fn hash_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure)
         [ref state_expr] => state_expr,
         _ => cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`")
     };
-    let call_hash = |&: span, thing_expr| {
+    let call_hash = |span, thing_expr| {
         let hash_path = {
             let strs = vec![
-                cx.ident_of("std"),
+                cx.ident_of_std("core"),
                 cx.ident_of("hash"),
                 cx.ident_of("Hash"),
                 cx.ident_of("hash"),
index d3d7fee3a189a19a578835ce1712b5b888c8d600..9c3fa58ad0960b825d445a1968778741b33fa204 100644 (file)
 use codemap::Span;
 use ptr::P;
 
+macro_rules! pathvec {
+    ($($x:ident)::+) => (
+        vec![ $( stringify!($x) ),+ ]
+    )
+}
+
+macro_rules! path {
+    ($($x:tt)*) => (
+        ::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
+    )
+}
+
+macro_rules! pathvec_std {
+    ($cx:expr, $first:ident :: $($rest:ident)::+) => (
+        if $cx.use_std {
+            pathvec!(std :: $($rest)::+)
+        } else {
+            pathvec!($first :: $($rest)::+)
+        }
+    )
+}
+
+macro_rules! path_std {
+    ($($x:tt)*) => (
+        ::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
+    )
+}
+
 pub mod bounds;
 pub mod clone;
 pub mod encodable;
@@ -74,7 +102,7 @@ macro_rules! expand {
                                                    |i| push(i)))
                         }
 
-                        match tname.get() {
+                        match &tname[] {
                             "Clone" => expand!(clone::expand_deriving_clone),
 
                             "Hash" => expand!(hash::expand_deriving_hash),
index ae7b20f7853fb0bd52f2f1f30142e02c81d848d6..bf742263c6d8774561efae0158c53a59db5755fb 100644 (file)
@@ -30,7 +30,7 @@ pub fn expand_deriving_from_primitive<F>(cx: &mut ExtCtxt,
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "num", "FromPrimitive")),
+        path: path_std!(cx, core::num::FromPrimitive),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
@@ -38,9 +38,8 @@ pub fn expand_deriving_from_primitive<F>(cx: &mut ExtCtxt,
                 name: "from_i64",
                 generics: LifetimeBounds::empty(),
                 explicit_self: None,
-                args: vec!(
-                    Literal(Path::new(vec!("i64")))),
-                ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
+                args: vec!(Literal(path!(i64))),
+                ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
                                            None,
                                            vec!(box Self),
                                            true)),
@@ -54,9 +53,8 @@ pub fn expand_deriving_from_primitive<F>(cx: &mut ExtCtxt,
                 name: "from_u64",
                 generics: LifetimeBounds::empty(),
                 explicit_self: None,
-                args: vec!(
-                    Literal(Path::new(vec!("u64")))),
-                ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
+                args: vec!(Literal(path!(u64))),
+                ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
                                            None,
                                            vec!(box Self),
                                            true)),
index 0b57e7e7c8e9e63a38a1855fe3fa8caaa040ab5c..4c3678d9572da8a91e80a9154c155d2357f2f6a4 100644 (file)
@@ -28,10 +28,16 @@ pub fn expand_deriving_rand<F>(cx: &mut ExtCtxt,
                  "`#[derive(Rand)]` is deprecated in favour of `#[derive_Rand]` from \
                   `rand_macros` on crates.io");
 
+    if !cx.use_std {
+        // FIXME(#21880): lift this requirement.
+        cx.span_err(span, "this trait cannot be derived with #![no_std]");
+        return;
+    }
+
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!("std", "rand", "Rand")),
+        path: path!(std::rand::Rand),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec!(
@@ -40,7 +46,7 @@ pub fn expand_deriving_rand<F>(cx: &mut ExtCtxt,
                 generics: LifetimeBounds {
                     lifetimes: Vec::new(),
                     bounds: vec!(("R",
-                                  vec!( Path::new(vec!("std", "rand", "Rng")) )))
+                                  vec!( path!(std::rand::Rng) ))),
                 },
                 explicit_self: None,
                 args: vec!(
@@ -70,7 +76,7 @@ fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure)
         cx.ident_of("Rand"),
         cx.ident_of("rand")
     );
-    let rand_call = |&: cx: &mut ExtCtxt, span| {
+    let rand_call = |cx: &mut ExtCtxt, span| {
         cx.expr_call_global(span,
                             rand_ident.clone(),
                             vec!(rng.clone()))
index ec5941f58f3f02c1aaf49b01a8d3ceafd0970689..3f5947672e022ce67971f031b5e88827b701882b 100644 (file)
@@ -29,13 +29,13 @@ pub fn expand_deriving_show<F>(cx: &mut ExtCtxt,
     F: FnOnce(P<Item>),
 {
     // &mut ::std::fmt::Formatter
-    let fmtr = Ptr(box Literal(Path::new(vec!("std", "fmt", "Formatter"))),
+    let fmtr = Ptr(box Literal(path_std!(cx, core::fmt::Formatter)),
                    Borrowed(None, ast::MutMutable));
 
     let trait_def = TraitDef {
         span: span,
         attributes: Vec::new(),
-        path: Path::new(vec!["std", "fmt", "Debug"]),
+        path: path_std!(cx, core::fmt::Debug),
         additional_bounds: Vec::new(),
         generics: LifetimeBounds::empty(),
         methods: vec![
@@ -44,7 +44,7 @@ pub fn expand_deriving_show<F>(cx: &mut ExtCtxt,
                 generics: LifetimeBounds::empty(),
                 explicit_self: borrowed_explicit_self(),
                 args: vec!(fmtr),
-                ret_ty: Literal(Path::new(vec!("std", "fmt", "Result"))),
+                ret_ty: Literal(path_std!(cx, core::fmt::Result)),
                 attributes: Vec::new(),
                 combine_substructure: combine_substructure(box |a, b, c| {
                     show_substructure(a, b, c)
@@ -72,7 +72,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span,
         }
     };
 
-    let mut format_string = String::from_str(token::get_ident(name).get());
+    let mut format_string = String::from_str(&token::get_ident(name));
     // the internal fields we're actually formatting
     let mut exprs = Vec::new();
 
@@ -107,7 +107,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span,
 
                     let name = token::get_ident(field.name.unwrap());
                     format_string.push_str(" ");
-                    format_string.push_str(name.get());
+                    format_string.push_str(&name);
                     format_string.push_str(": {:?}");
 
                     exprs.push(field.self_.clone());
index 9aa454ae8d5c9c567395e92d4a39c9997be1bb09..ef9d37998793229330fb6074fb8fe7137bc394cc 100644 (file)
@@ -34,7 +34,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT
       Err(..) => {
           cx.expr_path(cx.path_all(sp,
                                    true,
-                                   vec!(cx.ident_of("std"),
+                                   vec!(cx.ident_of_std("core"),
                                         cx.ident_of("option"),
                                         cx.ident_of("Option"),
                                         cx.ident_of("None")),
@@ -50,7 +50,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT
       }
       Ok(s) => {
           cx.expr_call_global(sp,
-                              vec!(cx.ident_of("std"),
+                              vec!(cx.ident_of_std("core"),
                                    cx.ident_of("option"),
                                    cx.ident_of("Option"),
                                    cx.ident_of("Some")),
@@ -101,12 +101,12 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
         }
     }
 
-    let e = match env::var_string(var.get()) {
-        Err(..) => {
-            cx.span_err(sp, msg.get());
+    let e = match env::var_string(&var[]) {
+        Err(_) => {
+            cx.span_err(sp, &msg);
             cx.expr_usize(sp, 0)
         }
-        Ok(s) => cx.expr_str(sp, token::intern_and_get_ident(&s[]))
+        Ok(s) => cx.expr_str(sp, token::intern_and_get_ident(&s))
     };
     MacExpr::new(e)
 }
index 77440914342fb2ef4a60710bf3c16376db58934b..fd7593f2a3b52adb4200d227ce604eb5cb18603c 100644 (file)
@@ -31,6 +31,7 @@
 use util::small_vector::SmallVector;
 use visit;
 use visit::Visitor;
+use std_inject;
 
 pub fn expand_type(t: P<ast::Ty>,
                    fld: &mut MacroExpander,
@@ -230,15 +231,18 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
         ast::ExprForLoop(pat, head, body, opt_ident) => {
             // to:
             //
-            //   match ::std::iter::IntoIterator::into_iter(<head>) {
-            //     mut iter => {
-            //       [opt_ident]: loop {
-            //         match ::std::iter::Iterator::next(&mut iter) {
-            //           ::std::option::Option::Some(<pat>) => <body>,
-            //           ::std::option::Option::None => break
+            //   {
+            //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
+            //       mut iter => {
+            //         [opt_ident]: loop {
+            //           match ::std::iter::Iterator::next(&mut iter) {
+            //             ::std::option::Option::Some(<pat>) => <body>,
+            //             ::std::option::Option::None => break
+            //           }
             //         }
             //       }
-            //     }
+            //     };
+            //     result
             //   }
 
             // expand <head>
@@ -275,7 +279,7 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
             let match_expr = {
                 let next_path = {
                     let strs = vec![
-                        fld.cx.ident_of("std"),
+                        fld.cx.ident_of_std("core"),
                         fld.cx.ident_of("iter"),
                         fld.cx.ident_of("Iterator"),
                         fld.cx.ident_of("next"),
@@ -308,7 +312,7 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
             let into_iter_expr = {
                 let into_iter_path = {
                     let strs = vec![
-                        fld.cx.ident_of("std"),
+                        fld.cx.ident_of_std("core"),
                         fld.cx.ident_of("iter"),
                         fld.cx.ident_of("IntoIterator"),
                         fld.cx.ident_of("into_iter"),
@@ -319,7 +323,16 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
 
                 fld.cx.expr_call(span, fld.cx.expr_path(into_iter_path), vec![head])
             };
-            fld.cx.expr_match(span, into_iter_expr, vec![iter_arm])
+
+            let match_expr = fld.cx.expr_match(span, into_iter_expr, vec![iter_arm]);
+
+            // `{ let result = ...; result }`
+            let result_ident = token::gensym_ident("result");
+            fld.cx.expr_block(
+                fld.cx.block_all(
+                    span,
+                    vec![fld.cx.stmt_let(span, false, result_ident, match_expr)],
+                    Some(fld.cx.expr_ident(span, result_ident))))
         }
 
         ast::ExprClosure(capture_clause, fn_decl, block) => {
@@ -375,7 +388,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span,
                     fld.cx.span_err(
                         pth.span,
                         &format!("macro undefined: '{}!'",
-                                extnamestr.get())[]);
+                                &extnamestr)[]);
 
                     // let compilation continue
                     None
@@ -385,7 +398,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span,
                         fld.cx.bt_push(ExpnInfo {
                                 call_site: span,
                                 callee: NameAndSpan {
-                                    name: extnamestr.get().to_string(),
+                                    name: extnamestr.to_string(),
                                     format: MacroBang,
                                     span: exp_span,
                                 },
@@ -411,7 +424,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span,
                                 fld.cx.span_err(
                                     pth.span,
                                     &format!("non-expression macro in expression position: {}",
-                                            &extnamestr.get()[]
+                                            &extnamestr[]
                                             )[]);
                                 return None;
                             }
@@ -422,7 +435,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span,
                         fld.cx.span_err(
                             pth.span,
                             &format!("'{}' is not a tt-style macro",
-                                    extnamestr.get())[]);
+                                    &extnamestr)[]);
                         None
                     }
                 }
@@ -506,14 +519,14 @@ fn expand_item_modifiers(mut it: P<ast::Item>, fld: &mut MacroExpander)
     for attr in &modifiers {
         let mname = attr.name();
 
-        match fld.cx.syntax_env.find(&intern(mname.get())) {
+        match fld.cx.syntax_env.find(&intern(&mname)) {
             Some(rc) => match *rc {
                 Modifier(ref mac) => {
                     attr::mark_used(attr);
                     fld.cx.bt_push(ExpnInfo {
                         call_site: attr.span,
                         callee: NameAndSpan {
-                            name: mname.get().to_string(),
+                            name: mname.to_string(),
                             format: MacroAttribute,
                             span: None,
                         }
@@ -613,7 +626,7 @@ pub fn expand_item_mac(it: P<ast::Item>,
                     fld.cx.bt_push(ExpnInfo {
                         call_site: it.span,
                         callee: NameAndSpan {
-                            name: extnamestr.get().to_string(),
+                            name: extnamestr.to_string(),
                             format: MacroBang,
                             span: span
                         }
@@ -626,13 +639,13 @@ pub fn expand_item_mac(it: P<ast::Item>,
                     if it.ident.name == parse::token::special_idents::invalid.name {
                         fld.cx.span_err(path_span,
                                         &format!("macro {}! expects an ident argument",
-                                                extnamestr.get())[]);
+                                                &extnamestr)[]);
                         return SmallVector::zero();
                     }
                     fld.cx.bt_push(ExpnInfo {
                         call_site: it.span,
                         callee: NameAndSpan {
-                            name: extnamestr.get().to_string(),
+                            name: extnamestr.to_string(),
                             format: MacroBang,
                             span: span
                         }
@@ -651,7 +664,7 @@ pub fn expand_item_mac(it: P<ast::Item>,
                     fld.cx.bt_push(ExpnInfo {
                         call_site: it.span,
                         callee: NameAndSpan {
-                            name: extnamestr.get().to_string(),
+                            name: extnamestr.to_string(),
                             format: MacroBang,
                             span: None,
                         }
@@ -664,7 +677,7 @@ pub fn expand_item_mac(it: P<ast::Item>,
                         id: ast::DUMMY_NODE_ID,
                         span: it.span,
                         imported_from: None,
-                        export: attr::contains_name(it.attrs.as_slice(), "macro_export"),
+                        export: attr::contains_name(&it.attrs, "macro_export"),
                         use_locally: true,
                         body: tts,
                     };
@@ -677,7 +690,7 @@ pub fn expand_item_mac(it: P<ast::Item>,
                 _ => {
                     fld.cx.span_err(it.span,
                                     &format!("{}! is not legal in item position",
-                                            extnamestr.get())[]);
+                                            &extnamestr)[]);
                     return SmallVector::zero();
                 }
             }
@@ -696,7 +709,7 @@ pub fn expand_item_mac(it: P<ast::Item>,
         None => {
             fld.cx.span_err(path_span,
                             &format!("non-item macro in item position: {}",
-                                    extnamestr.get())[]);
+                                    &extnamestr)[]);
             return SmallVector::zero();
         }
     };
@@ -950,7 +963,7 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> {
                     fld.cx.bt_push(ExpnInfo {
                         call_site: span,
                         callee: NameAndSpan {
-                            name: extnamestr.get().to_string(),
+                            name: extnamestr.to_string(),
                             format: MacroBang,
                             span: tt_span
                         }
@@ -968,7 +981,7 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> {
                                 pth.span,
                                 &format!(
                                     "non-pattern macro in pattern position: {}",
-                                    extnamestr.get()
+                                    &extnamestr
                                     )[]
                             );
                             return DummyResult::raw_pat(span);
@@ -981,7 +994,7 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> {
                 _ => {
                     fld.cx.span_err(span,
                                     &format!("{}! is not legal in pattern position",
-                                            extnamestr.get())[]);
+                                            &extnamestr)[]);
                     return DummyResult::raw_pat(span);
                 }
             }
@@ -1065,7 +1078,7 @@ fn expand_annotatable(a: Annotatable,
     for attr in a.attrs() {
         let mname = attr.name();
 
-        match fld.cx.syntax_env.find(&intern(mname.get())) {
+        match fld.cx.syntax_env.find(&intern(&mname)) {
             Some(rc) => match *rc {
                 Decorator(ref dec) => {
                     let it = match a {
@@ -1079,7 +1092,7 @@ fn expand_annotatable(a: Annotatable,
                     fld.cx.bt_push(ExpnInfo {
                         call_site: attr.span,
                         callee: NameAndSpan {
-                            name: mname.get().to_string(),
+                            name: mname.to_string(),
                             format: MacroAttribute,
                             span: None
                         }
@@ -1089,7 +1102,7 @@ fn expand_annotatable(a: Annotatable,
                     // but that double-mut-borrows fld
                     let mut items: SmallVector<P<ast::Item>> = SmallVector::zero();
                     dec.expand(fld.cx, attr.span, &*attr.node.value, &**it,
-                               box |&mut: item| items.push(item));
+                               box |item| items.push(item));
                     decorator_items.extend(items.into_iter()
                         .flat_map(|item| expand_item(item, fld).into_iter()));
 
@@ -1180,7 +1193,7 @@ fn modifiers(attrs: &Vec<ast::Attribute>,
              fld: &MacroExpander)
              -> (Vec<ast::Attribute>, Vec<ast::Attribute>) {
     attrs.iter().cloned().partition(|attr| {
-        match fld.cx.syntax_env.find(&intern(attr.name().get())) {
+        match fld.cx.syntax_env.find(&intern(&attr.name())) {
             Some(rc) => match *rc {
                 Modifier(_) => true,
                 _ => false
@@ -1195,7 +1208,7 @@ fn multi_modifiers(attrs: &[ast::Attribute],
                    fld: &MacroExpander)
                    -> (Vec<ast::Attribute>, Vec<ast::Attribute>) {
     attrs.iter().cloned().partition(|attr| {
-        match fld.cx.syntax_env.find(&intern(attr.name().get())) {
+        match fld.cx.syntax_env.find(&intern(&attr.name())) {
             Some(rc) => match *rc {
                 MultiModifier(_) => true,
                 _ => false
@@ -1220,14 +1233,14 @@ fn expand_item_multi_modifier(mut it: Annotatable,
     for attr in &modifiers {
         let mname = attr.name();
 
-        match fld.cx.syntax_env.find(&intern(mname.get())) {
+        match fld.cx.syntax_env.find(&intern(&mname)) {
             Some(rc) => match *rc {
                 MultiModifier(ref mac) => {
                     attr::mark_used(attr);
                     fld.cx.bt_push(ExpnInfo {
                         call_site: attr.span,
                         callee: NameAndSpan {
-                            name: mname.get().to_string(),
+                            name: mname.to_string(),
                             format: MacroAttribute,
                             span: None,
                         }
@@ -1417,6 +1430,8 @@ pub fn expand_crate(parse_sess: &parse::ParseSess,
                     user_exts: Vec<NamedSyntaxExtension>,
                     c: Crate) -> Crate {
     let mut cx = ExtCtxt::new(parse_sess, c.config.clone(), cfg);
+    cx.use_std = std_inject::use_std(&c);
+
     let mut expander = MacroExpander::new(&mut cx);
 
     for def in imported_macros {
@@ -1850,7 +1865,7 @@ fn run_renaming_test(t: &RenamingTest, test_idx: usize) {
             assert!((shouldmatch.len() == 0) ||
                     (varrefs.len() > *shouldmatch.iter().max().unwrap()));
             for (idx,varref) in varrefs.iter().enumerate() {
-                let print_hygiene_debug_info = |&:| {
+                let print_hygiene_debug_info = || {
                     // good lord, you can't make a path with 0 segments, can you?
                     let final_varref_ident = match varref.segments.last() {
                         Some(pathsegment) => pathsegment.identifier,
@@ -1862,7 +1877,7 @@ fn run_renaming_test(t: &RenamingTest, test_idx: usize) {
                         .collect();
                     println!("varref #{}: {:?}, resolves to {}",idx, varref_idents, varref_name);
                     let string = token::get_ident(final_varref_ident);
-                    println!("varref's first segment's string: \"{}\"", string.get());
+                    println!("varref's first segment's string: \"{}\"", &string[]);
                     println!("binding #{}: {}, resolves to {}",
                              binding_idx, bindings[binding_idx], binding_name);
                     mtwt::with_sctable(|x| mtwt::display_sctable(x));
@@ -1915,7 +1930,7 @@ fn run_renaming_test(t: &RenamingTest, test_idx: usize) {
         let cxbinds: Vec<&ast::Ident> =
             bindings.iter().filter(|b| {
                 let ident = token::get_ident(**b);
-                let string = ident.get();
+                let string = &ident[];
                 "xx" == string
             }).collect();
         let cxbinds: &[&ast::Ident] = &cxbinds[];
@@ -1929,7 +1944,7 @@ fn run_renaming_test(t: &RenamingTest, test_idx: usize) {
         // the xx binding should bind all of the xx varrefs:
         for (idx,v) in varrefs.iter().filter(|p| {
             p.segments.len() == 1
-            && "xx" == token::get_ident(p.segments[0].identifier).get()
+            && "xx" == &token::get_ident(p.segments[0].identifier)[]
         }).enumerate() {
             if mtwt::resolve(v.segments[0].identifier) != resolved_binding {
                 println!("uh oh, xx binding didn't match xx varref:");
index 16aaccb0207a2d4beed76bc1e2b6a0c07db2d23f..170a455a9132610d3658d0fd3786f6dd0e152222 100644 (file)
@@ -118,7 +118,8 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
                 }
             };
             let interned_name = token::get_ident(ident);
-            let name = interned_name.get();
+            let name = &interned_name[];
+
             p.expect(&token::Eq);
             let e = p.parse_expr();
             match names.get(name) {
@@ -301,13 +302,13 @@ fn verify_same(&self,
     }
 
     fn rtpath(ecx: &ExtCtxt, s: &str) -> Vec<ast::Ident> {
-        vec![ecx.ident_of("std"), ecx.ident_of("fmt"), ecx.ident_of("rt"),
+        vec![ecx.ident_of_std("core"), ecx.ident_of("fmt"), ecx.ident_of("rt"),
              ecx.ident_of("v1"), ecx.ident_of(s)]
     }
 
     fn trans_count(&self, c: parse::Count) -> P<ast::Expr> {
         let sp = self.fmtsp;
-        let count = |c, arg| {
+        let count = |c, arg| {
             let mut path = Context::rtpath(self.ecx, "Count");
             path.push(self.ecx.ident_of(c));
             match arg {
@@ -353,7 +354,7 @@ fn trans_piece(&mut self, piece: &parse::Piece) -> Option<P<ast::Expr>> {
             parse::NextArgument(ref arg) => {
                 // Translate the position
                 let pos = {
-                    let pos = |c, arg| {
+                    let pos = |c, arg| {
                         let mut path = Context::rtpath(self.ecx, "Position");
                         path.push(self.ecx.ident_of(c));
                         match arg {
@@ -404,7 +405,7 @@ fn trans_piece(&mut self, piece: &parse::Piece) -> Option<P<ast::Expr>> {
 
                 // Translate the format
                 let fill = self.ecx.expr_lit(sp, ast::LitChar(fill));
-                let align = |:name| {
+                let align = |name| {
                     let mut p = Context::rtpath(self.ecx, "Alignment");
                     p.push(self.ecx.ident_of(name));
                     self.ecx.path_global(sp, p)
@@ -575,7 +576,7 @@ fn into_expr(mut self) -> P<ast::Expr> {
         };
 
         self.ecx.expr_call_global(self.fmtsp, vec!(
-                self.ecx.ident_of("std"),
+                self.ecx.ident_of_std("core"),
                 self.ecx.ident_of("fmt"),
                 self.ecx.ident_of("Arguments"),
                 self.ecx.ident_of(fn_name)), fn_args)
@@ -606,7 +607,7 @@ fn format_arg(ecx: &ExtCtxt, sp: Span,
             }
             Unsigned => {
                 return ecx.expr_call_global(sp, vec![
-                        ecx.ident_of("std"),
+                        ecx.ident_of_std("core"),
                         ecx.ident_of("fmt"),
                         ecx.ident_of("ArgumentV1"),
                         ecx.ident_of("from_uint")], vec![arg])
@@ -614,12 +615,12 @@ fn format_arg(ecx: &ExtCtxt, sp: Span,
         };
 
         let format_fn = ecx.path_global(sp, vec![
-                ecx.ident_of("std"),
+                ecx.ident_of_std("core"),
                 ecx.ident_of("fmt"),
                 ecx.ident_of(trait_),
                 ecx.ident_of("fmt")]);
         ecx.expr_call_global(sp, vec![
-                ecx.ident_of("std"),
+                ecx.ident_of_std("core"),
                 ecx.ident_of("fmt"),
                 ecx.ident_of("ArgumentV1"),
                 ecx.ident_of("new")], vec![arg, ecx.expr_path(format_fn)])
@@ -672,7 +673,8 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
         None => return DummyResult::raw_expr(sp)
     };
 
-    let mut parser = parse::Parser::new(fmt.get());
+    let mut parser = parse::Parser::new(&fmt);
+
     loop {
         match parser.next() {
             Some(piece) => {
index 9092169e1820067e1f7a4833e6e3b29792639626..67990895d071affa20ed0b129ef4b395e0adc9ec 100644 (file)
@@ -161,7 +161,7 @@ fn to_source_with_hygiene(&self) -> String {
 
     impl ToSource for ast::Ident {
         fn to_source(&self) -> String {
-            token::get_ident(*self).get().to_string()
+            token::get_ident(*self).to_string()
         }
     }
 
@@ -791,11 +791,11 @@ fn expand_parse_call(cx: &ExtCtxt,
                      tts: &[ast::TokenTree]) -> P<ast::Expr> {
     let (cx_expr, tts_expr) = expand_tts(cx, sp, tts);
 
-    let cfg_call = |&:| cx.expr_method_call(
+    let cfg_call = || cx.expr_method_call(
         sp, cx.expr_ident(sp, id_ext("ext_cx")),
         id_ext("cfg"), Vec::new());
 
-    let parse_sess_call = |&:| cx.expr_method_call(
+    let parse_sess_call = || cx.expr_method_call(
         sp, cx.expr_ident(sp, id_ext("ext_cx")),
         id_ext("parse_sess"), Vec::new());
 
index fbc591834d07f928e89463a053423a2b916da21b..7a3a3562bdfdcbd9ede0d2597241449c74371470 100644 (file)
@@ -73,7 +73,7 @@ pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
     base::check_zero_tts(cx, sp, tts, "module_path!");
     let string = cx.mod_path()
                    .iter()
-                   .map(|x| token::get_ident(*x).get().to_string())
+                   .map(|x| token::get_ident(*x).to_string())
                    .collect::<Vec<String>>()
                    .connect("::");
     base::MacExpr::new(cx.expr_str(
@@ -111,10 +111,14 @@ fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
         fn make_items(mut self: Box<ExpandResult<'a>>)
                       -> Option<SmallVector<P<ast::Item>>> {
             let mut ret = SmallVector::zero();
-            loop {
+            while self.p.token != token::Eof {
                 match self.p.parse_item_with_outer_attributes() {
                     Some(item) => ret.push(item),
-                    None => break
+                    None => self.p.span_fatal(
+                        self.p.span,
+                        &format!("expected item, found `{}`",
+                                 self.p.this_token_to_string())[]
+                    )
                 }
             }
             Some(ret)
index 823efdd3eed225362d1f46ac3ab6a47a1dad22fa..d752e34c11253c149318013f13e1c02269a205f9 100644 (file)
@@ -229,7 +229,7 @@ fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>],
                         p_s.span_diagnostic
                            .span_fatal(sp,
                                        &format!("duplicated bind name: {}",
-                                               string.get())[])
+                                               &string)[])
                     }
                 }
             }
@@ -487,8 +487,8 @@ pub fn parse(sess: &ParseSess,
                     let name_string = token::get_ident(name);
                     let match_cur = ei.match_cur;
                     (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal(
-                        parse_nt(&mut rust_parser, span, name_string.get()))));
-                    ei.idx += 1;
+                        parse_nt(&mut rust_parser, span, &name_string))));
+                    ei.idx += 1us;
                     ei.match_cur += 1;
                   }
                   _ => panic!()
index ac9f375e0a4a90535f1aa9ac299423d9c521102d..de61bdefa5de3303f341b0ced5203380465d0ceb 100644 (file)
@@ -319,11 +319,11 @@ fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token)
                     Some(&&TtToken(_, ref tok)) => tok.clone(),
                     Some(&&TtSequence(sp, _)) => {
                         cx.span_err(sp,
-                                    format!("`${0}:{1}` is followed by a \
-                                             sequence repetition, which is not \
-                                             allowed for `{1}` fragments",
-                                            name.as_str(), frag_spec.as_str())
-                                        .as_slice());
+                                    &format!("`${0}:{1}` is followed by a \
+                                              sequence repetition, which is not \
+                                              allowed for `{1}` fragments",
+                                             name.as_str(), frag_spec.as_str())
+                                        );
                         Eof
                     },
                     // die next iteration
@@ -338,14 +338,14 @@ fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token)
                     (&Eof, _) => return Some((sp, tok.clone())),
                     (_, Ok(true)) => continue,
                     (next, Ok(false)) => {
-                        cx.span_err(sp, format!("`${0}:{1}` is followed by `{2}`, which \
-                                                 is not allowed for `{1}` fragments",
+                        cx.span_err(sp, &format!("`${0}:{1}` is followed by `{2}`, which \
+                                                  is not allowed for `{1}` fragments",
                                                  name.as_str(), frag_spec.as_str(),
-                                                 token_to_string(next)).as_slice());
+                                                 token_to_string(next)));
                         continue
                     },
                     (_, Err(msg)) => {
-                        cx.span_err(sp, msg.as_slice());
+                        cx.span_err(sp, &msg);
                         continue
                     }
                 }
index d7a51e1149f30b0931636d3e551a0d9e4410d976..72bbe1adfaa123730558b895fdcadad0d63ccc0e 100644 (file)
@@ -21,6 +21,7 @@
 //! For the purpose of future feature-tracking, once code for detection of feature
 //! gate usage is added, *do not remove it again* even once the feature
 //! becomes stable.
+
 use self::Status::*;
 
 use abi::RustIntrinsic;
     // int and uint are now deprecated
     ("int_uint", "1.0.0", Active),
 
-    // macro reexport needs more discusion and stabilization
+    // macro reexport needs more discussion and stabilization
     ("macro_reexport", "1.0.0", Active),
 
     // These are used to test this portion of the compiler, they don't actually
     ("staged_api", "1.0.0", Active),
 
     // Allows using items which are missing stability attributes
-    ("unmarked_api", "1.0.0", Active)
+    ("unmarked_api", "1.0.0", Active),
+
+    // Allows using #![no_std]
+    ("no_std", "1.0.0", Active),
 ];
 
 enum Status {
@@ -149,7 +153,10 @@ pub struct Features {
     pub old_orphan_check: bool,
     pub simd_ffi: bool,
     pub unmarked_api: bool,
-    pub lib_features: Vec<(InternedString, Span)>
+    /// spans of #![feature] attrs for stable language features. for error reporting
+    pub declared_stable_lang_features: Vec<Span>,
+    /// #![feature] attrs for non-language (library) features
+    pub declared_lib_features: Vec<(InternedString, Span)>
 }
 
 impl Features {
@@ -162,7 +169,8 @@ pub fn new() -> Features {
             old_orphan_check: false,
             simd_ffi: false,
             unmarked_api: false,
-            lib_features: Vec::new()
+            declared_stable_lang_features: Vec::new(),
+            declared_lib_features: Vec::new()
         }
     }
 }
@@ -251,7 +259,7 @@ fn gate_feature(&self, feature: &str, span: Span, explain: &str) {
 
 impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
     fn visit_name(&mut self, sp: Span, name: ast::Name) {
-        if !token::get_name(name).get().is_ascii() {
+        if !token::get_name(name).is_ascii() {
             self.gate_feature("non_ascii_idents", sp,
                               "non-ascii idents are not fully supported.");
         }
@@ -276,11 +284,7 @@ fn visit_item(&mut self, i: &ast::Item) {
         }
         match i.node {
             ast::ItemExternCrate(_) => {
-                if attr::contains_name(&i.attrs[], "plugin") {
-                    self.gate_feature("plugin", i.span,
-                                      "compiler plugins are experimental \
-                                       and possibly buggy");
-                } else if attr::contains_name(&i.attrs[], "macro_reexport") {
+                if attr::contains_name(&i.attrs[], "macro_reexport") {
                     self.gate_feature("macro_reexport", i.span,
                                       "macros reexports are experimental \
                                        and possibly buggy");
@@ -338,7 +342,7 @@ fn visit_item(&mut self, i: &ast::Item) {
                     _ => {}
                 }
 
-                if attr::contains_name(i.attrs.as_slice(),
+                if attr::contains_name(&i.attrs,
                                        "unsafe_destructor") {
                     self.gate_feature("unsafe_destructor",
                                       i.span,
@@ -376,9 +380,9 @@ fn visit_foreign_item(&mut self, i: &ast::ForeignItem) {
                                and not portable across platforms")
         }
 
-        let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
+        let links_to_llvm = match attr::first_attr_value_str_by_name(&i.attrs,
                                                                      "link_name") {
-            Some(val) => val.get().starts_with("llvm."),
+            Some(val) => val.starts_with("llvm."),
             _ => false
         };
         if links_to_llvm {
@@ -454,6 +458,10 @@ fn visit_attribute(&mut self, attr: &ast::Attribute) {
         if attr.check_name("staged_api") {
             self.gate_feature("staged_api", attr.span,
                               "staged_api is for use by rustc only");
+        } else if attr.check_name("plugin") {
+            self.gate_feature("plugin", attr.span,
+                              "compiler plugins are experimental \
+                               and possibly buggy");
         }
 
         if attr::contains_name(slice::ref_slice(attr), "lang") {
@@ -461,6 +469,11 @@ fn visit_attribute(&mut self, attr: &ast::Attribute) {
                               attr.span,
                               "language items are subject to change");
         }
+
+        if attr.check_name("no_std") {
+            self.gate_feature("no_std", attr.span,
+                              "no_std is experimental");
+        }
     }
 
     fn visit_pat(&mut self, pattern: &ast::Pat) {
@@ -511,6 +524,7 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::C
         cm: cm,
     };
 
+    let mut accepted_features = Vec::new();
     let mut unknown_features = Vec::new();
 
     for attr in &krate.attrs {
@@ -550,8 +564,7 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::C
                             span_handler.span_err(mi.span, "feature has been removed");
                         }
                         Some(&(_, _, Accepted)) => {
-                            span_handler.span_warn(mi.span, "feature has been added to Rust, \
-                                                             directive not necessary");
+                            accepted_features.push(mi.span);
                         }
                         None => {
                             unknown_features.push((name, mi.span));
@@ -572,7 +585,8 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::C
         old_orphan_check: cx.has_feature("old_orphan_check"),
         simd_ffi: cx.has_feature("simd_ffi"),
         unmarked_api: cx.has_feature("unmarked_api"),
-        lib_features: unknown_features
+        declared_stable_lang_features: accepted_features,
+        declared_lib_features: unknown_features
     }
 }
 
index 07b6af651f610eec1e10c9744fcd64d725657dfd..8f1d15f6da885f3d5304cc23ea892b6195d54099 100644 (file)
@@ -592,7 +592,7 @@ pub fn noop_fold_mac<T: Folder>(Spanned {node, span}: Mac, fld: &mut T) -> Mac {
     Spanned {
         node: match node {
             MacInvocTT(p, tts, ctxt) => {
-                MacInvocTT(fld.fold_path(p), fld.fold_tts(tts.as_slice()), ctxt)
+                MacInvocTT(fld.fold_path(p), fld.fold_tts(&tts), ctxt)
             }
         },
         span: fld.new_span(span)
@@ -629,7 +629,7 @@ pub fn noop_fold_tt<T: Folder>(tt: &TokenTree, fld: &mut T) -> TokenTree {
                             Delimited {
                                 delim: delimed.delim,
                                 open_span: delimed.open_span,
-                                tts: fld.fold_tts(delimed.tts.as_slice()),
+                                tts: fld.fold_tts(&delimed.tts),
                                 close_span: delimed.close_span,
                             }
                         ))
@@ -637,7 +637,7 @@ pub fn noop_fold_tt<T: Folder>(tt: &TokenTree, fld: &mut T) -> TokenTree {
         TtSequence(span, ref seq) =>
             TtSequence(span,
                        Rc::new(SequenceRepetition {
-                           tts: fld.fold_tts(seq.tts.as_slice()),
+                           tts: fld.fold_tts(&seq.tts),
                            separator: seq.separator.clone().map(|tok| fld.fold_token(tok)),
                            ..**seq
                        })),
@@ -806,10 +806,12 @@ pub fn noop_fold_where_predicate<T: Folder>(
                                  fld: &mut T)
                                  -> WherePredicate {
     match pred {
-        ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{bounded_ty,
+        ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{bound_lifetimes,
+                                                                     bounded_ty,
                                                                      bounds,
                                                                      span}) => {
             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
+                bound_lifetimes: fld.fold_lifetime_defs(bound_lifetimes),
                 bounded_ty: fld.fold_ty(bounded_ty),
                 bounds: bounds.move_map(|x| fld.fold_ty_param_bound(x)),
                 span: fld.new_span(span)
@@ -895,7 +897,8 @@ pub fn noop_fold_trait_ref<T: Folder>(p: TraitRef, fld: &mut T) -> TraitRef {
 pub fn noop_fold_poly_trait_ref<T: Folder>(p: PolyTraitRef, fld: &mut T) -> PolyTraitRef {
     ast::PolyTraitRef {
         bound_lifetimes: fld.fold_lifetime_defs(p.bound_lifetimes),
-        trait_ref: fld.fold_trait_ref(p.trait_ref)
+        trait_ref: fld.fold_trait_ref(p.trait_ref),
+        span: fld.new_span(p.span),
     }
 }
 
@@ -1441,7 +1444,7 @@ mod test {
     // this version doesn't care about getting comments or docstrings in.
     fn fake_print_crate(s: &mut pprust::State,
                         krate: &ast::Crate) -> old_io::IoResult<()> {
-        s.print_mod(&krate.module, krate.attrs.as_slice())
+        s.print_mod(&krate.module, &krate.attrs)
     }
 
     // change every identifier to "zz"
@@ -1463,7 +1466,7 @@ macro_rules! assert_pred {
                 let pred_val = $pred;
                 let a_val = $a;
                 let b_val = $b;
-                if !(pred_val(a_val.as_slice(),b_val.as_slice())) {
+                if !(pred_val(&a_val, &b_val)) {
                     panic!("expected args satisfying {}, got {} and {}",
                           $predname, a_val, b_val);
                 }
index 872354024e93c319bec2e6da8b7444f9e9a6d99e..0f9a56baa170bc43b4d646f92241d35720cd067c 100644 (file)
@@ -72,7 +72,7 @@ fn default() -> OwnedSlice<T> {
 
 impl<T: Clone> Clone for OwnedSlice<T> {
     fn clone(&self) -> OwnedSlice<T> {
-        OwnedSlice::from_vec(self.as_slice().to_vec())
+        OwnedSlice::from_vec(self.to_vec())
     }
 }
 
@@ -84,7 +84,7 @@ fn from_iter<I: Iterator<Item=T>>(iter: I) -> OwnedSlice<T> {
 
 impl<T: Encodable> Encodable for OwnedSlice<T> {
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
-       self.as_slice().encode(s)
+        Encodable::encode(&**self, s)
     }
 }
 
index e6da47304cee39cebf6ce3b96c34b4007d2ed9b9..ecc39925a40c55b495c459b032279c178a05d3a6 100644 (file)
@@ -360,7 +360,7 @@ pub fn nextch_is(&self, c: char) -> bool {
 
     pub fn nextnextch(&self) -> Option<char> {
         let offset = self.byte_offset(self.pos).to_usize();
-        let s = self.filemap.src.as_slice();
+        let s = &*self.filemap.src;
         if offset >= s.len() { return None }
         let str::CharRange { next, .. } = s.char_range_at(offset);
         if next < s.len() {
index eecd7d87185434c88501ed2fdcd4365eec2dd30f..5f4cf9af5ee75cc588eba2a8cf753ebcddb1b38f 100644 (file)
@@ -244,7 +244,7 @@ pub fn new_parser_from_tts<'a>(sess: &'a ParseSess,
 /// add the path to the session's codemap and return the new filemap.
 pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
     -> Rc<FileMap> {
-    let err = |&: msg: &str| {
+    let err = |msg: &str| {
         match spanopt {
             Some(sp) => sess.span_diagnostic.span_fatal(sp, msg),
             None => sess.span_diagnostic.handler().fatal(msg),
@@ -406,7 +406,7 @@ fn esc(len: usize, lit: &str) -> Option<(char, isize)> {
         .map(|x| (x, len as isize))
     }
 
-    let unicode_escape = |&: | -> Option<(char, isize)>
+    let unicode_escape = || -> Option<(char, isize)>
         if lit.as_bytes()[2] == b'{' {
             let idx = lit.find('}').expect(msg2);
             let subslice = &lit[3..idx];
@@ -433,7 +433,7 @@ pub fn str_lit(lit: &str) -> String {
     let mut res = String::with_capacity(lit.len());
 
     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
-    let error = |&: i| format!("lexer should have rejected {} at {}", lit, i);
+    let error = |i| format!("lexer should have rejected {} at {}", lit, i);
 
     /// Eat everything up to a non-whitespace
     fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
@@ -454,7 +454,7 @@ fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
                 match c {
                     '\\' => {
                         let ch = chars.peek().unwrap_or_else(|| {
-                            panic!("{}", error(i).as_slice())
+                            panic!("{}", error(i))
                         }).1;
 
                         if ch == '\n' {
@@ -462,7 +462,7 @@ fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
                         } else if ch == '\r' {
                             chars.next();
                             let ch = chars.peek().unwrap_or_else(|| {
-                                panic!("{}", error(i).as_slice())
+                                panic!("{}", error(i))
                             }).1;
 
                             if ch != '\n' {
@@ -480,7 +480,7 @@ fn eat<'a>(it: &mut iter::Peekable<str::CharIndices<'a>>) {
                     },
                     '\r' => {
                         let ch = chars.peek().unwrap_or_else(|| {
-                            panic!("{}", error(i).as_slice())
+                            panic!("{}", error(i))
                         }).1;
 
                         if ch != '\n' {
@@ -560,7 +560,7 @@ fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>,
 }
 pub fn float_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> ast::Lit_ {
     debug!("float_lit: {:?}, {:?}", s, suffix);
-    // FIXME #2252: bounds checking float literals is defered until trans
+    // FIXME #2252: bounds checking float literals is deferred until trans
     let s = s.chars().filter(|&c| c != '_').collect::<String>();
     let data = token::intern_and_get_ident(&*s);
     filtered_float_lit(data, suffix, sd, sp)
@@ -568,7 +568,7 @@ pub fn float_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> a
 
 /// Parse a string representing a byte literal into its final form. Similar to `char_lit`
 pub fn byte_lit(lit: &str) -> (u8, usize) {
-    let err = |&: i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
+    let err = |i| format!("lexer accepted invalid byte literal {} step {}", lit, i);
 
     if lit.len() == 1 {
         (lit.as_bytes()[0], 1)
@@ -602,7 +602,7 @@ pub fn binary_lit(lit: &str) -> Rc<Vec<u8>> {
     let mut res = Vec::with_capacity(lit.len());
 
     // FIXME #8372: This could be a for-loop if it didn't borrow the iterator
-    let error = |&: i| format!("lexer should have rejected {} at {}", lit, i);
+    let error = |i| format!("lexer should have rejected {} at {}", lit, i);
 
     /// Eat everything up to a non-whitespace
     fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
@@ -622,11 +622,11 @@ fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
         match chars.next() {
             Some((i, b'\\')) => {
                 let em = error(i);
-                match chars.peek().expect(em.as_slice()).1 {
+                match chars.peek().expect(&em).1 {
                     b'\n' => eat(&mut chars),
                     b'\r' => {
                         chars.next();
-                        if chars.peek().expect(em.as_slice()).1 != b'\n' {
+                        if chars.peek().expect(&em).1 != b'\n' {
                             panic!("lexer accepted bare CR");
                         }
                         eat(&mut chars);
@@ -644,7 +644,7 @@ fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
             },
             Some((i, b'\r')) => {
                 let em = error(i);
-                if chars.peek().expect(em.as_slice()).1 != b'\n' {
+                if chars.peek().expect(&em).1 != b'\n' {
                     panic!("lexer accepted bare CR");
                 }
                 chars.next();
@@ -1200,20 +1200,20 @@ fn wb() -> c_int { O_WRONLY as c_int }
         let name = "<source>".to_string();
         let source = "/// doc comment\r\nfn foo() {}".to_string();
         let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
-        let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap();
-        assert_eq!(doc.get(), "/// doc comment");
+        let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
+        assert_eq!(&doc[], "/// doc comment");
 
         let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
         let item = parse_item_from_source_str(name.clone(), source, Vec::new(), &sess).unwrap();
-        let docs = item.attrs.iter().filter(|a| a.name().get() == "doc")
-                    .map(|a| a.value_str().unwrap().get().to_string()).collect::<Vec<_>>();
+        let docs = item.attrs.iter().filter(|a| &a.name()[] == "doc")
+                    .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
         let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
         assert_eq!(&docs[], b);
 
         let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
         let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap();
-        let doc = first_attr_value_str_by_name(item.attrs.as_slice(), "doc").unwrap();
-        assert_eq!(doc.get(), "/** doc comment\n *  with CRLF */");
+        let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
+        assert_eq!(&doc[], "/** doc comment\n *  with CRLF */");
     }
 
     #[test]
@@ -1233,8 +1233,8 @@ fn ttdelim_span() {
         let span = tts.iter().rev().next().unwrap().get_span();
 
         match sess.span_diagnostic.cm.span_to_snippet(span) {
-            Some(s) => assert_eq!(&s[], "{ body }"),
-            None => panic!("could not get snippet"),
+            Ok(s) => assert_eq!(&s[], "{ body }"),
+            Err(_) => panic!("could not get snippet"),
         }
     }
 }
index 60de6c909b78bfc2d8fb7371bea068650da2a536..1df2e762ee748de0177a9778f3caef2f2c64fd52 100644 (file)
@@ -63,15 +63,15 @@ fn obsolete(&mut self, sp: Span, kind: ObsoleteSyntax) {
                 "use a `move ||` expression instead",
             ),
             ObsoleteSyntax::ClosureType => (
-                "`|usize| -> bool` closure type syntax",
+                "`|usize| -> bool` closure type",
                 "use unboxed closures instead, no type annotation needed"
             ),
             ObsoleteSyntax::ClosureKind => (
-                "`:`, `&mut:`, or `&:` syntax",
+                "`:`, `&mut:`, or `&:`",
                 "rely on inference instead"
             ),
             ObsoleteSyntax::Sized => (
-                "`Sized? T` syntax for removing the `Sized` bound",
+                "`Sized? T` for removing the `Sized` bound",
                 "write `T: ?Sized` instead"
             ),
         };
index 2cb265033c399842c6783b9af1e97c7f29f5dc7b..fd2f0685cab8386d3bf6cf59cd176547f869fdee 100644 (file)
@@ -1036,6 +1036,8 @@ pub fn parse_for_in_type(&mut self) -> Ty_ {
         */
 
         // parse <'lt>
+        let lo = self.span.lo;
+
         let lifetime_defs = self.parse_late_bound_lifetime_defs();
 
         // examine next token to decide to do
@@ -1047,9 +1049,11 @@ pub fn parse_for_in_type(&mut self) -> Ty_ {
                   self.token.is_ident() ||
                   self.token.is_path()
         {
+            let hi = self.span.hi;
             let trait_ref = self.parse_trait_ref();
             let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
-                                                     trait_ref: trait_ref };
+                                                     trait_ref: trait_ref,
+                                                     span: mk_sp(lo, hi)};
             let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
                 self.parse_ty_param_bounds(BoundParsingMode::Bare)
             } else {
@@ -1139,7 +1143,7 @@ pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
 
     /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
     pub fn parse_obsolete_closure_kind(&mut self) {
-        // let lo = self.span.lo;
+         let lo = self.span.lo;
         if
             self.check(&token::BinOp(token::And)) &&
             self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
@@ -1163,10 +1167,8 @@ pub fn parse_obsolete_closure_kind(&mut self) {
             return;
         }
 
-        // SNAP 474b324
-        // Enable these obsolete errors after snapshot:
-        // let span = mk_sp(lo, self.span.hi);
-        // self.obsolete(span, ObsoleteSyntax::ClosureKind);
+         let span = mk_sp(lo, self.span.hi);
+         self.obsolete(span, ObsoleteSyntax::ClosureKind);
     }
 
     pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
@@ -1683,7 +1685,7 @@ pub fn lit_from_token(&self, tok: &token::Token) -> Lit_ {
 
                     token::Str_(s) => {
                         (true,
-                         LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
+                         LitStr(token::intern_and_get_ident(&parse::str_lit(s.as_str())),
                                 ast::CookedStr))
                     }
                     token::StrRaw(s, n) => {
@@ -2529,16 +2531,7 @@ pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
                 let bracket_pos = self.span.lo;
                 self.bump();
 
-                let mut found_dotdot = false;
-                if self.token == token::DotDot &&
-                   self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) {
-                    // Using expr[..], which is a mistake, should be expr[]
-                    self.bump();
-                    self.bump();
-                    found_dotdot = true;
-                }
-
-                if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) {
+                if self.eat(&token::CloseDelim(token::Bracket)) {
                     // No expression, expand to a RangeFull
                     // FIXME(#20516) It would be better to use a lang item or
                     // something for RangeFull.
@@ -2562,7 +2555,11 @@ pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
                     let range = ExprStruct(path, vec![], None);
                     let ix = self.mk_expr(bracket_pos, hi, range);
                     let index = self.mk_index(e, ix);
-                    e = self.mk_expr(lo, hi, index)
+                    e = self.mk_expr(lo, hi, index);
+                    // Enable after snapshot.
+                    // self.span_warn(e.span, "deprecated slicing syntax: `[]`");
+                    // self.span_note(e.span,
+                    //               "use `&expr[..]` to construct a slice of the whole of expr");
                 } else {
                     let ix = self.parse_expr();
                     hi = self.span.hi;
@@ -2571,11 +2568,6 @@ pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
                     e = self.mk_expr(lo, hi, index)
                 }
 
-                if found_dotdot {
-                    self.span_err(e.span, "incorrect slicing expression: `[..]`");
-                    self.span_note(e.span,
-                                   "use `&expr[]` to construct a slice of the whole of expr");
-                }
               }
               _ => return e
             }
@@ -2598,7 +2590,7 @@ fn parse_unquoted(&mut self) -> TokenTree {
                         |p| p.parse_token_tree()
                     );
                     let (sep, repeat) = self.parse_sep_and_kleene_op();
-                    let name_num = macro_parser::count_names(seq.as_slice());
+                    let name_num = macro_parser::count_names(&seq);
                     return TtSequence(mk_sp(sp.lo, seq_span.hi),
                                       Rc::new(SequenceRepetition {
                                           tts: seq,
@@ -2936,9 +2928,14 @@ pub fn parse_assign_expr(&mut self) -> P<Expr> {
             // with the postfix-form 'expr..'
             let lo = self.span.lo;
             self.bump();
-            let rhs = self.parse_binops();
-            let hi = rhs.span.hi;
-            let ex = self.mk_range(None, Some(rhs));
+            let opt_end = if self.is_at_start_of_range_notation_rhs() {
+                let end = self.parse_binops();
+                Some(end)
+            } else {
+                None
+            };
+            let hi = self.span.hi;
+            let ex = self.mk_range(None, opt_end);
             self.mk_expr(lo, hi, ex)
           }
           _ => {
@@ -4077,7 +4074,8 @@ fn parse_ty_param(&mut self) -> TyParam {
         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 },
+                                                                trait_ref: unbound,
+                                                                span: span },
                                                  TraitBoundModifier::Maybe));
             bounds = OwnedSlice::from_vec(bounds_as_vec);
         };
@@ -4230,6 +4228,16 @@ fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
                 }
 
                 _ => {
+                    let bound_lifetimes = if self.eat_keyword(keywords::For) {
+                        // Higher ranked constraint.
+                        self.expect(&token::Lt);
+                        let lifetime_defs = self.parse_lifetime_defs();
+                        self.expect_gt();
+                        lifetime_defs
+                    } else {
+                        vec![]
+                    };
+
                     let bounded_ty = self.parse_ty();
 
                     if self.eat(&token::Colon) {
@@ -4240,12 +4248,13 @@ fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
                         if bounds.len() == 0 {
                             self.span_err(span,
                                           "each predicate in a `where` clause must have \
-                                   at least one bound in it");
+                                           at least one bound in it");
                         }
 
                         generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
                                 ast::WhereBoundPredicate {
                                     span: span,
+                                    bound_lifetimes: bound_lifetimes,
                                     bounded_ty: bounded_ty,
                                     bounds: bounds,
                         }));
@@ -4681,8 +4690,12 @@ pub fn parse_method(&mut self,
 
     /// Parse trait Foo { ... }
     fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
+
         let ident = self.parse_ident();
         let mut tps = self.parse_generics();
+        // This is not very accurate, but since unbound only exists to catch
+        // obsolete syntax, the span is unlikely to ever be used.
+        let unbound_span = self.span;
         let unbound = self.parse_for_sized();
 
         // Parse supertrait bounds.
@@ -4691,7 +4704,8 @@ fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
         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 },
+                                                                trait_ref: unbound,
+                                                                span:  unbound_span },
                                                  TraitBoundModifier::Maybe));
             bounds = OwnedSlice::from_vec(bounds_as_vec);
         };
@@ -4810,11 +4824,13 @@ fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
 
     /// Parse for<'l> a::B<String,i32>
     fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
+        let lo = self.span.lo;
         let lifetime_defs = self.parse_late_bound_lifetime_defs();
 
         ast::PolyTraitRef {
             bound_lifetimes: lifetime_defs,
-            trait_ref: self.parse_trait_ref()
+            trait_ref: self.parse_trait_ref(),
+            span: mk_sp(lo, self.last_span.hi),
         }
     }
 
@@ -5140,7 +5156,7 @@ fn eval_src_mod(&mut self,
                 outer_attrs, "path") {
             Some(d) => (dir_path.join(d), true),
             None => {
-                let mod_name = mod_string.get().to_string();
+                let mod_name = mod_string.to_string();
                 let default_path_str = format!("{}.rs", mod_name);
                 let secondary_path_str = format!("{}/mod.rs", mod_name);
                 let default_path = dir_path.join(&default_path_str[]);
@@ -5152,7 +5168,7 @@ fn eval_src_mod(&mut self,
                     self.span_err(id_sp,
                                   "cannot declare a new module at this location");
                     let this_module = match self.mod_path_stack.last() {
-                        Some(name) => name.get().to_string(),
+                        Some(name) => name.to_string(),
                         None => self.root_module_name.as_ref().unwrap().clone(),
                     };
                     self.span_note(id_sp,
@@ -5198,7 +5214,7 @@ fn eval_src_mod(&mut self,
         };
 
         self.eval_src_mod_from_path(file_path, owns_directory,
-                                    mod_string.get().to_string(), id_sp)
+                                    mod_string.to_string(), id_sp)
     }
 
     fn eval_src_mod_from_path(&mut self,
index 129c1d20bc04c6ecde9bc9bcd8aafe246538688e..45f4f044ea4d1ff7502cecf0fbed90c9e880eb6a 100644 (file)
@@ -625,11 +625,6 @@ fn new_from_rc_str(string: RcStr) -> InternedString {
             string: string,
         }
     }
-
-    #[inline]
-    pub fn get<'a>(&'a self) -> &'a str {
-        &self.string[]
-    }
 }
 
 impl Deref for InternedString {
@@ -644,7 +639,7 @@ fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
         // of `BytesContainer`, which is itself a workaround for the lack of
         // DST.
         unsafe {
-            let this = self.get();
+            let this = &self[];
             mem::transmute::<&[u8],&[u8]>(this.container_as_bytes())
         }
     }
index ee8e207fa6c059b909914232d1d501cda015a9f0..583095e15742738d5fdf2eeb1a42bae3462336a4 100644 (file)
 use ast::{MethodImplItem, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
 use ast::{RequiredMethod, ProvidedMethod, TypeImplItem, TypeTraitItem};
 use ast_util;
+use attr;
 use owned_slice::OwnedSlice;
 use attr::{AttrMetaMethods, AttributeMethods};
 use codemap::{self, CodeMap, BytePos};
 use diagnostic;
-use parse::token::{self, BinOpToken, Token};
+use parse::token::{self, BinOpToken, Token, InternedString};
 use parse::lexer::comments;
 use parse;
 use print::pp::{self, break_offset, word, space, zerobreak, hardbreak};
 use print::pp::{Breaks, eof};
 use print::pp::Breaks::{Consistent, Inconsistent};
 use ptr::P;
+use std_inject;
 
 use std::{ascii, mem};
 use std::old_io::{self, IoResult};
@@ -113,6 +115,25 @@ pub fn print_crate<'a>(cm: &'a CodeMap,
                                       out,
                                       ann,
                                       is_expanded);
+    if is_expanded && std_inject::use_std(krate) {
+        // We need to print `#![no_std]` (and its feature gate) so that
+        // compiling pretty-printed source won't inject libstd again.
+        // However we don't want these attributes in the AST because
+        // of the feature gate, so we fake them up here.
+
+        let no_std_meta = attr::mk_word_item(InternedString::new("no_std"));
+
+        // #![feature(no_std)]
+        let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(),
+                                            attr::mk_list_item(InternedString::new("feature"),
+                                                               vec![no_std_meta.clone()]));
+        try!(s.print_attribute(&fake_attr));
+
+        // #![no_std]
+        let fake_attr = attr::mk_attr_inner(attr::mk_attr_id(), no_std_meta);
+        try!(s.print_attribute(&fake_attr));
+    }
+
     try!(s.print_mod(&krate.module, &krate.attrs[]));
     try!(s.print_remaining_comments());
     eof(&mut s.s)
@@ -258,7 +279,7 @@ pub fn token_to_string(tok: &Token) -> String {
         }
 
         /* Name components */
-        token::Ident(s, _)          => token::get_ident(s).get().to_string(),
+        token::Ident(s, _)          => token::get_ident(s).to_string(),
         token::Lifetime(s)          => format!("{}", token::get_ident(s)),
         token::Underscore           => "_".to_string(),
 
@@ -798,7 +819,7 @@ pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
                 try!(self.head(&visibility_qualified(item.vis,
                                                      "extern crate")[]));
                 if let Some((ref p, style)) = *optional_path {
-                    try!(self.print_string(p.get(), style));
+                    try!(self.print_string(p, style));
                     try!(space(&mut self.s));
                     try!(word(&mut self.s, "as"));
                     try!(space(&mut self.s));
@@ -1004,11 +1025,11 @@ fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
         self.print_path(&t.path, false)
     }
 
-    fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
-        if !t.bound_lifetimes.is_empty() {
+    fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> IoResult<()> {
+        if !lifetimes.is_empty() {
             try!(word(&mut self.s, "for<"));
             let mut comma = false;
-            for lifetime_def in &t.bound_lifetimes {
+            for lifetime_def in lifetimes {
                 if comma {
                     try!(self.word_space(","))
                 }
@@ -1017,7 +1038,11 @@ fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
             }
             try!(word(&mut self.s, ">"));
         }
+        Ok(())
+    }
 
+    fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
+        try!(self.print_formal_lifetime_list(&t.bound_lifetimes));
         self.print_trait_ref(&t.trait_ref)
     }
 
@@ -1313,7 +1338,7 @@ pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
         try!(self.hardbreak_if_not_bol());
         try!(self.maybe_print_comment(attr.span.lo));
         if attr.node.is_sugared_doc {
-            word(&mut self.s, attr.value_str().unwrap().get())
+            word(&mut self.s, &attr.value_str().unwrap())
         } else {
             match attr.node.style {
                 ast::AttrInner => try!(word(&mut self.s, "#![")),
@@ -1485,7 +1510,7 @@ pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
                     token::Bracket => try!(word(&mut self.s, "[")),
                     token::Brace => try!(self.bopen()),
                 }
-                try!(self.print_tts(tts.as_slice()));
+                try!(self.print_tts(tts));
                 match delim {
                     token::Paren => self.pclose(),
                     token::Bracket => word(&mut self.s, "]"),
@@ -1811,9 +1836,7 @@ pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
                 if let &Some(ref e) = start {
                     try!(self.print_expr(&**e));
                 }
-                if start.is_some() || end.is_some() {
-                    try!(word(&mut self.s, ".."));
-                }
+                try!(word(&mut self.s, ".."));
                 if let &Some(ref e) = end {
                     try!(self.print_expr(&**e));
                 }
@@ -1849,17 +1872,17 @@ pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
             ast::ExprInlineAsm(ref a) => {
                 try!(word(&mut self.s, "asm!"));
                 try!(self.popen());
-                try!(self.print_string(a.asm.get(), a.asm_str_style));
+                try!(self.print_string(&a.asm, a.asm_str_style));
                 try!(self.word_space(":"));
 
                 try!(self.commasep(Inconsistent, &a.outputs[],
                                    |s, &(ref co, ref o, is_rw)| {
-                    match co.get().slice_shift_char() {
+                    match co.slice_shift_char() {
                         Some(('=', operand)) if is_rw => {
                             try!(s.print_string(&format!("+{}", operand)[],
                                                 ast::CookedStr))
                         }
-                        _ => try!(s.print_string(co.get(), ast::CookedStr))
+                        _ => try!(s.print_string(&co, ast::CookedStr))
                     }
                     try!(s.popen());
                     try!(s.print_expr(&**o));
@@ -1871,7 +1894,7 @@ pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
 
                 try!(self.commasep(Inconsistent, &a.inputs[],
                                    |s, &(ref co, ref o)| {
-                    try!(s.print_string(co.get(), ast::CookedStr));
+                    try!(s.print_string(&co, ast::CookedStr));
                     try!(s.popen());
                     try!(s.print_expr(&**o));
                     try!(s.pclose());
@@ -1882,7 +1905,7 @@ pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
 
                 try!(self.commasep(Inconsistent, &a.clobbers[],
                                    |s, co| {
-                    try!(s.print_string(co.get(), ast::CookedStr));
+                    try!(s.print_string(&co, ast::CookedStr));
                     Ok(())
                 }));
 
@@ -1956,7 +1979,7 @@ pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
             let encoded = ident.encode_with_hygiene();
             try!(word(&mut self.s, &encoded[]))
         } else {
-            try!(word(&mut self.s, token::get_ident(ident).get()))
+            try!(word(&mut self.s, &token::get_ident(ident)))
         }
         self.ann.post(self, NodeIdent(&ident))
     }
@@ -1966,7 +1989,7 @@ pub fn print_usize(&mut self, i: usize) -> IoResult<()> {
     }
 
     pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
-        try!(word(&mut self.s, token::get_name(name).get()));
+        try!(word(&mut self.s, &token::get_name(name)));
         self.ann.post(self, NodeName(&name))
     }
 
@@ -2498,11 +2521,13 @@ pub fn print_where_clause(&mut self, generics: &ast::Generics)
             }
 
             match predicate {
-                &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bounded_ty,
+                &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
+                                                                              ref bounded_ty,
                                                                               ref bounds,
                                                                               ..}) => {
+                    try!(self.print_formal_lifetime_list(bound_lifetimes));
                     try!(self.print_type(&**bounded_ty));
-                    try!(self.print_bounds(":", bounds.as_slice()));
+                    try!(self.print_bounds(":", bounds));
                 }
                 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
                                                                                 ref bounds,
@@ -2534,15 +2559,15 @@ pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
         try!(self.ibox(indent_unit));
         match item.node {
             ast::MetaWord(ref name) => {
-                try!(word(&mut self.s, name.get()));
+                try!(word(&mut self.s, &name));
             }
             ast::MetaNameValue(ref name, ref value) => {
-                try!(self.word_space(name.get()));
+                try!(self.word_space(&name[]));
                 try!(self.word_space("="));
                 try!(self.print_literal(value));
             }
             ast::MetaList(ref name, ref items) => {
-                try!(word(&mut self.s, name.get()));
+                try!(word(&mut self.s, &name));
                 try!(self.popen());
                 try!(self.commasep(Consistent,
                                    &items[],
@@ -2733,7 +2758,7 @@ pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
             _ => ()
         }
         match lit.node {
-            ast::LitStr(ref st, style) => self.print_string(st.get(), style),
+            ast::LitStr(ref st, style) => self.print_string(&st, style),
             ast::LitByte(byte) => {
                 let mut res = String::from_str("b'");
                 ascii::escape_default(byte, |c| res.push(c as char));
@@ -2760,7 +2785,7 @@ pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
                              &format!("-{}", istr)[])
                     }
                     ast::UnsignedIntLit(ut) => {
-                        word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice())
+                        word(&mut self.s, &ast_util::uint_ty_to_string(ut, Some(i)))
                     }
                     ast::UnsuffixedIntLit(ast::Plus) => {
                         word(&mut self.s, &format!("{}", i)[])
@@ -2774,10 +2799,10 @@ pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
                 word(&mut self.s,
                      &format!(
                          "{}{}",
-                         f.get(),
+                         &f,
                          &ast_util::float_ty_to_string(t)[])[])
             }
-            ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
+            ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, &f[]),
             ast::LitBool(val) => {
                 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
             }
@@ -2937,7 +2962,7 @@ pub fn print_fn_header_info(&mut self,
                                 opt_unsafety: Option<ast::Unsafety>,
                                 abi: abi::Abi,
                                 vis: ast::Visibility) -> IoResult<()> {
-        try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
+        try!(word(&mut self.s, &visibility_qualified(vis, "")));
         try!(self.print_opt_unsafety(opt_unsafety));
 
         if abi != abi::Rust {
index d75fbcf199dbe1d8b187dedf6ff4896ea08f4cb9..98c193c7e6b850b1bfc90d6d39d8b8d7537b27ea 100644 (file)
@@ -37,7 +37,7 @@ pub fn maybe_inject_prelude(krate: ast::Crate) -> ast::Crate {
     }
 }
 
-fn use_std(krate: &ast::Crate) -> bool {
+pub fn use_std(krate: &ast::Crate) -> bool {
     !attr::contains_name(&krate.attrs[], "no_std")
 }
 
@@ -69,9 +69,6 @@ fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
             span: DUMMY_SP
         }));
 
-        // don't add #![no_std] here, that will block the prelude injection later.
-        // Add it during the prelude injection instead.
-
         krate
     }
 }
@@ -87,16 +84,6 @@ fn inject_crates_ref(krate: ast::Crate, alt_std_name: Option<String>) -> ast::Cr
 
 impl<'a> fold::Folder for PreludeInjector<'a> {
     fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
-        // Add #![no_std] here, so we don't re-inject when compiling pretty-printed source.
-        // This must happen here and not in StandardLibraryInjector because this
-        // fold happens second.
-
-        let no_std_attr = attr::mk_attr_inner(attr::mk_attr_id(),
-                                              attr::mk_word_item(InternedString::new("no_std")));
-        // std_inject runs after feature checking so manually mark this attr
-        attr::mark_used(&no_std_attr);
-        krate.attrs.push(no_std_attr);
-
         // only add `use std::prelude::*;` if there wasn't a
         // `#![no_implicit_prelude]` at the crate level.
         // fold_mod() will insert glob path.
index 61ce664d2c79036a45dfd433a7c93ab411dc8ae8..1a8cb2b376aeb1e9fe73271f34b56c65022562eb 100644 (file)
@@ -512,7 +512,7 @@ fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) {
     });
     let reexport = cx.reexport_test_harness_main.as_ref().map(|s| {
         // building `use <ident> = __test::main`
-        let reexport_ident = token::str_to_ident(s.get());
+        let reexport_ident = token::str_to_ident(&s);
 
         let use_path =
             nospan(ast::ViewPathSimple(reexport_ident,
@@ -575,7 +575,7 @@ fn mk_tests(cx: &TestCtxt) -> P<ast::Item> {
 
 fn is_test_crate(krate: &ast::Crate) -> bool {
     match attr::find_crate_name(&krate.attrs[]) {
-        Some(ref s) if "test" == &s.get()[] => true,
+        Some(ref s) if "test" == &s[] => true,
         _ => false
     }
 }
@@ -609,11 +609,11 @@ fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> {
     let test_id = ecx.ident_of("test");
 
     // creates self::test::$name
-    let test_path = |&: name| {
+    let test_path = |name| {
         ecx.path(span, vec![self_id, test_id, ecx.ident_of(name)])
     };
     // creates $name: $expr
-    let field = |&: name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
+    let field = |name, expr| ecx.field_imm(span, ecx.ident_of(name), expr);
 
     debug!("encoding {}", ast_util::path_name_i(&path[]));
 
@@ -627,7 +627,7 @@ fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> {
                                   vec![name_expr]);
 
     let ignore_expr = ecx.expr_bool(span, test.ignore);
-    let should_fail_path = |&: name| {
+    let should_fail_path = |name| {
         ecx.path(span, vec![self_id, test_id, ecx.ident_of("ShouldFail"), ecx.ident_of(name)])
     };
     let fail_expr = match test.should_fail {
index a6c92c037439658217f50e341b0a7f8ed9c9b893..b2009a7e8485480c00f418968c9f54c730a26f73 100644 (file)
@@ -65,7 +65,7 @@ pub fn as_slice<'a>(&'a self) -> &'a [T] {
                 result
             }
             One(ref v) => slice::ref_slice(v),
-            Many(ref vs) => vs.as_slice()
+            Many(ref vs) => vs
         }
     }
 
index fbcfcaadf12b71c29782e0ae4d5944b92043232a..21cb62b0a0c112818f30308c2ec7f3888906950d 100644 (file)
@@ -762,7 +762,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
             visitor.visit_expr(&**subexpression)
         }
         ExprVec(ref subexpressions) => {
-            walk_exprs(visitor, subexpressions.as_slice())
+            walk_exprs(visitor, subexpressions)
         }
         ExprRepeat(ref element, ref count) => {
             visitor.visit_expr(&**element);
@@ -787,7 +787,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
             visitor.visit_expr(&**callee_expression)
         }
         ExprMethodCall(_, ref types, ref arguments) => {
-            walk_exprs(visitor, arguments.as_slice());
+            walk_exprs(visitor, arguments);
             for typ in types {
                 visitor.visit_ty(&**typ)
             }
index 17c1e8cdb8c6d119b9a06a2f28836638993f35e6..0a1439ebee0f1e8c1edcc89cbdb97d43c7dbe775 100644 (file)
@@ -80,10 +80,10 @@ fn fg(&mut self, color: color::Color) -> IoResult<bool> {
                                .strings
                                .get("setaf")
                                .unwrap()
-                               .as_slice(),
+                               ,
                            &[Number(color as int)], &mut Variables::new());
             if s.is_ok() {
-                try!(self.out.write_all(s.unwrap().as_slice()));
+                try!(self.out.write_all(&s.unwrap()));
                 return Ok(true)
             }
         }
@@ -97,10 +97,10 @@ fn bg(&mut self, color: color::Color) -> IoResult<bool> {
                                .strings
                                .get("setab")
                                .unwrap()
-                               .as_slice(),
+                               ,
                            &[Number(color as int)], &mut Variables::new());
             if s.is_ok() {
-                try!(self.out.write_all(s.unwrap().as_slice()));
+                try!(self.out.write_all(&s.unwrap()));
                 return Ok(true)
             }
         }
@@ -115,11 +115,11 @@ fn attr(&mut self, attr: attr::Attr) -> IoResult<bool> {
                 let cap = cap_for_attr(attr);
                 let parm = self.ti.strings.get(cap);
                 if parm.is_some() {
-                    let s = expand(parm.unwrap().as_slice(),
+                    let s = expand(parm.unwrap(),
                                    &[],
                                    &mut Variables::new());
                     if s.is_ok() {
-                        try!(self.out.write_all(s.unwrap().as_slice()));
+                        try!(self.out.write_all(&s.unwrap()));
                         return Ok(true)
                     }
                 }
@@ -151,10 +151,10 @@ fn reset(&mut self) -> IoResult<()> {
             }
         }
         let s = cap.map_or(Err("can't find terminfo capability `sgr0`".to_string()), |op| {
-            expand(op.as_slice(), &[], &mut Variables::new())
+            expand(op, &[], &mut Variables::new())
         });
         if s.is_ok() {
-            return self.out.write_all(s.unwrap().as_slice())
+            return self.out.write_all(&s.unwrap())
         }
         Ok(())
     }
index 4173744ab4b1877b11e53223b384c995a25f9474..016dc84b23b9e22ae910d7970c7dda0e04c703eb 100644 (file)
@@ -257,7 +257,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
                         let flags = Flags::new();
                         let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), flags);
                         if res.is_err() { return res }
-                        output.push_all(res.unwrap().as_slice())
+                        output.push_all(&res.unwrap())
                     } else { return Err("stack is empty".to_string()) },
                     ':'|'#'|' '|'.'|'0'...'9' => {
                         let mut flags = Flags::new();
@@ -355,7 +355,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
                     (_,'d')|(_,'o')|(_,'x')|(_,'X')|(_,'s') => if stack.len() > 0 {
                         let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), *flags);
                         if res.is_err() { return res }
-                        output.push_all(res.unwrap().as_slice());
+                        output.push_all(&res.unwrap());
                         // will cause state to go to Nothing
                         old_state = FormatPattern(*flags, *fstate);
                     } else { return Err("stack is empty".to_string()) },
@@ -609,7 +609,7 @@ fn get_res(fmt: &str, cap: &str, params: &[Param], vars: &mut Variables) ->
         {
             let mut u8v: Vec<_> = fmt.bytes().collect();
             u8v.extend(cap.as_bytes().iter().map(|&b| b));
-            expand(u8v.as_slice(), params, vars)
+            expand(&u8v, params, vars)
         }
 
         let caps = ["%d", "%c", "%s", "%Pa", "%l", "%!", "%~"];
index c369e354875b5be7367c14d9817fc4ebbca53f73..f3edd90b4fa5b3c15ee1c35a06c4a6bc802969db 100644 (file)
@@ -105,7 +105,7 @@ impl TestName {
     fn as_slice<'a>(&'a self) -> &'a str {
         match *self {
             StaticTestName(s) => s,
-            DynTestName(ref s) => s.as_slice()
+            DynTestName(ref s) => s
         }
     }
 }
@@ -130,11 +130,11 @@ fn padded_name(&self, column_count: uint, align: NamePadding) -> String {
         match align {
             PadNone => name,
             PadOnLeft => {
-                pad.push_str(name.as_slice());
+                pad.push_str(&name);
                 pad
             }
             PadOnRight => {
-                name.push_str(pad.as_slice());
+                name.push_str(&pad);
                 name
             }
         }
@@ -354,20 +354,19 @@ fn usage(binary: &str) {
                      test, then the test runner will ignore these tests during
                      normal test runs. Running with --ignored will run these
                      tests."#,
-             usage = getopts::usage(message.as_slice(),
-                                    optgroups().as_slice()));
+             usage = getopts::usage(&message, &optgroups()));
 }
 
 // Parses command line arguments into test options
 pub fn parse_opts(args: &[String]) -> Option<OptRes> {
     let args_ = args.tail();
     let matches =
-        match getopts::getopts(args_.as_slice(), optgroups().as_slice()) {
+        match getopts::getopts(args_, &optgroups()) {
           Ok(m) => m,
           Err(f) => return Some(Err(f.to_string()))
         };
 
-    if matches.opt_present("h") { usage(args[0].as_slice()); return None; }
+    if matches.opt_present("h") { usage(&args[0]); return None; }
 
     let filter = if matches.free.len() > 0 {
         Some(matches.free[0].clone())
@@ -389,7 +388,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> {
         nocapture = env::var("RUST_TEST_NOCAPTURE").is_some();
     }
 
-    let color = match matches.opt_str("color").as_ref().map(|s| s.as_slice()) {
+    let color = match matches.opt_str("color").as_ref().map(|s| &**s) {
         Some("auto") | None => AutoColor,
         Some("always") => AlwaysColor,
         Some("never") => NeverColor,
@@ -523,13 +522,13 @@ pub fn write_plain(&mut self, s: &str) -> old_io::IoResult<()> {
     pub fn write_run_start(&mut self, len: uint) -> old_io::IoResult<()> {
         self.total = len;
         let noun = if len != 1 { "tests" } else { "test" };
-        self.write_plain(format!("\nrunning {} {}\n", len, noun).as_slice())
+        self.write_plain(&format!("\nrunning {} {}\n", len, noun))
     }
 
     pub fn write_test_start(&mut self, test: &TestDesc,
                             align: NamePadding) -> old_io::IoResult<()> {
         let name = test.padded_name(self.max_name_len, align);
-        self.write_plain(format!("test {} ... ", name).as_slice())
+        self.write_plain(&format!("test {} ... ", name))
     }
 
     pub fn write_result(&mut self, result: &TestResult) -> old_io::IoResult<()> {
@@ -539,13 +538,12 @@ pub fn write_result(&mut self, result: &TestResult) -> old_io::IoResult<()> {
             TrIgnored => self.write_ignored(),
             TrMetrics(ref mm) => {
                 try!(self.write_metric());
-                self.write_plain(format!(": {}", mm.fmt_metrics()).as_slice())
+                self.write_plain(&format!(": {}", mm.fmt_metrics()))
             }
             TrBench(ref bs) => {
                 try!(self.write_bench());
 
-                try!(self.write_plain(format!(": {}",
-                                              fmt_bench_samples(bs)).as_slice()));
+                try!(self.write_plain(&format!(": {}", fmt_bench_samples(bs))));
 
                 Ok(())
             }
@@ -564,7 +562,7 @@ pub fn write_log(&mut self, test: &TestDesc,
                         TrIgnored => "ignored".to_string(),
                         TrMetrics(ref mm) => mm.fmt_metrics(),
                         TrBench(ref bs) => fmt_bench_samples(bs)
-                    }, test.name.as_slice());
+                    }, test.name);
                 o.write_all(s.as_bytes())
             }
         }
@@ -577,23 +575,21 @@ pub fn write_failures(&mut self) -> old_io::IoResult<()> {
         for &(ref f, ref stdout) in &self.failures {
             failures.push(f.name.to_string());
             if stdout.len() > 0 {
-                fail_out.push_str(format!("---- {} stdout ----\n\t",
-                                          f.name.as_slice()).as_slice());
-                let output = String::from_utf8_lossy(stdout.as_slice());
-                fail_out.push_str(output.as_slice());
+                fail_out.push_str(&format!("---- {} stdout ----\n\t", f.name));
+                let output = String::from_utf8_lossy(stdout);
+                fail_out.push_str(&output);
                 fail_out.push_str("\n");
             }
         }
         if fail_out.len() > 0 {
             try!(self.write_plain("\n"));
-            try!(self.write_plain(fail_out.as_slice()));
+            try!(self.write_plain(&fail_out));
         }
 
         try!(self.write_plain("\nfailures:\n"));
         failures.sort();
         for name in &failures {
-            try!(self.write_plain(format!("    {}\n",
-                                          name.as_slice()).as_slice()));
+            try!(self.write_plain(&format!("    {}\n", name)));
         }
         Ok(())
     }
@@ -615,7 +611,7 @@ pub fn write_run_finish(&mut self) -> old_io::IoResult<bool> {
         }
         let s = format!(". {} passed; {} failed; {} ignored; {} measured\n\n",
                         self.passed, self.failed, self.ignored, self.measured);
-        try!(self.write_plain(s.as_slice()));
+        try!(self.write_plain(&s));
         return Ok(success);
     }
 }
@@ -648,13 +644,13 @@ fn callback<T: Writer>(event: &TestEvent,
                     TrOk => st.passed += 1,
                     TrIgnored => st.ignored += 1,
                     TrMetrics(mm) => {
-                        let tname = test.name.as_slice();
+                        let tname = test.name;
                         let MetricMap(mm) = mm;
                         for (k,v) in &mm {
                             st.metrics
-                              .insert_metric(format!("{}.{}",
-                                                     tname,
-                                                     k).as_slice(),
+                              .insert_metric(&format!("{}.{}",
+                                                      tname,
+                                                      k),
                                              v.value,
                                              v.noise);
                         }
@@ -686,7 +682,7 @@ fn len_if_padded(t: &TestDescAndFn) -> uint {
     match tests.iter().max_by(|t|len_if_padded(*t)) {
         Some(t) => {
             let n = t.desc.name.as_slice();
-            st.max_name_len = n.len();
+            st.max_name_len = n.as_slice().len();
         },
         None => {}
     }
@@ -1237,7 +1233,7 @@ fn parse_ignored_flag() {
         let args = vec!("progname".to_string(),
                         "filter".to_string(),
                         "--ignored".to_string());
-        let opts = match parse_opts(args.as_slice()) {
+        let opts = match parse_opts(&args) {
             Some(Ok(o)) => o,
             _ => panic!("Malformed arg in parse_ignored_flag")
         };
index ebd86dbf61cbff9e8d19e5f5e3b2167afaa6048e..04617757465ec97a58bb913e23e409e22b299f6b 100644 (file)
@@ -260,19 +260,19 @@ fn median_abs_dev_pct(&self) -> T {
 
     fn percentile(&self, pct: T) -> T {
         let mut tmp = self.to_vec();
-        local_sort(tmp.as_mut_slice());
-        percentile_of_sorted(tmp.as_slice(), pct)
+        local_sort(&mut tmp);
+        percentile_of_sorted(&tmp, pct)
     }
 
     fn quartiles(&self) -> (T,T,T) {
         let mut tmp = self.to_vec();
-        local_sort(tmp.as_mut_slice());
+        local_sort(&mut tmp);
         let first = FromPrimitive::from_uint(25).unwrap();
-        let a = percentile_of_sorted(tmp.as_slice(), first);
+        let a = percentile_of_sorted(&tmp, first);
         let secound = FromPrimitive::from_uint(50).unwrap();
-        let b = percentile_of_sorted(tmp.as_slice(), secound);
+        let b = percentile_of_sorted(&tmp, secound);
         let third = FromPrimitive::from_uint(75).unwrap();
-        let c = percentile_of_sorted(tmp.as_slice(), third);
+        let c = percentile_of_sorted(&tmp, third);
         (a,b,c)
     }
 
@@ -317,10 +317,10 @@ fn percentile_of_sorted<T: Float + FromPrimitive>(sorted_samples: &[T],
 /// See: http://en.wikipedia.org/wiki/Winsorising
 pub fn winsorize<T: Float + FromPrimitive>(samples: &mut [T], pct: T) {
     let mut tmp = samples.to_vec();
-    local_sort(tmp.as_mut_slice());
-    let lo = percentile_of_sorted(tmp.as_slice(), pct);
+    local_sort(&mut tmp);
+    let lo = percentile_of_sorted(&tmp, pct);
     let hundred: T = FromPrimitive::from_uint(100).unwrap();
-    let hi = percentile_of_sorted(tmp.as_slice(), hundred-pct);
+    let hi = percentile_of_sorted(&tmp, hundred-pct);
     for samp in samples {
         if *samp > hi {
             *samp = hi
index 822dde7eb2c61084045b3cedbe57a6032d8f64b5..54c8fcd205b8f7e5b05affff65ce279530445c41 100644 (file)
@@ -29,6 +29,7 @@
        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
        html_root_url = "http://doc.rust-lang.org/nightly/",
        html_playground_url = "http://play.rust-lang.org/")]
+#![feature(no_std)]
 #![no_std]
 #![feature(slicing_syntax)]
 #![feature(int_uint)]
@@ -78,7 +79,9 @@ pub mod str {
     pub use u_str::{utf16_items, Utf16Encoder};
 }
 
+// NOTE: remove after next snapshot
 // this lets us use #[derive(..)]
+#[cfg(stage0)]
 mod std {
     pub use core::clone;
     pub use core::cmp;
index ff8246a0e3f875023ab849f72790febd4a6bfd62..15cf3986e6e80c61eeb74124afb041980fb63c96 100644 (file)
@@ -89,12 +89,12 @@ fn trim(&self) -> &str {
 
     #[inline]
     fn trim_left(&self) -> &str {
-        self.trim_left_matches(|&: c: char| c.is_whitespace())
+        self.trim_left_matches(|c: char| c.is_whitespace())
     }
 
     #[inline]
     fn trim_right(&self) -> &str {
-        self.trim_right_matches(|&: c: char| c.is_whitespace())
+        self.trim_right_matches(|c: char| c.is_whitespace())
     }
 }
 
@@ -527,7 +527,7 @@ fn next(&mut self) -> Option<u16> {
 
         let mut buf = [0u16; 2];
         self.chars.next().map(|ch| {
-            let n = CharExt::encode_utf16(ch, buf.as_mut_slice()).unwrap_or(0);
+            let n = CharExt::encode_utf16(ch, &mut buf).unwrap_or(0);
             if n == 2 { self.extra = buf[1]; }
             buf[0]
         })
index 382cbf0d5d129e5849ca9714f809626ba6d4c5d4..b756602ead4f43286408ad769742f79e4fc32934 100644 (file)
@@ -47,7 +47,8 @@ extern char **environ;
 #endif
 #endif
 
-#if defined(__FreeBSD__) || defined(__linux__) || defined(__ANDROID__) || defined(__DragonFly__) || defined(__OpenBSD__)
+#if defined(__FreeBSD__) || defined(__linux__) || defined(__ANDROID__) \
+  || defined(__DragonFly__) || defined(__OpenBSD__)
 extern char **environ;
 #endif
 
@@ -204,7 +205,7 @@ int *__dfly_error(void) { return __error(); }
 #include <sys/sysctl.h>
 #include <limits.h>
 
-const char * rust_load_self() {
+const char * rust_current_exe() {
     static char *self = NULL;
 
     if (self == NULL) {
@@ -235,7 +236,7 @@ const char * rust_load_self() {
 
         /* get realpath if possible */
         if ((argv[0] != NULL) && ((*argv[0] == '.') || (*argv[0] == '/')
-                               || (strstr(argv[0], "/") != NULL)))
+                                || (strstr(argv[0], "/") != NULL)))
 
             self = realpath(argv[0], NULL);
         else
index 8b933fdd6dd57802f0d60b20a9efa0d559d8d575..a5192eefd57ba2e5c61fcccf1ea1f35c796278ca 100644 (file)
     max-width:none;
 }
 
-#toc {
-    position: absolute;
-    left: 0px;
-    top: 0px;
-    bottom: 0px;
-    width: 250px;
-    overflow-y: auto;
-    border-right: 1px solid rgba(0, 0, 0, 0.07);
-    padding: 10px 10px;
-    font-size: 16px;
-    background: none repeat scroll 0% 0% #FFF;
-    box-sizing: border-box;
-    -webkit-overflow-scrolling: touch;
+@media only screen {
+    #toc {
+        position: absolute;
+        left: 0px;
+        top: 0px;
+        bottom: 0px;
+        width: 250px;
+        overflow-y: auto;
+        border-right: 1px solid rgba(0, 0, 0, 0.07);
+        padding: 10px 10px;
+        font-size: 16px;
+        background: none repeat scroll 0% 0% #FFF;
+        box-sizing: border-box;
+        -webkit-overflow-scrolling: touch;
+    }
+
+    #page-wrapper {
+        position: absolute;
+        overflow-y: auto;
+        left: 260px;
+        right: 0px;
+        top: 0px;
+        bottom: 0px;
+        box-sizing: border-box;
+        background: none repeat scroll 0% 0% #FFF;
+        -webkit-overflow-scrolling: touch;
+    }
 }
 
-#page-wrapper {
-    position: absolute;
-    overflow-y: auto;
-    left: 260px;
-    right: 0px;
-    top: 0px;
-    bottom: 0px;
-    box-sizing: border-box;
-    background: none repeat scroll 0% 0% #FFF;
-    -webkit-overflow-scrolling: touch;
+@media only print {
+    #toc, #nav {
+        display: none;
+    }
+}
+
+@media only screen and (max-width: 1060px) {
+    #toc {
+        width: 100%;
+        margin-right: 0;
+        top: 40px;
+    }
+    #page-wrapper {
+        top: 40px;
+        left: 15px;
+        padding-right: 15px;
+    }
+    .mobile-hidden {
+        display: none;
+    }
 }
 
 #page {
     color: #000000;
 }
 
-@media only screen and (max-width: 1060px) {
-    #toc {
-        width: 100%;
-        margin-right: 0;
-        top: 40px;
-    }
-    #page-wrapper {
-        top: 40px;
-        left: 15px;
-        padding-right: 15px;
-    }
-    .mobile-hidden {
-        display: none;
-    }
-}
-
-
 #toggle-nav {
     height: 20px;
     width:  30px;
 .right {
     float: right;
 }
-
 "#;
index d34887d2b08b59e6af92c34c6b7b2f48d62d97fe..6ee8230e9f8baeab4b1bd35d05c521fcc488caaf 100644 (file)
@@ -43,7 +43,7 @@
   // of each of the sections.
   // It works by extracting the current page based on the url and iterates over
   // the menu links until it finds the menu item for the current page. We then
-  // create a copy of the preceeding and following menu links and add the
+  // create a copy of the preceding and following menu links and add the
   // correct css class and insert them into the bottom of the page.
   var toc = document.getElementById('toc').getElementsByTagName('a');
   var href = document.location.pathname.split('/').pop();
index 058e2e6bf7f28680c60817ed391389e5590bb4a5..56948ea1219ea437dff3933d31db71dcc80ccfec 100644 (file)
@@ -1,3 +1,12 @@
+S 2015-02-04 ac134f7
+  freebsd-x86_64 483e37a02a7ebc12a872e3146145e342ba4a5c04
+  linux-i386 8af64e5df839cc945399484380a8b2ebe05a6751
+  linux-x86_64 9f485d79c1f0d273ed864eddadb1707f3e2df489
+  macos-i386 800f86abd589a1d46c37a8700211c7ba6b05decb
+  macos-x86_64 b9961faccf79dcfdc0b7a6909bef8b6769798d08
+  winnt-i386 2c56a7573f8d0f78271dab1c8e29d3ced7a44ed8
+  winnt-x86_64 f1736f47de2a6fad1ff881e51c176f71db5dc2a5
+
 S 2015-01-31 474b324
   freebsd-x86_64 c5b55eb488790ff8425d74afa3b37c49517bc55f
   linux-i386 319f2f3573c058cb2c4dfc75faaf8ea3ae86ef11
index 54f1595780db715f0dc3b23705d47512364e3073..a29dcc00cddf8ed0272758a9ea2bd8a45910ccdb 100644 (file)
@@ -12,5 +12,5 @@
 #![crate_type = "rlib"]
 
 pub fn inner<F>(f: F) -> F {
-    (move |:| f)()
+    (move || f)()
 }
diff --git a/src/test/auxiliary/issue-21146-inc.rs b/src/test/auxiliary/issue-21146-inc.rs
new file mode 100644 (file)
index 0000000..1b740d1
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// include file for issue-21146.rs
+
+parse_error
index e99a8f0b8773750c9e9ec77130b6a9c2bf2be8c6..834667968c85bdd3cb623701249d3cf5bc6df2bc 100644 (file)
@@ -8,6 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(no_std)]
 #![no_std]
 #![feature(lang_items)]
 
index ae9804423bbd65152ddb05144b3b96184c8b411d..36b3091852bce5c4e52f5a7e4588d791f6ca3f3b 100644 (file)
@@ -37,9 +37,9 @@ fn get_lints(&self) -> LintArray {
 
     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
         let name = token::get_ident(it.ident);
-        if name.get() == "lintme" {
+        if &name[] == "lintme" {
             cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'");
-        } else if name.get() == "pleaselintme" {
+        } else if &name[] == "pleaselintme" {
             cx.span_lint(PLEASE_LINT, it.span, "item is named 'pleaselintme'");
         }
     }
index 06051b874939b82570b5613e877ae87186821af0..9020bb7b0fb2ebd6fb0637c2ce76813f87d57bdf 100644 (file)
@@ -35,7 +35,7 @@ fn get_lints(&self) -> LintArray {
 
     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
         let name = token::get_ident(it.ident);
-        if name.get() == "lintme" {
+        if &name[] == "lintme" {
             cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'");
         }
     }
index 67037a3ac9e08cde559758543ff5280e342b3849..bf4ab975cedd8c97a66dfd89a45a30488e732cdf 100644 (file)
@@ -12,5 +12,5 @@
 
 pub fn foo<T>() {
     fn death() -> int { panic!() }
-    debug!("{}", (|&:|{ death() })());
+    debug!("{}", (||{ death() })());
 }
index 7cfae6d121da1cdce8dad0e6a6390839afbd207c..d830aef54f5ef0ff825d56f1ba83ff3e43ddea18 100644 (file)
@@ -8,6 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(no_std)]
 #![no_std]
 
 pub fn foo() {}
index e01a95d461b21347e29a576213c2c52b2cad3727..907d80b50db82729f77d4a5329e9e5018db18757 100644 (file)
@@ -27,7 +27,7 @@
 use rustc::plugin::Registry;
 
 struct Expander {
-    args: P<ast::MetaItem>,
+    args: Vec<P<ast::MetaItem>>,
 }
 
 impl TTMacroExpander for Expander {
@@ -35,10 +35,9 @@ fn expand<'cx>(&self,
                    ecx: &'cx mut ExtCtxt,
                    sp: Span,
                    _: &[ast::TokenTree]) -> Box<MacResult+'cx> {
-
-        let attr = ecx.attribute(sp, self.args.clone());
-        let src = pprust::attribute_to_string(&attr);
-        let interned = token::intern_and_get_ident(src.as_slice());
+        let args = self.args.iter().map(|i| pprust::meta_item_to_string(&*i))
+            .collect::<Vec<_>>().connect(", ");
+        let interned = token::intern_and_get_ident(&args[]);
         MacExpr::new(ecx.expr_str(sp, interned))
     }
 }
index 3096adaaf11f38de7201099c70a09f120a528399..3fe7a29256d8e1d9246c03d5b4e9ccc088ae4f1c 100644 (file)
@@ -46,7 +46,7 @@ fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
         }
     };
 
-    let mut text = text.as_slice();
+    let mut text = &*text;
     let mut total = 0u;
     while !text.is_empty() {
         match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
index 6cb16f04ce115713ab4bd4f2b52f2cf162f6e85b..d84ded25702f4b38de4abf61bb5721b6e526068a 100644 (file)
@@ -25,7 +25,7 @@ fn readMaybe(s: String) -> Option<int> {
 
 impl read for bool {
     fn readMaybe(s: String) -> Option<bool> {
-        match s.as_slice() {
+        match &*s {
           "true" => Some(true),
           "false" => Some(false),
           _ => None
diff --git a/src/test/auxiliary/syntax-extension-with-dll-deps-1.rs b/src/test/auxiliary/syntax-extension-with-dll-deps-1.rs
deleted file mode 100644 (file)
index 338e04f..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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.
-
-// force-host
-
-#![crate_type = "dylib"]
-
-pub fn the_answer() -> int {
-    2
-}
diff --git a/src/test/auxiliary/syntax-extension-with-dll-deps-2.rs b/src/test/auxiliary/syntax-extension-with-dll-deps-2.rs
deleted file mode 100644 (file)
index 5ad1d24..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-// 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.
-
-// force-host
-
-#![crate_type = "dylib"]
-#![feature(plugin_registrar, quote)]
-
-extern crate "syntax-extension-with-dll-deps-1" as other;
-extern crate syntax;
-extern crate rustc;
-
-use syntax::ast::{TokenTree, Item, MetaItem};
-use syntax::codemap::Span;
-use syntax::ext::base::*;
-use rustc::plugin::Registry;
-
-#[plugin_registrar]
-pub fn plugin_registrar(reg: &mut Registry) {
-    reg.register_macro("foo", expand_foo);
-}
-
-fn expand_foo(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
-              -> Box<MacResult+'static> {
-    let answer = other::the_answer();
-    MacExpr::new(quote_expr!(cx, $answer))
-}
diff --git a/src/test/auxiliary/syntax_extension_with_dll_deps_1.rs b/src/test/auxiliary/syntax_extension_with_dll_deps_1.rs
new file mode 100644 (file)
index 0000000..338e04f
--- /dev/null
@@ -0,0 +1,17 @@
+// 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.
+
+// force-host
+
+#![crate_type = "dylib"]
+
+pub fn the_answer() -> int {
+    2
+}
diff --git a/src/test/auxiliary/syntax_extension_with_dll_deps_2.rs b/src/test/auxiliary/syntax_extension_with_dll_deps_2.rs
new file mode 100644 (file)
index 0000000..7a24dd7
--- /dev/null
@@ -0,0 +1,34 @@
+// 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.
+
+// force-host
+
+#![crate_type = "dylib"]
+#![feature(plugin_registrar, quote)]
+
+extern crate "syntax_extension_with_dll_deps_1" as other;
+extern crate syntax;
+extern crate rustc;
+
+use syntax::ast::{TokenTree, Item, MetaItem};
+use syntax::codemap::Span;
+use syntax::ext::base::*;
+use rustc::plugin::Registry;
+
+#[plugin_registrar]
+pub fn plugin_registrar(reg: &mut Registry) {
+    reg.register_macro("foo", expand_foo);
+}
+
+fn expand_foo(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree])
+              -> Box<MacResult+'static> {
+    let answer = other::the_answer();
+    MacExpr::new(quote_expr!(cx, $answer))
+}
index 4bc45caa170e4eee4e1c46d19db61bd01ffa7c7a..f03bcb41fafe8bd1f31ef25735699dcd0eb6ca81 100644 (file)
 #[inline]
 pub fn has_closures() -> uint {
     let x = 1u;
-    let mut f = move |&mut:| x;
+    let mut f = move || x;
     let y = 1u;
-    let g = |:| y;
+    let g = || y;
     f() + g()
 }
 
 pub fn has_generic_closures<T: Add<Output=T> + Copy>(x: T, y: T) -> T {
-    let mut f = move |&mut:| x;
-    let g = |:| y;
+    let mut f = move || x;
+    let g = || y;
     f() + g()
 }
index 39462fdc1e528b8dfce72d33d0fd2d910a31caba..fa254cb91ad53e87ee17fb4ede2e84d8c126419a 100644 (file)
@@ -13,6 +13,7 @@
 // This aux-file will require the eh_personality function to be codegen'd, but
 // it hasn't been defined just yet. Make sure we don't explode.
 
+#![feature(no_std)]
 #![no_std]
 #![crate_type = "rlib"]
 
index 8330c159769fd06dd5a2610ddebef910c46bdd55..12c95e4c60c64beff6a75fcae565e2a0a769ef55 100644 (file)
@@ -102,7 +102,7 @@ fn vector<M: MutableMap>(map: &mut M, n_keys: uint, dist: &[uint]) {
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
+    let args = args;
     let n_keys = {
         if args.len() == 2 {
             args[1].parse::<uint>().unwrap()
@@ -143,7 +143,7 @@ fn main() {
     {
         println!(" Random integers:");
         let mut map: BTreeMap<uint,uint> = BTreeMap::new();
-        vector(&mut map, n_keys, rand.as_slice());
+        vector(&mut map, n_keys, &rand);
     }
 
     // FIXME: #9970
@@ -162,6 +162,6 @@ fn main() {
     {
         println!(" Random integers:");
         let mut map: HashMap<uint,uint> = HashMap::new();
-        vector(&mut map, n_keys, rand.as_slice());
+        vector(&mut map, n_keys, &rand);
     }
 }
index b78b147348a8cf0bfceb1d4b04da8e3bee63612b..33ac8a43b437bf24dcdc17bb0641bf93b4b0f75a 100644 (file)
@@ -180,7 +180,7 @@ fn empty_results() -> Results {
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
+    let args = args;
     let num_keys = {
         if args.len() == 2 {
             args[1].parse::<uint>().unwrap()
index 388868eee708efd86c6bbbbf2c6a8238244d7d83..991c08f60be7af05df2cff6181cb27b47f2d1d16 100644 (file)
@@ -29,7 +29,7 @@ fn main() {
 
     macro_rules! bench {
         ($id:ident) =>
-            (maybe_run_test(argv.as_slice(),
+            (maybe_run_test(&argv,
                             stringify!($id).to_string(),
                             $id))
     }
@@ -94,7 +94,7 @@ fn vec_plus() {
             v.extend(rv.into_iter());
         } else {
             let mut rv = rv.clone();
-            rv.push_all(v.as_slice());
+            rv.push_all(&v);
             v = rv;
         }
         i += 1;
@@ -110,12 +110,12 @@ fn vec_append() {
         let rv = repeat(i).take(r.gen_range(0u, i + 1)).collect::<Vec<_>>();
         if r.gen() {
             let mut t = v.clone();
-            t.push_all(rv.as_slice());
+            t.push_all(&rv);
             v = t;
         }
         else {
             let mut t = rv.clone();
-            t.push_all(v.as_slice());
+            t.push_all(&v);
             v = t;
         }
         i += 1;
@@ -129,11 +129,11 @@ fn vec_push_all() {
     for i in 0u..1500 {
         let mut rv = repeat(i).take(r.gen_range(0u, i + 1)).collect::<Vec<_>>();
         if r.gen() {
-            v.push_all(rv.as_slice());
+            v.push_all(&rv);
         }
         else {
             swap(&mut v, &mut rv);
-            v.push_all(rv.as_slice());
+            v.push_all(&rv);
         }
     }
 }
@@ -142,7 +142,7 @@ fn is_utf8_ascii() {
     let mut v : Vec<u8> = Vec::new();
     for _ in 0u..20000 {
         v.push('b' as u8);
-        if str::from_utf8(v.as_slice()).is_err() {
+        if str::from_utf8(&v).is_err() {
             panic!("from_utf8 panicked");
         }
     }
@@ -153,7 +153,7 @@ fn is_utf8_multibyte() {
     let mut v : Vec<u8> = Vec::new();
     for _ in 0u..5000 {
         v.push_all(s.as_bytes());
-        if str::from_utf8(v.as_slice()).is_err() {
+        if str::from_utf8(&v).is_err() {
             panic!("from_utf8 panicked");
         }
     }
index 259b4d9418dcf428b5bf8312db7fa43e09cf1571..be42cb277f7a0c38fcbb8bfc05bf844acee5db24 100644 (file)
@@ -103,5 +103,5 @@ fn main() {
     };
 
     println!("{:?}", args);
-    run(args.as_slice());
+    run(&args);
 }
index 1341c03e5055b05e7645f55f2d0ab011786dbf46..d9eea02a1769be036290df74c4e52f1c3c36b535 100644 (file)
@@ -110,5 +110,5 @@ fn main() {
     };
 
     println!("{:?}", args);
-    run(args.as_slice());
+    run(&args);
 }
index a67deac67db6cf3c348944f1e739f223c45da828..e4e8b4a6e6e1e2a954aadf48ba360d5a27e33c5c 100644 (file)
@@ -65,7 +65,7 @@ fn run_pair(n: uint) {
 fn main() {
 
     let args = os::args();
-    let args = args.as_slice();
+    let args = args;
     let n = if args.len() == 3 {
         args[1].parse::<uint>().unwrap()
     } else {
index 7dc94efcf916a8f0eaf0cbef4905f18e468c093e..13b8a5ca763ad1e5a8814c08ebdcba27d4470fa8 100644 (file)
@@ -32,7 +32,7 @@ fn parfib(n: uint) -> uint {
 fn main() {
 
     let args = os::args();
-    let args = args.as_slice();
+    let args = args;
     let n = if args.len() == 2 {
         args[1].parse::<uint>().unwrap()
     } else {
index dc65a63c5cb400c2f3d5271d6aa44093a9c3366a..38648b426f6cdd6fd7b6fd5e3bfd2d9543cb5164 100644 (file)
@@ -85,7 +85,7 @@ fn inner(depth: i32, iterations: i32) -> String {
 
 fn main() {
     let args = std::os::args();
-    let args = args.as_slice();
+    let args = args;
     let n = if std::os::getenv("RUST_BENCH").is_some() {
         17
     } else if args.len() <= 1u {
index 0835dd9a08e964103e2237bd0c39ec75fa5ca522..30bbb3bc924db6a12c12c75a82fd62f834e678a4 100644 (file)
@@ -82,7 +82,7 @@ fn show_color_list(set: Vec<Color>) -> String {
     let mut out = String::new();
     for col in &set {
         out.push(' ');
-        out.push_str(format!("{:?}", col).as_slice());
+        out.push_str(&format!("{:?}", col));
     }
     out
 }
@@ -230,7 +230,7 @@ fn main() {
     let nn = if std::os::getenv("RUST_BENCH").is_some() {
         200000
     } else {
-        std::os::args().as_slice()
+        std::os::args()
                        .get(1)
                        .and_then(|arg| arg.parse().ok())
                        .unwrap_or(600u)
index 47613e2d69c73c7d5a95637b167daf8e97ce483d..92e1bc1a922c281043e468edaa880e0791572a67 100644 (file)
@@ -180,7 +180,7 @@ fn fannkuch(n: i32) -> (i32, i32) {
 }
 
 fn main() {
-    let n = std::os::args().as_slice()
+    let n = std::os::args()
         .get(1)
         .and_then(|arg| arg.parse().ok())
         .unwrap_or(2i32);
index 5386fc0419dc3c405b09283c2f4f70d229fa1486..d91031b8401f3fddd06235922018c9278a42a63e 100644 (file)
@@ -124,7 +124,7 @@ fn make(&mut self, n: uint) -> IoResult<()> {
         let mut buf = repeat(0u8).take(alu_len + LINE_LEN).collect::<Vec<_>>();
         let alu: &[u8] = self.alu.as_bytes();
 
-        copy_memory(buf.as_mut_slice(), alu);
+        copy_memory(&mut buf, alu);
         let buf_len = buf.len();
         copy_memory(&mut buf[alu_len..buf_len],
                     &alu[..LINE_LEN]);
@@ -180,7 +180,7 @@ fn rng(&mut self, max: f32) -> f32 {
 
     fn nextc(&mut self) -> u8 {
         let r = self.rng(1.0);
-        for a in &self.lookup[] {
+        for a in &self.lookup[..] {
             if a.p >= r {
                 return a.c;
             }
@@ -209,7 +209,7 @@ fn make(&mut self, n: uint) -> IoResult<()> {
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
+    let args = args;
     let n = if args.len() > 1 {
         args[1].parse::<uint>().unwrap()
     } else {
@@ -226,12 +226,12 @@ fn main() {
 
     out.write_line(">TWO IUB ambiguity codes").unwrap();
     let iub = sum_and_scale(&IUB);
-    let mut random = RandomFasta::new(&mut out, iub.as_slice());
+    let mut random = RandomFasta::new(&mut out, &iub);
     random.make(n * 3).unwrap();
 
     random.out.write_line(">THREE Homo sapiens frequency").unwrap();
     let homo_sapiens = sum_and_scale(&HOMO_SAPIENS);
-    random.lookup = make_lookup(homo_sapiens.as_slice());
+    random.lookup = make_lookup(&homo_sapiens);
     random.make(n * 5).unwrap();
 
     random.out.write_str("\n").unwrap();
index 8a2a8453a9ef533c8a81fb6d38c88ed30b18e1b1..141e098745e7bdf790e639ddc1989bc00c433568 100644 (file)
@@ -104,7 +104,7 @@ fn make_fasta<W: Writer, I: Iterator<Item=u8>>(
 
 fn run<W: Writer>(writer: &mut W) -> std::old_io::IoResult<()> {
     let args = os::args();
-    let args = args.as_slice();
+    let args = args;
     let n = if os::getenv("RUST_BENCH").is_some() {
         25000000
     } else if args.len() <= 1u {
index ad8e6551a031b1a44c2ac5cba27ac8071b214c27..ed93594534cb4f04d999e7c5c1cba3d8697417d7 100644 (file)
@@ -64,9 +64,9 @@ fn sortKV(mut orig: Vec<(Vec<u8> ,f64)> ) -> Vec<(Vec<u8> ,f64)> {
 
    let mut buffer = String::new();
    for &(ref k, v) in &pairs_sorted {
-       buffer.push_str(format!("{:?} {:0.3}\n",
-                               k.to_ascii_uppercase(),
-                               v).as_slice());
+       buffer.push_str(&format!("{:?} {:0.3}\n",
+                                k.to_ascii_uppercase(),
+                                v));
    }
 
    return buffer
@@ -122,8 +122,8 @@ fn make_sequence_processor(sz: uint,
        line = from_parent.recv().unwrap();
        if line == Vec::new() { break; }
 
-       carry.push_all(line.as_slice());
-       carry = windows_with_carry(carry.as_slice(), sz, |window| {
+       carry.push_all(&line);
+       carry = windows_with_carry(&carry, sz, |window| {
            update_freq(&mut freqs, window);
            total += 1u;
        });
index e3f8e60df93db2fcc7a0901e331abeefa1a7b346..474e5464293976f3bc758165ea15e9afb8bbe121 100644 (file)
@@ -261,7 +261,7 @@ fn print_frequencies(frequencies: &Table, frame: uint) {
     for entry in frequencies.iter() {
         vector.push((entry.count, entry.code));
     }
-    vector.as_mut_slice().sort();
+    vector.sort();
 
     let mut total_count = 0;
     for &(count, _) in &vector {
@@ -270,7 +270,7 @@ fn print_frequencies(frequencies: &Table, frame: uint) {
 
     for &(count, key) in vector.iter().rev() {
         println!("{} {:.3}",
-                 key.unpack(frame).as_slice(),
+                 key.unpack(frame),
                  (count as f32 * 100.0) / (total_count as f32));
     }
     println!("");
@@ -301,11 +301,11 @@ fn main() {
 
     let nb_freqs: Vec<_> = (1u..3).map(|i| {
         let input = input.clone();
-        (i, Thread::scoped(move|| generate_frequencies(input.as_slice(), i)))
+        (i, Thread::scoped(move|| generate_frequencies(&input, i)))
     }).collect();
     let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| {
         let input = input.clone();
-        Thread::scoped(move|| generate_frequencies(input.as_slice(), occ.len()))
+        Thread::scoped(move|| generate_frequencies(&input, occ.len()))
     }).collect();
 
     for (i, freq) in nb_freqs {
index a5729c5b5bd4c1c02596d6a661418c8e8ec2379a..e2d51fbf4111d43f63371143e6ea59eafb5b903f 100644 (file)
@@ -124,7 +124,7 @@ fn mandelbrot<W: old_io::Writer>(w: usize, mut out: W) -> old_io::IoResult<()> {
 
         Thread::scoped(move|| {
             let mut res: Vec<u8> = Vec::with_capacity((chunk_size * w) / 8);
-            let init_r_slice = vec_init_r.as_slice();
+            let init_r_slice = vec_init_r;
 
             let start = i * chunk_size;
             let end = if i == (WORKERS - 1) {
@@ -134,7 +134,7 @@ fn mandelbrot<W: old_io::Writer>(w: usize, mut out: W) -> old_io::IoResult<()> {
             };
 
             for &init_i in &vec_init_i[start..end] {
-                write_line(init_i, init_r_slice, &mut res);
+                write_line(init_i, &init_r_slice, &mut res);
             }
 
             res
@@ -143,7 +143,7 @@ fn mandelbrot<W: old_io::Writer>(w: usize, mut out: W) -> old_io::IoResult<()> {
 
     try!(writeln!(&mut out as &mut Writer, "P4\n{} {}", w, h));
     for res in data {
-        try!(out.write(res.join().ok().unwrap().as_slice()));
+        try!(out.write(&res.join().ok().unwrap()));
     }
     out.flush()
 }
index a8de1469456cb18d1fb89d3b2557e0c19d20d968..71fe1c6affce3283d946fe95f6173c020d0f7a75 100644 (file)
@@ -103,7 +103,7 @@ struct Planet {
 
 fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) {
     for _ in 0..steps {
-        let mut b_slice = bodies.as_mut_slice();
+        let mut b_slice: &mut [_] = bodies;
         loop {
             let bi = match shift_mut_ref(&mut b_slice) {
                 Some(bi) => bi,
index ea1d913b3e2ee9cd5f576908c7d507e40ef989e2..a1a9fbb471a475df28f0f35eb003b611775f0ac1 100644 (file)
@@ -57,7 +57,7 @@ fn parse_opts(argv: Vec<String> ) -> Config {
     let argv = argv.iter().map(|x| x.to_string()).collect::<Vec<_>>();
     let opt_args = &argv[1..argv.len()];
 
-    match getopts::getopts(opt_args, opts.as_slice()) {
+    match getopts::getopts(opt_args, &opts) {
       Ok(ref m) => {
           return Config {stress: m.opt_present("stress")}
       }
index 3a35bea0d5997fc3ebf23a7de6437a36424dd0fa..944383199543f3972925bfc6a50a0325d02d1c4b 100644 (file)
@@ -90,12 +90,12 @@ fn computed_cpl8(c: u8) -> u8 {
         }
     }
 
-    /// Retreives the complement for `i`.
+    /// Retrieves the complement for `i`.
     fn cpl8(&self, i: u8) -> u8 {
         self.table8[i as uint]
     }
 
-    /// Retreives the complement for `i`.
+    /// Retrieves the complement for `i`.
     fn cpl16(&self, i: u16) -> u16 {
         self.table16[i as uint]
     }
@@ -251,6 +251,6 @@ fn parallel<'a, I, T, F>(iter: I, f: F)
 fn main() {
     let mut data = read_to_end(&mut stdin_raw()).unwrap();
     let tables = &Tables::new();
-    parallel(mut_dna_seqs(data.as_mut_slice()), |&: seq| reverse_complement(seq, tables));
-    stdout_raw().write(data.as_mut_slice()).unwrap();
+    parallel(mut_dna_seqs(&mut data), |seq| reverse_complement(seq, tables));
+    stdout_raw().write(&data).unwrap();
 }
index ec85ba18f900a1fd136f0e169162a212846b8685..24e11887065c280f3fc834bd96b0decee58231da 100644 (file)
@@ -69,10 +69,10 @@ fn spectralnorm(n: uint) -> f64 {
     let mut v = u.clone();
     let mut tmp = v.clone();
     for _ in 0u..10 {
-        mult_AtAv(u.as_slice(), v.as_mut_slice(), tmp.as_mut_slice());
-        mult_AtAv(v.as_slice(), u.as_mut_slice(), tmp.as_mut_slice());
+        mult_AtAv(&u, &mut v, &mut tmp);
+        mult_AtAv(&v, &mut u, &mut tmp);
     }
-    (dot(u.as_slice(), v.as_slice()) / dot(v.as_slice(), v.as_slice())).sqrt()
+    (dot(&u, &v) / dot(&v, &v)).sqrt()
 }
 
 fn mult_AtAv(v: &[f64], out: &mut [f64], tmp: &mut [f64]) {
index 75126973cd9f4b579bcd2700e6e4efddfa4ae163..4a248384e1054848cb8ae6b1ebef0a6cda912e8e 100644 (file)
@@ -63,7 +63,7 @@ pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku {
                           .take(10).collect::<Vec<_>>();
         for line in reader.lines() {
             let line = line.unwrap();
-            let comps: Vec<&str> = line.as_slice()
+            let comps: Vec<&str> = line
                                        .trim()
                                        .split(',')
                                        .collect();
index be9e57e2d195001a4c94b6ce66c9438b2024c4fc..9fa93063ea3a5a4235427a250e8425e7df113574 100644 (file)
@@ -11,7 +11,7 @@
 // aux-build:macro_crate_test.rs
 // ignore-stage1
 
-#[plugin] #[no_link] extern crate macro_crate_test;
+#![plugin(macro_crate_test)]
 //~^ ERROR compiler plugins are experimental and possibly buggy
 
 fn main() {}
index 11ae55639596201edee9e5ead41537e9dc11c74d..a523799278c01ba3b901acf82547ddebfea10e7a 100644 (file)
@@ -13,9 +13,7 @@
 // compile-flags: -D lint-me
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate lint_group_plugin_test;
+#![plugin(lint_group_plugin_test)]
 
 fn lintme() { } //~ ERROR item is named 'lintme'
 
index 62007d6575a8db289fb27f98bf68d0db83601146..e3dbdc331a763fd115558573c95878eb9c4bd5f1 100644 (file)
 // ignore-stage1
 
 #![feature(plugin)]
+#![plugin(lint_plugin_test)]
 #![deny(test_lint)]
 
-#[plugin] #[no_link]
-extern crate lint_plugin_test;
-
 fn lintme() { } //~ ERROR item is named 'lintme'
 
 pub fn main() {
index da51c047f57e1109cbb2f2d9c65f4a576fdcee8c..41d25becd8452a87126f63c6f6f602a9dcf78c7c 100644 (file)
@@ -13,9 +13,7 @@
 // compile-flags: -D test-lint
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate lint_plugin_test;
+#![plugin(lint_plugin_test)]
 
 fn lintme() { } //~ ERROR item is named 'lintme'
 
index cf51958b53d8bec9304640e2cf4fd589675d6a7d..83c845bfdf96ef413adc5fc39ddcae2383ebc702 100644 (file)
 // ignore-stage1
 
 #![feature(plugin)]
+#![plugin(lint_plugin_test)]
 #![forbid(test_lint)]
 
-#[plugin] #[no_link]
-extern crate lint_plugin_test;
-
 fn lintme() { } //~ ERROR item is named 'lintme'
 
 #[allow(test_lint)] //~ ERROR allow(test_lint) overruled by outer forbid(test_lint)
index 9a36143f65c6ad33e6a183faf953d864317126e2..155294f8026abdc58e0517c8deadd5d8f82ca2e0 100644 (file)
@@ -13,9 +13,7 @@
 // compile-flags: -F test-lint
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate lint_plugin_test;
+#![plugin(lint_plugin_test)]
 
 fn lintme() { } //~ ERROR item is named 'lintme'
 
index 2e727f19635002a1b2294052ca77b5438c4e2c00..c9ca6e5326c69474a50fda738f119df4cf0b6502 100644 (file)
@@ -21,9 +21,7 @@
 // ident form.
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate macro_crate_test;
+#![plugin(macro_crate_test)]
 
 fn main() {
     let x = 0;
index 1f44ac7cf9cae0f7604b30e8743a3242a8c6fb33..7d38d4352b0de6bbff13da1ce964b9cee31a8c18 100644 (file)
@@ -15,7 +15,7 @@
 // ignore-cross-compile gives a different error message
 
 #![feature(plugin)]
-#[plugin] #[no_link] extern crate rlib_crate_test;
+#![plugin(rlib_crate_test)]
 //~^ ERROR: plugin crate `rlib_crate_test` only found in rlib format, but must be available in dylib format
 
 fn main() {}
index cff2e5eaf8786226904552cc21d2699d59383beb..68b27822d3d0d2d3dc5919e814459418e7c705e8 100644 (file)
@@ -14,8 +14,6 @@
 // error-pattern: plugin tried to register a new MacroRulesTT
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate macro_crate_MacroRulesTT;
+#![plugin(macro_crate_MacroRulesTT)]
 
 fn main() { }
diff --git a/src/test/compile-fail/array-old-syntax-1.rs b/src/test/compile-fail/array-old-syntax-1.rs
deleted file mode 100644 (file)
index 71c57fe..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// Test that the old fixed length array syntax is a parsing error.
-
-fn main() {
-    let _x: [isize, ..3] = [0, 1, 2]; //~ ERROR
-}
index 0694420e7666fed35f4935e80f659ba03b7b5cb5..b8aba7c483db943ea34227d32b4d1f6154d1de37 100644 (file)
@@ -27,5 +27,5 @@ fn cat(in_x : usize, in_y : isize) -> cat {
 
 fn main() {
   let nyan : cat = cat(52us, 99);
-  nyan.speak = |&:| println!("meow"); //~ ERROR attempted to take value of method
+  nyan.speak = || println!("meow"); //~ ERROR attempted to take value of method
 }
index ba8e4a652d337397609eb7c254de9b938e6f96a8..e68c3e30b9a7b08f5a4da6c097a0e929fc644c07 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// Test associated types are forbidden in inherant impls.
+// Test associated types are forbidden in inherent impls.
 
 struct Foo;
 
index b35d5131c781aa24f9a5354754b74d68a922c678..621f5ec9660fca6aff50caf0bf144f62f0b0b008 100644 (file)
@@ -13,6 +13,7 @@
 
 #![crate_type = "lib"]
 #![feature(lang_items)]
+#![feature(no_std)]
 #![no_std]
 
 #[lang="sized"]
diff --git a/src/test/compile-fail/associated-types-project-from-hrtb-explicit.rs b/src/test/compile-fail/associated-types-project-from-hrtb-explicit.rs
deleted file mode 100644 (file)
index 917c03f..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-// 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 you can't use a higher-ranked trait bound inside of a qualified
-// path (just won't parse).
-
-pub trait Foo<T> {
-    type A;
-
-    fn get(&self, t: T) -> Self::A;
-}
-
-fn foo2<I>(x: <I as for<'x> Foo<&'x isize>>::A)
-    //~^ ERROR expected identifier, found keyword `for`
-    //~| ERROR expected one of `::` or `>`
-{
-}
-
-pub fn main() {}
diff --git a/src/test/compile-fail/attr-bad-meta.rs b/src/test/compile-fail/attr-bad-meta.rs
deleted file mode 100644 (file)
index dbf2929..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:expected `]`
-
-// asterisk is bogus
-#[attr*]
-mod m {}
diff --git a/src/test/compile-fail/bad-match.rs b/src/test/compile-fail/bad-match.rs
deleted file mode 100644 (file)
index 33043ff..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-// 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.
-
-// error-pattern: expected
-
-fn main() {
-  let isize x = 5;
-  match x;
-}
-
-fn main() {
-}
index 79fe4e7165ec378d133e49be0faa3846781e4b9a..c91849ca53e1a780f2cba3bfafcf960ecc0a4ca5 100644 (file)
@@ -10,6 +10,7 @@
 
 // ignore-tidy-linelength
 
+#![feature(no_std)]
 #![no_std]
 #![feature(lang_items)]
 
diff --git a/src/test/compile-fail/bad-name.rs b/src/test/compile-fail/bad-name.rs
deleted file mode 100644 (file)
index b208c6f..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern: expected
-
-fn main() {
-  let x.y::<isize>.z foo;
-}
diff --git a/src/test/compile-fail/better-expected.rs b/src/test/compile-fail/better-expected.rs
deleted file mode 100644 (file)
index e07f4b8..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 main() {
-    let x: [isize 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `3`
-}
diff --git a/src/test/compile-fail/bind-struct-early-modifiers.rs b/src/test/compile-fail/bind-struct-early-modifiers.rs
deleted file mode 100644 (file)
index c358a21..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn main() {
-    struct Foo { x: isize }
-    match (Foo { x: 10 }) {
-        Foo { ref x: ref x } => {}, //~ ERROR expected `,`, found `:`
-        _ => {}
-    }
-}
index a28f5f6e557150b53d02d50c032fd00d4fe24ebc..5cc087cb66e3c5d9f66316df9559d7f25390efbe 100644 (file)
@@ -13,7 +13,7 @@ pub fn foo() -> bool { true }
 }
 
 fn main() {
-    let foo = |&:| false;
+    let foo = || false;
     use bar::foo;
     //~^ ERROR imports are not allowed after non-item statements
     assert_eq!(foo(), false);
diff --git a/src/test/compile-fail/borrowck-array-double-move.rs b/src/test/compile-fail/borrowck-array-double-move.rs
deleted file mode 100644 (file)
index 3fb42b3..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-// 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.
-
-#![allow(unknown_features)]
-#![feature(box_syntax)]
-
-fn f() {
-    let mut a = [box 0, box 1];
-    drop(a[0]);
-    a[1] = box 2;
-    drop(a[0]); //~ ERROR use of moved value: `a[..]`
-}
-
-fn main() {
-    f();
-}
-
index 3a2c6f038510721794edb2b4a60884df0767cdd5..b18df7f3db608b4f3bee2355d9907c16eeafa101 100644 (file)
@@ -33,7 +33,7 @@ fn b() {
     let mut p = vec!(1);
 
     borrow(
-        p.as_slice(),
+        &p,
         || p[0] = 5); //~ ERROR cannot borrow `p` as mutable
 }
 
@@ -41,7 +41,7 @@ fn c() {
     // Legal because the scope of the borrow does not include the
     // modification:
     let mut p = vec!(1);
-    borrow(p.as_slice(), ||{});
+    borrow(&p, ||{});
     p[0] = 5;
 }
 
index d983c5d5087897a9b676aee43fa7350ebdfa8f82..99ac86722693ab90716e32784ca9dbfb8007c7f4 100644 (file)
@@ -30,7 +30,7 @@ fn defer<'r>(x: &'r [&'r str]) -> defer<'r> {
 }
 
 fn main() {
-    let x = defer(vec!("Goodbye", "world!").as_slice());
+    let x = defer(&vec!("Goodbye", "world!"));
     //~^ ERROR borrowed value does not live long enough
     x.x[0];
 }
index 9b9edce243bb77ce9a9c5e94b4ff5356cbe4b752..9ea5fbbdb1af08e72e83750025961b6652fbfe72 100644 (file)
@@ -49,15 +49,15 @@ fn test5(f: &mut Test) {
 }
 
 fn test6() {
-    let mut f = |&mut:| {};
-    (|&mut:| {
+    let mut f = || {};
+    (|| {
         f();
     })();
 }
 
 fn test7() {
     fn foo<F>(_: F) where F: FnMut(Box<FnMut(isize)>, isize) {}
-    let mut f = |&mut: g: Box<FnMut(isize)>, b: isize| {};
+    let mut f = |g: Box<FnMut(isize)>, b: isize| {};
     f(box |a| {
         foo(f);
         //~^ ERROR cannot move `f` into closure because it is borrowed
index 9d73ad319a61c864b45b7ccd2a19c78090849045..851b11fac2b9d1949f9eb09f3e5a15a82c5afe33 100644 (file)
@@ -23,37 +23,37 @@ fn set(x: &mut isize) {
 
 fn a() {
     let mut x = 3;
-    let c1 = |&mut:| x = 4;
-    let c2 = |&mut:| x * 5; //~ ERROR cannot borrow `x`
+    let c1 = || x = 4;
+    let c2 = || x * 5; //~ ERROR cannot borrow `x`
 }
 
 fn b() {
     let mut x = 3;
-    let c1 = |&mut:| set(&mut x);
-    let c2 = |&mut:| get(&x); //~ ERROR cannot borrow `x`
+    let c1 = || set(&mut x);
+    let c2 = || get(&x); //~ ERROR cannot borrow `x`
 }
 
 fn c() {
     let mut x = 3;
-    let c1 = |&mut:| set(&mut x);
-    let c2 = |&mut:| x * 5; //~ ERROR cannot borrow `x`
+    let c1 = || set(&mut x);
+    let c2 = || x * 5; //~ ERROR cannot borrow `x`
 }
 
 fn d() {
     let mut x = 3;
-    let c2 = |&mut:| x * 5;
+    let c2 = || x * 5;
     x = 5; //~ ERROR cannot assign
 }
 
 fn e() {
     let mut x = 3;
-    let c1 = |&mut:| get(&x);
+    let c1 = || get(&x);
     x = 5; //~ ERROR cannot assign
 }
 
 fn f() {
     let mut x = box 3;
-    let c1 = |&mut:| get(&*x);
+    let c1 = || get(&*x);
     *x = 5; //~ ERROR cannot assign
 }
 
@@ -63,7 +63,7 @@ struct Foo {
     }
 
     let mut x = box Foo { f: box 3 };
-    let c1 = |&mut:| get(&*x.f);
+    let c1 = || get(&*x.f);
     *x.f = 5; //~ ERROR cannot assign to `*x.f`
 }
 
@@ -73,8 +73,8 @@ struct Foo {
     }
 
     let mut x = box Foo { f: box 3 };
-    let c1 = |&mut:| get(&*x.f);
-    let c2 = |&mut:| *x.f = 5; //~ ERROR cannot borrow `x` as mutable
+    let c1 = || get(&*x.f);
+    let c2 = || *x.f = 5; //~ ERROR cannot borrow `x` as mutable
 }
 
 fn main() {
index 8260774190967b417962d319ce0ce46cc0bfd1a4..40f9be2dd8230fcb82f80831b698013c703c4db5 100644 (file)
@@ -20,9 +20,9 @@ fn set(x: &mut isize) {
 }
 
 fn a(x: &isize) {
-    let c1 = |&mut:| set(&mut *x);
+    let c1 = || set(&mut *x);
     //~^ ERROR cannot borrow
-    let c2 = |&mut:| set(&mut *x);
+    let c2 = || set(&mut *x);
     //~^ ERROR cannot borrow
     //~| ERROR closure requires unique access
 }
index 48a9dccfef0baaf39c11130e168a8a77bb941cc5..8ab4e257b0626d35a76eca6239519d5e2072e8f4 100644 (file)
 
 #![feature(box_syntax)]
 
+fn to_fn_mut<F: FnMut()>(f: F) -> F { f }
+
 fn a() {
     let mut x = 3;
-    let c1 = |&mut:| x = 4;
-    let c2 = |&mut:| x = 5; //~ ERROR cannot borrow `x` as mutable more than once
+    let c1 = to_fn_mut(|| x = 4);
+    let c2 = to_fn_mut(|| x = 5); //~ ERROR cannot borrow `x` as mutable more than once
 }
 
 fn set(x: &mut isize) {
@@ -26,20 +28,20 @@ fn set(x: &mut isize) {
 
 fn b() {
     let mut x = 3;
-    let c1 = |&mut:| set(&mut x);
-    let c2 = |&mut:| set(&mut x); //~ ERROR cannot borrow `x` as mutable more than once
+    let c1 = to_fn_mut(|| set(&mut x));
+    let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
 }
 
 fn c() {
     let mut x = 3;
-    let c1 = |&mut:| x = 5;
-    let c2 = |&mut:| set(&mut x); //~ ERROR cannot borrow `x` as mutable more than once
+    let c1 = to_fn_mut(|| x = 5);
+    let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
 }
 
 fn d() {
     let mut x = 3;
-    let c1 = |&mut:| x = 5;
-    let c2 = |&mut:| { let _y = |&mut:| set(&mut x); }; // (nested closure)
+    let c1 = to_fn_mut(|| x = 5);
+    let c2 = to_fn_mut(|| { let _y = to_fn_mut(|| set(&mut x)); }); // (nested closure)
     //~^ ERROR cannot borrow `x` as mutable more than once
 }
 
@@ -49,8 +51,8 @@ struct Foo {
     }
 
     let mut x = box Foo { f: box 3 };
-    let c1 = |&mut:| set(&mut *x.f);
-    let c2 = |&mut:| set(&mut *x.f);
+    let c1 = to_fn_mut(|| set(&mut *x.f));
+    let c2 = to_fn_mut(|| set(&mut *x.f));
     //~^ ERROR cannot borrow `x` as mutable more than once
 }
 
index cf86602af0be22106ddb8ff056b512b37c81098d..dcf43c01e1775635612f4b2e7f8d46c90ef69ac8 100644 (file)
@@ -16,7 +16,7 @@ pub fn main() {
     let mut this = &mut Foo {
         x: 1,
     };
-    let mut r = |&mut:| {
+    let mut r = || {
         let p = &this.x;
         &mut this.x; //~ ERROR cannot borrow
     };
index f9a6d5ac84575617db471360a6fead5f28f34f4f..9410181659c1a229a73adf620d88c2863091d913 100644 (file)
@@ -23,27 +23,27 @@ fn set(x: &mut isize) -> isize {
 }
 
 fn a(x: &mut isize) {
-    let c1 = |&mut:| get(x);
-    let c2 = |&mut:| get(x);
+    let c1 = || get(x);
+    let c2 = || get(x);
 }
 
 fn b(x: &mut isize) {
-    let c1 = |&mut:| get(x);
-    let c2 = |&mut:| set(x); //~ ERROR closure requires unique access to `x`
+    let c1 = || get(x);
+    let c2 = || set(x); //~ ERROR closure requires unique access to `x`
 }
 
 fn c(x: &mut isize) {
-    let c1 = |&mut:| get(x);
-    let c2 = |&mut:| { get(x); set(x); }; //~ ERROR closure requires unique access to `x`
+    let c1 = || get(x);
+    let c2 = || { get(x); set(x); }; //~ ERROR closure requires unique access to `x`
 }
 
 fn d(x: &mut isize) {
-    let c1 = |&mut:| set(x);
-    let c2 = |&mut:| set(x); //~ ERROR closure requires unique access to `x`
+    let c1 = || set(x);
+    let c2 = || set(x); //~ ERROR closure requires unique access to `x`
 }
 
 fn e(x: &mut isize) {
-    let c1 = |&mut:| x = panic!(); //~ ERROR closure cannot assign to immutable local variable
+    let c1 = || x = panic!(); //~ ERROR closure cannot assign to immutable local variable
 }
 
 fn main() {
index b6529da18838b96c5f38694f699885b195eb1f11..32cd364d1f2d644ad18917d46514eeaa30e795b1 100644 (file)
@@ -26,7 +26,7 @@ fn drop(&mut self) {
 
 fn main() {
   let mut ptr = box Foo { x: 0 };
-  let mut test = |&mut: foo: &Foo| {
+  let mut test = |foo: &Foo| {
     ptr = box Foo { x: ptr.x + 1 };
   };
   test(&*ptr); //~ ERROR cannot borrow `*ptr`
index 3c20abab8bdeffac38047bab550ff1647a130cc5..5b32fd2d1987245ed1e7f76f58f142873fb801a7 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 fn main() {
-    let j = |&:| -> isize {
+    let j = || -> isize {
         let i: isize;
         i //~ ERROR use of possibly uninitialized variable: `i`
     };
index 31ca39c3f9b36772a15acd3d81c7908625c55c66..65f1a1fa098aeee2fbf521b420c4e5d18ba9fcca 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 fn main() {
-    let f  = |&:| -> isize {
+    let f  = || -> isize {
         let i: isize;
         i //~ ERROR use of possibly uninitialized variable: `i`
     };
index 4e7d81a1cb0cc5f4f526149f8813c1bad72e2bb3..f9d24130e47afdbe5f9c95588ac9a5bb62d054cf 100644 (file)
@@ -21,7 +21,7 @@ pub fn main() {
         Foo { string: "bar".to_string() },
         Foo { string: "baz".to_string() }
     );
-    let x: &[Foo] = x.as_slice();
+    let x: &[Foo] = &x;
     match x {
         [_, tail..] => {
             match tail {
index b8a92db4e422334eca533c5c27702df16e9bf831..9341758afd82e279c7b125fe6912e16a63116623 100644 (file)
@@ -14,5 +14,5 @@ fn write(v: &mut [isize]) {
 
 fn main() {
     let v = vec!(1, 2, 3);
-    write(v.as_mut_slice()); //~ ERROR cannot borrow
+    write(&mut v); //~ ERROR cannot borrow
 }
index 9193a28511e70e069a540969b9048b168d7d9875..99f396ef8143213af415dbca2a649d0b4e1cd167 100644 (file)
@@ -22,7 +22,7 @@ impl Index<String> for Foo {
     type Output = isize;
 
     fn index<'a>(&'a self, z: &String) -> &'a isize {
-        if z.as_slice() == "x" {
+        if *z == "x" {
             &self.x
         } else {
             &self.y
@@ -31,10 +31,8 @@ fn index<'a>(&'a self, z: &String) -> &'a isize {
 }
 
 impl IndexMut<String> for Foo {
-    type Output = isize;
-
     fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize {
-        if z.as_slice() == "x" {
+        if *z == "x" {
             &mut self.x
         } else {
             &mut self.y
index 7259ca8971d2b6ca363c47349679cfb9d355110d..2d752abe7e3c293a1ccc443bf378581786c635dd 100644 (file)
@@ -19,7 +19,7 @@ impl Index<String> for Foo {
     type Output = isize;
 
     fn index<'a>(&'a self, z: &String) -> &'a isize {
-        if z.as_slice() == "x" {
+        if *z == "x" {
             &self.x
         } else {
             &self.y
@@ -28,10 +28,8 @@ fn index<'a>(&'a self, z: &String) -> &'a isize {
 }
 
 impl IndexMut<String> for Foo {
-    type Output = isize;
-
     fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize {
-        if z.as_slice() == "x" {
+        if *z == "x" {
             &mut self.x
         } else {
             &mut self.y
index c3a1e808e37f8aa5381ea83c85e9129e849655fd..7093da6803ca5754d69aa7a93749d6a4ac9c42fa 100644 (file)
@@ -32,7 +32,7 @@ fn foo() {
 
 fn bar() {
     // Original borrow ends at end of closure
-    |&:| {
+    || {
         let mut x = 1us;
         let y = &mut x;
         let z = &mut x; //~ ERROR cannot borrow
index 94c1d3a6a4505a1b68dae4f3c6747e7d4a2d6a5f..7291bcd2ce1264fb984e5eb9723729ce420d2967 100644 (file)
 
 fn test() {
     let w: &mut [isize];
-    w[5] = 0; //~ ERROR use of possibly uninitialized variable: `w`
+    w[5] = 0; //~ ERROR use of possibly uninitialized variable: `*w`
 
     let mut w: &mut [isize];
-    w[5] = 0; //~ ERROR use of possibly uninitialized variable: `w`
+    w[5] = 0; //~ ERROR use of possibly uninitialized variable: `*w`
 }
 
 fn main() { test(); }
index 577334cce95042c53ef2c267e37c6720ed9f1683..2d6a4b7d2c9df023f55075450f18727d43bf27b3 100644 (file)
@@ -12,7 +12,7 @@
 
 fn a<'a>() -> &'a [isize] {
     let vec = vec!(1, 2, 3, 4);
-    let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough
+    let vec: &[isize] = &vec; //~ ERROR does not live long enough
     let tail = match vec {
         [_, tail..] => tail,
         _ => panic!("a")
@@ -22,7 +22,7 @@ fn a<'a>() -> &'a [isize] {
 
 fn b<'a>() -> &'a [isize] {
     let vec = vec!(1, 2, 3, 4);
-    let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough
+    let vec: &[isize] = &vec; //~ ERROR does not live long enough
     let init = match vec {
         [init.., _] => init,
         _ => panic!("b")
@@ -32,7 +32,7 @@ fn b<'a>() -> &'a [isize] {
 
 fn c<'a>() -> &'a [isize] {
     let vec = vec!(1, 2, 3, 4);
-    let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough
+    let vec: &[isize] = &vec; //~ ERROR does not live long enough
     let slice = match vec {
         [_, slice.., _] => slice,
         _ => panic!("c")
index 565b8ca2f6856d7000acb007581ea1acf4ebb231..c1906758a5ae89586c8531770d9bbbc56abc856a 100644 (file)
@@ -10,7 +10,7 @@
 
 fn a() {
     let mut v = vec!(1, 2, 3);
-    let vb: &mut [isize] = v.as_mut_slice();
+    let vb: &mut [isize] = &mut v;
     match vb {
         [_a, tail..] => {
             v.push(tail[0] + tail[1]); //~ ERROR cannot borrow
index 5f58027af5337c367ed92372ec5cba1a6ee8b3b5..242a38440034ccaca016addea210f249a000de09 100644 (file)
@@ -14,6 +14,8 @@ fn main() {
         [1, 2, tail..] => tail,
         _ => unreachable!()
     };
-    a[0] = 0; //~ ERROR cannot assign to `a[..]` because it is borrowed
+    println!("t[0]: {}", t[0]);
+    a[2] = 0; //~ ERROR cannot assign to `a[..]` because it is borrowed
+    println!("t[0]: {}", t[0]);
     t[0];
 }
index e125d777371c8dbaad20946459507c716984352d..b574507081713a04e5148e5a46e89ad08659f98f 100644 (file)
@@ -22,7 +22,7 @@ fn a() {
 
 fn b() {
     let mut vec = vec!(box 1, box 2, box 3);
-    let vec: &mut [Box<isize>] = vec.as_mut_slice();
+    let vec: &mut [Box<isize>] = &mut vec;
     match vec {
         [_b..] => {
             vec[0] = box 4; //~ ERROR cannot assign
@@ -32,7 +32,7 @@ fn b() {
 
 fn c() {
     let mut vec = vec!(box 1, box 2, box 3);
-    let vec: &mut [Box<isize>] = vec.as_mut_slice();
+    let vec: &mut [Box<isize>] = &mut vec;
     match vec {
         [_a,         //~ ERROR cannot move out
          _b..] => {  //~^ NOTE attempting to move value to here
@@ -50,7 +50,7 @@ fn c() {
 
 fn d() {
     let mut vec = vec!(box 1, box 2, box 3);
-    let vec: &mut [Box<isize>] = vec.as_mut_slice();
+    let vec: &mut [Box<isize>] = &mut vec;
     match vec {
         [_a..,     //~ ERROR cannot move out
          _b] => {} //~ NOTE attempting to move value to here
@@ -61,7 +61,7 @@ fn d() {
 
 fn e() {
     let mut vec = vec!(box 1, box 2, box 3);
-    let vec: &mut [Box<isize>] = vec.as_mut_slice();
+    let vec: &mut [Box<isize>] = &mut vec;
     match vec {
         [_a, _b, _c] => {}  //~ ERROR cannot move out
         //~^ NOTE attempting to move value to here
index bcd1aa81d4c2ec68c96c78a549c9085ba3ff2568..df0fee437b94ab93ef87107bd71f5eca0fd06c19 100644 (file)
@@ -10,7 +10,7 @@
 
 fn a<'a>() -> &'a isize {
     let vec = vec!(1, 2, 3, 4);
-    let vec: &[isize] = vec.as_slice(); //~ ERROR `vec` does not live long enough
+    let vec: &[isize] = &vec; //~ ERROR `vec` does not live long enough
     let tail = match vec {
         [_a, tail..] => &tail[0],
         _ => panic!("foo")
diff --git a/src/test/compile-fail/byte-literals.rs b/src/test/compile-fail/byte-literals.rs
deleted file mode 100644 (file)
index 436078f..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-
-// ignore-tidy-tab
-
-static FOO: u8 = b'\f';  //~ ERROR unknown byte escape
-
-pub fn main() {
-    b'\f';  //~ ERROR unknown byte escape
-    b'\x0Z';  //~ ERROR illegal character in numeric character escape: Z
-    b' ';  //~ ERROR byte constant must be escaped
-    b''';  //~ ERROR byte constant must be escaped
-    b'é';  //~ ERROR byte constant must be ASCII
-    b'a  //~ ERROR unterminated byte constant
-}
-
-
diff --git a/src/test/compile-fail/byte-string-literals.rs b/src/test/compile-fail/byte-string-literals.rs
deleted file mode 100644 (file)
index ec67cdd..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-
-// ignore-tidy-tab
-
-static FOO: &'static [u8] = b"\f";  //~ ERROR unknown byte escape
-
-pub fn main() {
-    b"\f";  //~ ERROR unknown byte escape
-    b"\x0Z";  //~ ERROR illegal character in numeric character escape: Z
-    b"é";  //~ ERROR byte constant must be ASCII
-    b"a  //~ ERROR unterminated double quote byte string
-}
-
-
index 738755855c0703211532b79c82ce43e92581bebc..e59bd62d178549133ae66fe02cd04cc1cb21bbba 100644 (file)
@@ -14,10 +14,10 @@ fn to_fn_once<A,F:FnOnce<A>>(f: F) -> F { f }
 
 fn main() {
     let x = 1;
-    to_fn_once(move|:| { x = 2; });
+    to_fn_once(move|| { x = 2; });
     //~^ ERROR: cannot assign to immutable captured outer variable
 
     let s = std::old_io::stdin();
-    to_fn_once(move|:| { s.read_to_end(); });
+    to_fn_once(move|| { s.read_to_end(); });
     //~^ ERROR: cannot borrow immutable captured outer variable
 }
diff --git a/src/test/compile-fail/circular_modules_hello.rs b/src/test/compile-fail/circular_modules_hello.rs
deleted file mode 100644 (file)
index 3bf8516..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// ignore-test: this is an auxiliary file for circular-modules-main.rs
-
-mod circular_modules_main;
-
-pub fn say_hello() {
-    println!("{}", circular_modules_main::hi_str());
-}
diff --git a/src/test/compile-fail/circular_modules_main.rs b/src/test/compile-fail/circular_modules_main.rs
deleted file mode 100644 (file)
index ac5ec12..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#[path = "circular_modules_hello.rs"]
-mod circular_modules_hello; //~ERROR: circular modules
-
-pub fn hi_str() -> String {
-  "Hi!".to_string()
-}
-
-fn main() {
-    circular_modules_hello::say_hello();
-}
diff --git a/src/test/compile-fail/class-implements-bad-trait.rs b/src/test/compile-fail/class-implements-bad-trait.rs
deleted file mode 100644 (file)
index d709ffd..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:nonexistent
-class cat : nonexistent {
-  let meows: usize;
-  new(in_x : usize) { self.meows = in_x; }
-}
-
-fn main() {
-  let nyan = cat(0us);
-}
index ef01c96addeb8f555f4ba26919e7f3b65b73c961..d2295eba6d7a41f99fc288e116dcbf2ab72d669d 100644 (file)
@@ -17,7 +17,7 @@ fn call_bare(f: fn(&str)) {
 
 fn main() {
     let string = "world!";
-    let f = |&: s: &str| println!("{}{}", s, string);
+    let f = |s: &str| println!("{}{}", s, string);
     call_bare(f)    //~ ERROR mismatched types
 }
 
diff --git a/src/test/compile-fail/column-offset-1-based.rs b/src/test/compile-fail/column-offset-1-based.rs
deleted file mode 100644 (file)
index 621b480..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// 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.
-
-# //~ ERROR 11:1: 11:2 error: expected one of `!` or `[`, found `<eof>`
index 46f5f41d7282f89254c2c022629204c0aefe2f39..280e2ed095266f54f943de374503a38a86bc62f7 100644 (file)
@@ -13,7 +13,7 @@
 #![deny(unreachable_code)]
 
 fn main() {
-    let x = |:| panic!();
+    let x = || panic!();
     x();
     std::io::println("Foo bar"); //~ ERROR: unreachable statement
 }
diff --git a/src/test/compile-fail/derive-no-std-not-supported.rs b/src/test/compile-fail/derive-no-std-not-supported.rs
new file mode 100644 (file)
index 0000000..f82e7f3
--- /dev/null
@@ -0,0 +1,38 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(no_std)]
+#![no_std]
+
+extern crate core;
+extern crate rand;
+extern crate "serialize" as rustc_serialize;
+
+#[derive(Rand)]  //~ ERROR this trait cannot be derived
+//~^ WARNING `#[derive(Rand)]` is deprecated
+struct Foo {
+    x: u32,
+}
+
+#[derive(RustcEncodable)]  //~ ERROR this trait cannot be derived
+struct Bar {
+    x: u32,
+}
+
+#[derive(RustcDecodable)]  //~ ERROR this trait cannot be derived
+struct Baz {
+    x: u32,
+}
+
+fn main() {
+    Foo { x: 0 };
+    Bar { x: 0 };
+    Baz { x: 0 };
+}
diff --git a/src/test/compile-fail/duplicate-visibility.rs b/src/test/compile-fail/duplicate-visibility.rs
deleted file mode 100644 (file)
index b213730..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:unmatched visibility `pub`
-extern {
-    pub pub fn foo();
-}
diff --git a/src/test/compile-fail/empty-impl-semicolon.rs b/src/test/compile-fail/empty-impl-semicolon.rs
deleted file mode 100644 (file)
index 70c7d42..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-impl Foo; //~ ERROR expected one of `(`, `+`, `::`, `<`, `for`, `where`, or `{`, found `;`
index 5335fa1206dbbf4685c2712b95508cc9c1317405..6e64e01d7410d2858315a2e6e3f4d462f8abe5f3 100644 (file)
@@ -13,12 +13,12 @@ fn wants_slice(x: &str) { }
 
 fn has_uniq(x: String) {
    wants_uniq(x);
-   wants_slice(x.as_slice());
+   wants_slice(&*x);
 }
 
 fn has_slice(x: &str) {
    wants_uniq(x); //~ ERROR mismatched types
-   wants_slice(x);
+   wants_slice(x.as_slice());
 }
 
 fn main() {
diff --git a/src/test/compile-fail/extern-expected-fn-or-brace.rs b/src/test/compile-fail/extern-expected-fn-or-brace.rs
deleted file mode 100644 (file)
index 7d1110c..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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.
-
-// Verifies that the expected token errors for `extern crate` are
-// raised
-
-extern "C" mod foo; //~ERROR expected `{` or `fn`, found `mod`
diff --git a/src/test/compile-fail/extern-foreign-crate.rs b/src/test/compile-fail/extern-foreign-crate.rs
deleted file mode 100644 (file)
index 24b978b..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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.
-
-// Verifies that the expected token errors for `extern crate` are
-// raised
-
-extern crate foo {} //~ERROR expected `;`, found `{`
diff --git a/src/test/compile-fail/extern-no-fn.rs b/src/test/compile-fail/extern-no-fn.rs
deleted file mode 100644 (file)
index 69e2f3a..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-extern {
-    f(); //~ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `f`
-}
-
-fn main() {
-}
index f8e7dc11828ff4f304a0bcef0ccbdacb728e6b7f..71e1f7091b2c99094e9459e64ba25fe261906ecc 100644 (file)
 fn needs_fn<F>(x: F) where F: Fn(isize) -> isize {}
 
 fn main() {
-    let _: () = (box |:_: isize| {}) as Box<FnOnce(isize)>;
+    let _: () = (box |_: isize| {}) as Box<FnOnce(isize)>;
     //~^ ERROR object-safe
     //~| ERROR mismatched types
     //~| expected `()`
     //~| found `Box<core::ops::FnOnce(isize)>`
     //~| expected ()
     //~| found box
-    let _: () = (box |&:_: isize, isize| {}) as Box<Fn(isize, isize)>;
+    let _: () = (box |_: isize, isize| {}) as Box<Fn(isize, isize)>;
     //~^ ERROR mismatched types
     //~| expected `()`
     //~| found `Box<core::ops::Fn(isize, isize)>`
     //~| expected ()
     //~| found box
-    let _: () = (box |&mut:| -> isize unimplemented!()) as Box<FnMut() -> isize>;
+    let _: () = (box || -> isize unimplemented!()) as Box<FnMut() -> isize>;
     //~^ ERROR mismatched types
     //~| expected `()`
     //~| found `Box<core::ops::FnMut() -> isize>`
index 39cd3e3b86afefb7857816323cb2dad10abf979e..5baafd4153159f3f6b27b31c5b0042720c51484e 100644 (file)
@@ -20,4 +20,3 @@
 #![feature = "foo"] //~ ERROR: malformed feature
 
 #![feature(test_removed_feature)] //~ ERROR: feature has been removed
-#![feature(test_accepted_feature)] //~ WARNING: feature has been added
diff --git a/src/test/compile-fail/gated-no-std.rs b/src/test/compile-fail/gated-no-std.rs
new file mode 100644 (file)
index 0000000..893ba8a
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2105 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.
+
+#![no_std] //~ ERROR no_std is experimental
+
+fn main() {}
index 99927d8b9bf5518d5bfee7903441443f6996de5b..949c1c0d9c436759fdbf78576794d92e4422ff7a 100644 (file)
@@ -14,7 +14,7 @@ fn f(y: Box<isize>) {
 }
 
 fn g() {
-    let _frob = |&: q: Box<isize>| { *q = 2; }; //~ ERROR cannot assign
+    let _frob = |q: Box<isize>| { *q = 2; }; //~ ERROR cannot assign
 
 }
 
diff --git a/src/test/compile-fail/import-from-path.rs b/src/test/compile-fail/import-from-path.rs
deleted file mode 100644 (file)
index ce91de7..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:expected
-use foo::{bar}::baz
diff --git a/src/test/compile-fail/import-from-rename.rs b/src/test/compile-fail/import-from-rename.rs
deleted file mode 100644 (file)
index ebd897a..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:expected
-
-use foo::{bar} as baz;
-
-mod foo {
-    pub fn bar() {}
-}
-
-fn main() {
-}
diff --git a/src/test/compile-fail/import-glob-path.rs b/src/test/compile-fail/import-glob-path.rs
deleted file mode 100644 (file)
index b6bc53f..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:expected
-use foo::*::bar
diff --git a/src/test/compile-fail/import-glob-rename.rs b/src/test/compile-fail/import-glob-rename.rs
deleted file mode 100644 (file)
index fb400b6..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:expected
-
-use foo::* as baz;
-
-mod foo {
-    pub fn bar() {}
-}
-
-fn main() {
-}
index ef651dd9ce7293d24df0f468a9a62ba8cbb39f9b..88dd63384b7100dffa3364f49c6a763688d57358 100644 (file)
 pub fn main() {
     let v: Vec<isize> = vec!(0, 1, 2, 3, 4, 5);
     let s: String = "abcdef".to_string();
-    v.as_slice()[3us];
-    v.as_slice()[3];
-    v.as_slice()[3u8];  //~ERROR the trait `core::ops::Index<u8>` is not implemented
+    v[3us];
+    v[3];
+    v[3u8];  //~ERROR the trait `core::ops::Index<u8>` is not implemented
     //~^ ERROR the trait `core::ops::Index<u8>` is not implemented
-    v.as_slice()[3i8];  //~ERROR the trait `core::ops::Index<i8>` is not implemented
+    v[3i8];  //~ERROR the trait `core::ops::Index<i8>` is not implemented
     //~^ ERROR the trait `core::ops::Index<i8>` is not implemented
-    v.as_slice()[3u32]; //~ERROR the trait `core::ops::Index<u32>` is not implemented
+    v[3u32]; //~ERROR the trait `core::ops::Index<u32>` is not implemented
     //~^ ERROR the trait `core::ops::Index<u32>` is not implemented
-    v.as_slice()[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented
+    v[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented
     //~^ ERROR the trait `core::ops::Index<i32>` is not implemented
     s.as_bytes()[3us];
     s.as_bytes()[3];
diff --git a/src/test/compile-fail/issue-10392-2.rs b/src/test/compile-fail/issue-10392-2.rs
deleted file mode 100644 (file)
index b077081..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct A { foo: isize }
-
-fn a() -> A { panic!() }
-
-fn main() {
-    let A { .., } = a(); //~ ERROR: expected `}`
-}
-
diff --git a/src/test/compile-fail/issue-10392.rs b/src/test/compile-fail/issue-10392.rs
deleted file mode 100644 (file)
index 3f8d26b..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct A { foo: isize }
-
-fn a() -> A { panic!() }
-
-fn main() {
-    let A { , } = a(); //~ ERROR: expected ident
-}
index 5ee693d97a878febbd8d97a53ba579ec0eb64526..736f9630127121e23bd24340114c5700f4102656 100644 (file)
@@ -12,7 +12,7 @@
 
 fn main() {
     let x = box 1;
-    let f = move|:| {
+    let f = move|| {
         let _a = x;
         drop(x);
         //~^ ERROR: use of moved value: `x`
diff --git a/src/test/compile-fail/issue-10636-1.rs b/src/test/compile-fail/issue-10636-1.rs
deleted file mode 100644 (file)
index bb020d5..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct Obj { //~ NOTE: unclosed delimiter
-    member: usize
-) //~ ERROR: incorrect close delimiter
diff --git a/src/test/compile-fail/issue-10636-2.rs b/src/test/compile-fail/issue-10636-2.rs
deleted file mode 100644 (file)
index a92ef24..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-pub fn trace_option(option: Option<isize>) {
-    option.map(|some| 42; //~ NOTE: unclosed delimiter
-} //~ ERROR: incorrect close delimiter
index 0d7a846bff633d8c7969ae93240e5837092889ca..a95bcc73a9c473adf98a2ac38839dfdeaf42ee73 100644 (file)
@@ -22,7 +22,7 @@ fn drop(&mut self) {
 
 fn main() {
     let mut ptr = box Foo { x: 0 };
-    let mut test = |&mut: foo: &Foo| {
+    let mut test = |foo: &Foo| {
         println!("access {}", foo.x);
         ptr = box Foo { x: ptr.x + 1 };
         println!("access {}", foo.x);
index aa2a71ca2dbbf51bebdf9dec83476e707f16fc3e..6dbea33d7d5d0aa59cce195851f6b1166764c740 100644 (file)
@@ -33,5 +33,5 @@ pub fn for_stdin<'a>() -> Container<'a> {
 fn main() {
     let mut c = for_stdin();
     let mut v = Vec::new();
-    c.read_to(v.as_mut_slice());
+    c.read_to(v);
 }
index f9a523641e41e1dbef4377388c1fa82fc5aab0cd..38956944f63e637a06eb70a445125ccd10b40084 100644 (file)
@@ -10,7 +10,7 @@
 
 fn main() {
     let mut v = vec!(1);
-    let mut f = |&mut:| v.push(2);
+    let mut f = || v.push(2);
     let _w = v; //~ ERROR: cannot move out of `v`
 
     f();
index 0587bdf6136b8ffe4e4b0af7c7eb0e59bbc566d7..9a471a4341f5f1706bfc9a9458c264b1e9fbef44 100644 (file)
@@ -10,7 +10,7 @@
 
 fn main() {
     let sl = vec![1,2,3];
-    let v: isize = match sl.as_slice() {
+    let v: isize = match &*sl {
         [] => 0,
         [a,b,c] => 3,
         [a, rest..] => a,
diff --git a/src/test/compile-fail/issue-14303-enum.rs b/src/test/compile-fail/issue-14303-enum.rs
deleted file mode 100644 (file)
index a26b7fd..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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.
-
-enum X<'a, T, 'b> {
-//~^ ERROR lifetime parameters must be declared prior to type parameters
-    A(&'a T)
-}
diff --git a/src/test/compile-fail/issue-14303-fn-def.rs b/src/test/compile-fail/issue-14303-fn-def.rs
deleted file mode 100644 (file)
index aaf9541..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-// 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<'a, T, 'b>(x: &'a T) {}
-//~^ ERROR lifetime parameters must be declared prior to type parameters
diff --git a/src/test/compile-fail/issue-14303-fncall.rs b/src/test/compile-fail/issue-14303-fncall.rs
deleted file mode 100644 (file)
index a7adaac..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// 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 main() {
-    (0..4)
-    .map(|x| x * 2)
-    .collect::<Vec<'a, usize, 'b>>()
-    //~^ ERROR lifetime parameters must be declared prior to type parameters
-}
diff --git a/src/test/compile-fail/issue-14303-impl.rs b/src/test/compile-fail/issue-14303-impl.rs
deleted file mode 100644 (file)
index c4a0058..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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 X { x: isize }
-
-impl<'a, T, 'b> X {}
-//~^ ERROR lifetime parameters must be declared prior to type parameters
diff --git a/src/test/compile-fail/issue-14303-path.rs b/src/test/compile-fail/issue-14303-path.rs
deleted file mode 100644 (file)
index 30cc41c..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-// 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 bar<'a, T>(x: mymodule::X<'a, T, 'b, 'c>) {}
-//~^ ERROR lifetime parameters must be declared prior to type parameters
diff --git a/src/test/compile-fail/issue-14303-struct.rs b/src/test/compile-fail/issue-14303-struct.rs
deleted file mode 100644 (file)
index 6edd808..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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 X<'a, T, 'b> {
-//~^ ERROR lifetime parameters must be declared prior to type parameters
-    x: &'a T
-}
diff --git a/src/test/compile-fail/issue-14303-trait.rs b/src/test/compile-fail/issue-14303-trait.rs
deleted file mode 100644 (file)
index 753acdd..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-// 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<'a, T, 'b> {}
-//~^ ERROR lifetime parameters must be declared prior to type parameters
index 7080db23d42e521c8b42ddb609579128603a24d8..13a5fa4b8af5af16ad60efb1adc04de9e764e358 100644 (file)
@@ -14,7 +14,7 @@ pub fn foo(params: Option<&[&str]>) -> usize {
 
 fn main() {
     let name = "Foo";
-    let x = Some(&[name.as_slice()]);
+    let x = Some(&[name]);
     let msg = foo(x);
 //~^ ERROR mismatched types
 //~| expected `core::option::Option<&[&str]>`
diff --git a/src/test/compile-fail/issue-15914.rs b/src/test/compile-fail/issue-15914.rs
deleted file mode 100644 (file)
index 45b3abf..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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 main() {
-    let ref
-        (); //~ ERROR expected identifier, found `(`
-}
diff --git a/src/test/compile-fail/issue-1655.rs b/src/test/compile-fail/issue-1655.rs
deleted file mode 100644 (file)
index a8704f7..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:expected one of `!` or `[`, found `vec`
-mod blade_runner {
-    #vec[doc(
-        brief = "Blade Runner is probably the best movie ever",
-        desc = "I like that in the world of Blade Runner it is always
-                raining, and that it's always night time. And Aliens
-                was also a really good movie.
-
-                Alien 3 was crap though."
-    )]
-}
index 9d2212b69cee116de1d270b87f1010416b4ab45a..7ec3fef5c878eb05a060356e60fa5b169b03392c 100644 (file)
@@ -14,7 +14,7 @@
 // wrong arity.
 
 fn _foo<F: Fn()> (f: F) {
-    |&: t| f(t); //~ ERROR E0057
+    |t| f(t); //~ ERROR E0057
 }
 
 fn main() {}
index 3889b6f4f7dceca1d9d261603bdddfe69d598a30..b19a7703b85605e49bbc807bec3c1edd0159ff02 100644 (file)
@@ -14,5 +14,5 @@
 
 fn main() {
     let foo = B;
-    let closure = |:| foo; //~ ERROR unable to infer enough type information
+    let closure = || foo; //~ ERROR unable to infer enough type information
 }
index fbecd0487bf6f5d7811752cfd71c9a24a3d12e80..1cdf48e291c755e6efb727f780d31a727e26a315 100644 (file)
@@ -14,7 +14,7 @@
 #![feature(box_syntax)]
 
 fn main() {
-    (|&:| box *[0us].as_slice())();
+    (|| box *[0us].as_slice())();
     //~^ ERROR cannot move out of borrowed content
     //~^^ ERROR cannot move a value of type [usize]
 }
index 9c708bdeaa8093fe68ac0c30ef32f5c7616e6ea7..83e52216be29baa371506ac14f26f106294db121 100644 (file)
@@ -100,7 +100,7 @@ impl TraversesWorld for Player {
 impl Debug 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(&self.name);
         formatter.write_str(" }");
         Ok(())
     }
diff --git a/src/test/compile-fail/issue-17904.rs b/src/test/compile-fail/issue-17904.rs
deleted file mode 100644 (file)
index 96ba712..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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 Baz<U> where U: Eq(U); //This is parsed as the new Fn* style parenthesis syntax.
-struct Baz<U> where U: Eq(U) -> R; // Notice this parses as well.
-struct Baz<U>(U) where U: Eq; // This rightfully signals no error as well.
-struct Foo<T> where T: Copy, (T); //~ ERROR unexpected token in `where` clause
-struct Bar<T> { x: T } where T: Copy //~ ERROR expected item, found `where`
-
-fn main() {}
diff --git a/src/test/compile-fail/issue-1802-1.rs b/src/test/compile-fail/issue-1802-1.rs
deleted file mode 100644 (file)
index 8ce99f5..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:no valid digits found for number
-fn main() {
-    log(error, 0b42);
-}
diff --git a/src/test/compile-fail/issue-19096.rs b/src/test/compile-fail/issue-19096.rs
deleted file mode 100644 (file)
index 90d2acb..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn main() {
-    let t = (42, 42);
-    t.0::<isize>; //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `::`
-}
diff --git a/src/test/compile-fail/issue-19398.rs b/src/test/compile-fail/issue-19398.rs
deleted file mode 100644 (file)
index 3a6d15e..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// 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 T {
-    extern "Rust" unsafe fn foo(); //~ ERROR expected `fn`, found `unsafe`
-}
-
-fn main() {}
index f83037d47bbb1dc398068a64e95551f3fae8805c..14601e67a77c1c77a86391940ab74a47eb0e8820 100644 (file)
@@ -10,7 +10,7 @@
 
 // error-pattern: requires `copy` lang_item
 
-#![feature(lang_items, start)]
+#![feature(lang_items, start, no_std)]
 #![no_std]
 
 #[lang = "sized"]
diff --git a/src/test/compile-fail/issue-20711-2.rs b/src/test/compile-fail/issue-20711-2.rs
deleted file mode 100644 (file)
index a6c4570..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct Foo;
-
-impl Foo {
-    fn foo() {}
-
-    #[stable(feature = "rust1", since = "1.0.0")]
-} //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `}`
-
-fn main() {}
-
diff --git a/src/test/compile-fail/issue-20711.rs b/src/test/compile-fail/issue-20711.rs
deleted file mode 100644 (file)
index 3b329d7..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct Foo;
-
-impl Foo {
-    #[stable(feature = "rust1", since = "1.0.0")]
-} //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `}`
-
-fn main() {}
diff --git a/src/test/compile-fail/issue-21146.rs b/src/test/compile-fail/issue-21146.rs
new file mode 100644 (file)
index 0000000..4c6059c
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern: expected item, found `parse_error`
+include!("../auxiliary/issue-21146-inc.rs");
+fn main() {}
diff --git a/src/test/compile-fail/issue-21153.rs b/src/test/compile-fail/issue-21153.rs
deleted file mode 100644 (file)
index e2b6deb..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 MyTrait<T>: Iterator {
-    Item = T; //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `Item`
-}
index 45b7bebfc281e904465d3d7174b09d98cfcb4731..37dbcaf39bd10ba17c99dfdc6c30f9a243a3a851 100644 (file)
@@ -20,6 +20,6 @@ fn bind<B, F>(&self, mut f: F) where F: FnMut(A) -> Vec<B> {
    }
 }
 fn main() {
-    ["hi"].bind(|&mut: x| [x] );
+    ["hi"].bind(|x| [x] );
     //~^ ERROR type `[&str; 1]` does not implement any method in scope named `bind`
 }
diff --git a/src/test/compile-fail/issue-21974.rs b/src/test/compile-fail/issue-21974.rs
new file mode 100644 (file)
index 0000000..f768d6c
--- /dev/null
@@ -0,0 +1,28 @@
+// 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 (for now) we report an ambiguity error here, because
+// specific trait relationships are ignored for the purposes of trait
+// matching. This behavior should likely be improved such that this
+// test passes. See #21974 for more details.
+
+trait Foo {
+    fn foo(self);
+}
+
+fn foo<'a,'b,T>(x: &'a T, y: &'b T)
+    where &'a T : Foo,
+          &'b T : Foo
+{
+    x.foo(); //~ ERROR type annotations required
+    y.foo();
+}
+
+fn main() { }
diff --git a/src/test/compile-fail/issue-2354-1.rs b/src/test/compile-fail/issue-2354-1.rs
deleted file mode 100644 (file)
index d37837b..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-static foo: isize = 2; } //~ ERROR incorrect close delimiter:
-
diff --git a/src/test/compile-fail/issue-2354.rs b/src/test/compile-fail/issue-2354.rs
deleted file mode 100644 (file)
index cc219a6..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn foo() { //~ HELP did you mean to close this delimiter?
-  match Some(x) {
-      Some(y) { panic!(); }
-      None    { panic!(); }
-}
-
-fn bar() {
-    let mut i = 0;
-    while (i < 1000) {}
-}
-
-fn main() {} //~ ERROR this file contains an un-closed delimiter
diff --git a/src/test/compile-fail/issue-3036.rs b/src/test/compile-fail/issue-3036.rs
deleted file mode 100644 (file)
index 16834f4..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// Testing that semicolon tokens are printed correctly in errors
-
-fn main()
-{
-    let x = 3
-} //~ ERROR: expected one of `.`, `;`, or an operator, found `}`
index c67d6b1ce8f7ce17e063dcc42ab31835527ca254..0f7cc2cb72b8e2b05b73dcb6456119e3ade48d33 100644 (file)
@@ -11,7 +11,7 @@
 
 fn main() {
     let needlesArr: Vec<char> = vec!('a', 'f');
-    needlesArr.iter().fold(|&: x, y| {
+    needlesArr.iter().fold(|x, y| {
     });
     //~^^ ERROR this function takes 2 parameters but 1 parameter was supplied
     //
index 7ebc5b7a5b96bf3757311379e0ac7aa5ee2ce235..0e1cc18dba910f373767b697787be67bfe32a3e2 100644 (file)
@@ -10,7 +10,7 @@
 
 trait A {
     fn a(&self) {
-        |&:| self.b()
+        || self.b()
         //~^ ERROR type `&Self` does not implement any method in scope named `b`
         //~| ERROR mismatched types
         //~| expected `()`
index 3d44c1a52d49253fceb0a9476dad591cd465c7d0..d0da51373d926fe599ee84da402673be3913f5d9 100644 (file)
@@ -14,7 +14,7 @@
 fn id<T>(t: T) -> T { t }
 
 fn f<'r, T>(v: &'r T) -> Box<FnMut() -> T + 'r> {
-    id(box |&mut:| *v) //~ ERROR cannot infer
+    id(box || *v) //~ ERROR cannot infer
 }
 
 fn main() {
index 0eaa40efca22bda731c6b7ae5a66ba0d19fac370..49a43ee37adca88d9ec5224a79b161945a0354f0 100644 (file)
@@ -11,6 +11,6 @@
 // Regression test for issue #5239
 
 fn main() {
-    let x = |&: ref x: isize| -> isize { x += 1; };
+    let x = |ref x: isize| -> isize { x += 1; };
     //~^ ERROR binary assignment operation `+=` cannot be applied to type `&isize`
 }
diff --git a/src/test/compile-fail/issue-5806.rs b/src/test/compile-fail/issue-5806.rs
deleted file mode 100644 (file)
index 597366a..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-// 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.
-
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#[path = "../compile-fail"]
-mod foo; //~ ERROR: a directory
-
-fn main() {}
diff --git a/src/test/compile-fail/issue-6610.rs b/src/test/compile-fail/issue-6610.rs
deleted file mode 100644 (file)
index 166e91b..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-trait Foo { fn a() } //~ ERROR expected `;` or `{`, found `}`
-
-fn main() {}
index 9424ff22dc75ce971e9e68fdf571a7f12441ad0e..9e797019392450e201d0958e24809a6e031e03a8 100644 (file)
@@ -24,7 +24,7 @@ fn invoke<F>(f: F) where F: FnOnce() -> usize {
 
 fn main() {
       let x  : Box<usize>  = box 9;
-      let sq =  |:| { *x * *x };
+      let sq =  || { *x * *x };
 
       twice(x); //~ ERROR: cannot move out of
       invoke(sq);
index 2e644b65402344f1310aaa6e34d55b9f3ee03c7d..465a38111babcc63e81360df74680502e6fe02f0 100644 (file)
@@ -12,7 +12,7 @@
 
 use std::cell::RefCell;
 
-// Regresion test for issue 7364
+// Regression test for issue 7364
 static boxed: Box<RefCell<isize>> = box RefCell::new(0);
 //~^ ERROR statics are not allowed to have custom pointers
 //~| ERROR: the trait `core::marker::Sync` is not implemented for the type
index c15c556f5d68f2bc7eb0b07e4386a2c4c3da1794..2d1cea1d44b746698ff438f6db9d2edc3d69161d 100644 (file)
@@ -25,7 +25,7 @@ fn new(s: &str) -> CrateId {
 
 pub fn remove_package_from_database() {
     let mut lines_to_use: Vec<&CrateId> = Vec::new();
-    let push_id = |&mut: installed_id: &CrateId| {
+    let push_id = |installed_id: &CrateId| {
         lines_to_use.push(installed_id);
         //~^ ERROR cannot infer an appropriate lifetime for automatic coercion due to
         // conflicting requirements
index 808aa098c5a28c1c317c1e99d518a3a9ff26df29..7424a45d04405aa2ea2997a43304c5fa12467c18 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// Regresion test for issue 9243
+// Regression test for issue 9243
 
 struct Test {
     mem: isize,
diff --git a/src/test/compile-fail/keyword-abstract.rs b/src/test/compile-fail/keyword-abstract.rs
deleted file mode 100644 (file)
index 1f1360e..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 main() {
-    let abstract = (); //~ ERROR `abstract` is a reserved keyword
-}
diff --git a/src/test/compile-fail/keyword-do-as-identifier.rs b/src/test/compile-fail/keyword-do-as-identifier.rs
deleted file mode 100644 (file)
index 90f73f8..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn main() {
-    let do = "bar"; //~ error: ident
-}
diff --git a/src/test/compile-fail/keyword-final.rs b/src/test/compile-fail/keyword-final.rs
deleted file mode 100644 (file)
index 305ef0e..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 main() {
-    let final = (); //~ ERROR `final` is a reserved keyword
-}
diff --git a/src/test/compile-fail/keyword-mut-as-identifier.rs b/src/test/compile-fail/keyword-mut-as-identifier.rs
deleted file mode 100644 (file)
index b5d36e5..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// This file was auto-generated using 'src/etc/generate-keyword-tests.py mut'
-
-fn main() {
-    let mut = "foo"; //~ error: ident
-}
diff --git a/src/test/compile-fail/keyword-override.rs b/src/test/compile-fail/keyword-override.rs
deleted file mode 100644 (file)
index f70e6b9..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 main() {
-    let override = (); //~ ERROR `override` is a reserved keyword
-}
diff --git a/src/test/compile-fail/keyword-priv-as-identifier.rs b/src/test/compile-fail/keyword-priv-as-identifier.rs
deleted file mode 100644 (file)
index 7cbaeb9..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// This file was auto-generated using 'src/etc/generate-keyword-tests.py priv'
-
-fn main() {
-    let priv = "foo"; //~ error: ident
-}
diff --git a/src/test/compile-fail/keyword-ref-as-identifier.rs b/src/test/compile-fail/keyword-ref-as-identifier.rs
deleted file mode 100644 (file)
index 72af521..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// This file was auto-generated using 'src/etc/generate-keyword-tests.py ref'
-
-fn main() {
-    let ref = "foo"; //~ error: ident
-}
diff --git a/src/test/compile-fail/keyword-typeof.rs b/src/test/compile-fail/keyword-typeof.rs
deleted file mode 100644 (file)
index c428753..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn main() {
-    let typeof = (); //~ ERROR `typeof` is a reserved keyword
-}
index 61d55fd0964e3e3a72d2e12de8bfb68a55f78593..c7426fc6fc1b06cb3f36511390f7166bd02de36f 100644 (file)
@@ -13,8 +13,8 @@
 
 // error-pattern: requires `sized` lang_item
 
+#![feature(start, no_std)]
 #![no_std]
-#![feature(start)]
 
 #[start]
 fn start(argc: isize, argv: *const *const u8) -> isize {
diff --git a/src/test/compile-fail/lex-bad-char-literals.rs b/src/test/compile-fail/lex-bad-char-literals.rs
deleted file mode 100644 (file)
index fbe03e3..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-static c: char =
-    '\u539_' //~ ERROR: illegal character in numeric character escape
-    //~^ WARNING: \uABCD escapes are deprecated
-;
-
-static c2: char =
-    '\Uffffffff' //~ ERROR: illegal numeric character escape
-    //~^ WARNING: \uABCD escapes are deprecated
-;
-
-static c3: char =
-    '\x1' //~ ERROR: numeric character escape is too short
-;
-
-static c4: char =
-    '\u23q' //~  ERROR: illegal character in numeric character escape
-    //~^ WARNING: \uABCD escapes are deprecated
-;
-//~^^^ ERROR: numeric character escape is too short
-
-static s: &'static str =
-    "\x1" //~ ERROR: numeric character escape is too short
-;
-
-static s2: &'static str =
-    "\u23q" //~ ERROR: illegal character in numeric character escape
-    //~^ ERROR: numeric character escape is too short
-    //~^^ WARNING: \uABCD escapes are deprecated
-;
-
-static c: char =
-    '\●' //~ ERROR: unknown character escape
-;
-
-static s: &'static str =
-    "\●" //~ ERROR: unknown character escape
-;
-
-// THIS MUST BE LAST, since unterminated character constants kill the lexer
-
-static c: char =
-    '●  //~ ERROR: unterminated character constant
-;
diff --git a/src/test/compile-fail/lex-bad-token.rs b/src/test/compile-fail/lex-bad-token.rs
deleted file mode 100644 (file)
index d28d9a2..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// 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.
-
-● //~ ERROR: unknown start of token
index 519839ae2f4cb723e8413387ce387e46571a321d..e91e6efd1cbf07407b56460e907e16e6b0298b72 100644 (file)
@@ -8,11 +8,11 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(no_std)]
 #![no_std]
 #![allow(unused_variables)]
 #![allow(non_camel_case_types)]
 #![allow(non_upper_case_globals)]
-#![allow(missing_copy_implementations)]
 #![deny(dead_code)]
 #![feature(core)]
 
index 55103f10f2ce1cc80a19a5a576b74a4b1b8e9e68..3b96fd64fa200e8f3d397bd69e6283a4f066fdfc 100644 (file)
@@ -12,7 +12,6 @@
 // injected intrinsics by the compiler.
 #![deny(missing_docs)]
 #![allow(dead_code)]
-#![allow(missing_copy_implementations)]
 
 //! Some garbage docs for the crate here
 #![doc="More garbage"]
index ddba7b58afaab6e5ad68c5acc3a34cb95570c747..dcc82b8920ff5b51245b6fb52880011da181e6fb 100644 (file)
@@ -35,7 +35,7 @@ fn main() {
       _ => {}
     }
 
-    let x = |&: mut y: isize| 10; //~ ERROR: variable does not need to be mutable
+    let x = |mut y: isize| 10; //~ ERROR: variable does not need to be mutable
     fn what(mut foo: isize) {} //~ ERROR: variable does not need to be mutable
 
     // positive cases
@@ -65,7 +65,7 @@ fn what(mut foo: isize) {} //~ ERROR: variable does not need to be mutable
       _ => {}
     }
 
-    let x = |&mut: mut y: isize| y = 32;
+    let x = |mut y: isize| y = 32;
     fn nothing(mut foo: isize) { foo = 37; }
 
     // leading underscore should avoid the warning, just like the
index 6dcf1fdee83028c5a4ceec06c42b6b51ec1b2622..06af8ac8719e57b539496912b1a825860f4947f6 100644 (file)
@@ -16,14 +16,14 @@ pub fn opt_str0<'a>(maybestr: &'a Option<String>) -> &'a str {
     if maybestr.is_none() {
         "(none)"
     } else {
-        let s: &'a str = maybestr.as_ref().unwrap().as_slice();
+        let s: &'a str = maybestr.as_ref().unwrap();
         s
     }
 }
 
 pub fn opt_str1<'a>(maybestr: &'a Option<String>) -> &'a str {
     if maybestr.is_some() {
-        let s: &'a str = maybestr.as_ref().unwrap().as_slice();
+        let s: &'a str = maybestr.as_ref().unwrap();
         s
     } else {
         "(none)"
@@ -34,14 +34,14 @@ pub fn opt_str2<'a>(maybestr: &'a Option<String>) -> &'static str {
     if maybestr.is_none() {
         "(none)"
     } else {
-        let s: &'a str = maybestr.as_ref().unwrap().as_slice();
+        let s: &'a str = maybestr.as_ref().unwrap();
         s  //~ ERROR cannot infer an appropriate lifetime for automatic coercion due to conflicting
     }
 }
 
 pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {
     if maybestr.is_some() {
-        let s: &'a str = maybestr.as_ref().unwrap().as_slice();
+        let s: &'a str = maybestr.as_ref().unwrap();
         s  //~ ERROR cannot infer an appropriate lifetime for automatic coercion due to conflicting
     } else {
         "(none)"
index 1939df2877b82da4e20b754d739a593d3a6d42bc..1b5824964a8eb53b44a45bd5a82fb43af5e0bdc4 100644 (file)
@@ -15,7 +15,7 @@
 pub fn opt_str0<'a>(maybestr: &'a Option<String>) -> &'a str {
     match *maybestr {
         Some(ref s) => {
-            let s: &'a str = s.as_slice();
+            let s: &'a str = s;
             s
         }
         None => "(none)",
@@ -26,7 +26,7 @@ pub fn opt_str1<'a>(maybestr: &'a Option<String>) -> &'a str {
     match *maybestr {
         None => "(none)",
         Some(ref s) => {
-            let s: &'a str = s.as_slice();
+            let s: &'a str = s;
             s
         }
     }
@@ -36,7 +36,7 @@ pub fn opt_str2<'a>(maybestr: &'a Option<String>) -> &'static str {
     match *maybestr {
         None => "(none)",
         Some(ref s) => {
-            let s: &'a str = s.as_slice();
+            let s: &'a str = s;
             s
             //~^ ERROR cannot infer an appropriate lifetime
         }
@@ -46,7 +46,7 @@ pub fn opt_str2<'a>(maybestr: &'a Option<String>) -> &'static str {
 pub fn opt_str3<'a>(maybestr: &'a Option<String>) -> &'static str {
     match *maybestr {
         Some(ref s) => {
-            let s: &'a str = s.as_slice();
+            let s: &'a str = s;
             s
             //~^ ERROR cannot infer an appropriate lifetime
         }
diff --git a/src/test/compile-fail/macro-attribute.rs b/src/test/compile-fail/macro-attribute.rs
deleted file mode 100644 (file)
index 77ea0c9..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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.
-
-#[doc = $not_there] //~ error: unexpected token: `$`
-fn main() { }
-
diff --git a/src/test/compile-fail/macro-bad-delimiter-ident.rs b/src/test/compile-fail/macro-bad-delimiter-ident.rs
deleted file mode 100644 (file)
index 75f7b5d..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 main() {
-    foo! bar < //~ ERROR expected `(` or `{`, found `<`
-}
diff --git a/src/test/compile-fail/macro-keyword.rs b/src/test/compile-fail/macro-keyword.rs
deleted file mode 100644 (file)
index 9d4ec9c..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn macro() {  //~ ERROR `macro` is a reserved keyword
-}
-
-pub fn main() {
-}
diff --git a/src/test/compile-fail/macro-mismatched-delim-brace-paren.rs b/src/test/compile-fail/macro-mismatched-delim-brace-paren.rs
deleted file mode 100644 (file)
index d03698c..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// 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 main() {
-    foo! {
-        bar, "baz", 1, 2.0
-    ) //~ ERROR incorrect close delimiter
-}
diff --git a/src/test/compile-fail/macro-mismatched-delim-paren-brace.rs b/src/test/compile-fail/macro-mismatched-delim-paren-brace.rs
deleted file mode 100644 (file)
index d80f93d..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// 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 main() {
-    foo! (
-        bar, "baz", 1, 2.0
-    } //~ ERROR incorrect close delimiter
-}
diff --git a/src/test/compile-fail/macros-no-semicolon.rs b/src/test/compile-fail/macros-no-semicolon.rs
deleted file mode 100644 (file)
index 0e85551..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// 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 main() {
-    assert!(1 == 2)
-    assert!(3 == 4) //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `assert`
-    println!("hello");
-}
-
diff --git a/src/test/compile-fail/malformed-plugin-1.rs b/src/test/compile-fail/malformed-plugin-1.rs
new file mode 100644 (file)
index 0000000..254a797
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![plugin] //~ ERROR malformed plugin attribute
+
+fn main() {}
diff --git a/src/test/compile-fail/malformed-plugin-2.rs b/src/test/compile-fail/malformed-plugin-2.rs
new file mode 100644 (file)
index 0000000..884087b
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![plugin="bleh"] //~ ERROR malformed plugin attribute
+
+fn main() {}
diff --git a/src/test/compile-fail/malformed-plugin-3.rs b/src/test/compile-fail/malformed-plugin-3.rs
new file mode 100644 (file)
index 0000000..4885bb9
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![plugin(foo="bleh")] //~ ERROR malformed plugin attribute
+
+fn main() {}
diff --git a/src/test/compile-fail/match-arrows-block-then-binop.rs b/src/test/compile-fail/match-arrows-block-then-binop.rs
deleted file mode 100644 (file)
index b6b2313..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn main() {
-
-    match 0 {
-      0 => {
-      } + 5 //~ ERROR unexpected token: `+`
-    }
-}
diff --git a/src/test/compile-fail/match-vec-invalid.rs b/src/test/compile-fail/match-vec-invalid.rs
deleted file mode 100644 (file)
index 3e073d3..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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 main() {
-    let a = Vec::new();
-    match a {
-        [1, tail.., tail..] => {}, //~ ERROR: expected one of `!`, `,`, or `@`, found `..`
-        _ => ()
-    }
-}
index e2671552b43497b289ba9e4a5530ab250e54df5d..2c63438cbf3af4ef6dceb833fc4f9105251441d5 100644 (file)
@@ -11,7 +11,7 @@
 
 fn main() {
     let x: Vec<(isize, isize)> = Vec::new();
-    let x: &[(isize, isize)] = x.as_slice();
+    let x: &[(isize, isize)] = &x;
     match x {
         [a, (2, 3), _] => (),
         [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern
@@ -21,7 +21,7 @@ fn main() {
     let x: Vec<String> = vec!["foo".to_string(),
                               "bar".to_string(),
                               "baz".to_string()];
-    let x: &[String] = x.as_slice();
+    let x: &[String] = &x;
     match x {
         [a, _, _, ..] => { println!("{}", a); }
         [_, _, _, _, _] => { } //~ ERROR unreachable pattern
@@ -29,7 +29,7 @@ fn main() {
     }
 
     let x: Vec<char> = vec!('a', 'b', 'c');
-    let x: &[char] = x.as_slice();
+    let x: &[char] = &x;
     match x {
         ['a', 'b', 'c', _tail..] => {}
         ['a', 'b', 'c'] => {} //~ ERROR unreachable pattern
index bc4bfef4d48c45adfb9696e0bb8862230c441f57..ddc9081e33bb6f235a45a633d6cc65e6e6e32292 100644 (file)
@@ -10,7 +10,7 @@
 
 // compile-flags: --crate-type lib
 #![deny(missing_debug_implementations)]
-#![allow(unused, missing_copy_implementations)]
+#![allow(unused)]
 
 use std::fmt;
 
diff --git a/src/test/compile-fail/mod_file_disambig.rs b/src/test/compile-fail/mod_file_disambig.rs
deleted file mode 100644 (file)
index 48bd00a..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-mod mod_file_disambig_aux; //~ ERROR file for module `mod_file_disambig_aux` found at both
-
-fn main() {
-    assert_eq!(mod_file_aux::bar(), 10);
-}
diff --git a/src/test/compile-fail/mod_file_not_exist.rs b/src/test/compile-fail/mod_file_not_exist.rs
deleted file mode 100644 (file)
index bbf2152..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-mod not_a_real_file; //~ ERROR file not found for module `not_a_real_file`
-//~^ HELP name the file either not_a_real_file.rs or not_a_real_file/mod.rs inside the directory
-
-fn main() {
-    assert_eq!(mod_file_aux::bar(), 10);
-}
diff --git a/src/test/compile-fail/mod_file_not_owning.rs b/src/test/compile-fail/mod_file_not_owning.rs
deleted file mode 100644 (file)
index adbcedd..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// 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.
-
-// error-pattern: cannot declare a new module at this location
-
-mod mod_file_not_owning_aux1;
-
-fn main() {}
diff --git a/src/test/compile-fail/mod_file_with_path_attr.rs b/src/test/compile-fail/mod_file_with_path_attr.rs
deleted file mode 100644 (file)
index ff33004..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#[path = "not_a_real_file.rs"]
-mod m; //~ ERROR not_a_real_file.rs
-
-fn main() {
-    assert_eq!(m::foo(), 10);
-}
index d0eeebd02f8091aa0d4636fc741581a8f51d3e12..426d5fa29a02000aa657a87354dde4af4339e028 100644 (file)
@@ -33,15 +33,6 @@ impl Drop for D { fn drop(&mut self) { } }
     *recv = a;
 }
 
-#[rustc_move_fragments]
-pub fn test_extract_array_elem(a: [D; 3], i: usize) -> D {
-    //~^ ERROR                 parent_of_fragments: `$(local a)`
-    //~| ERROR                  assigned_leaf_path: `$(local i)`
-    //~| ERROR                     moved_leaf_path: `$(local a).[]`
-    //~| ERROR                    unmoved_fragment: `$(allbutone $(local a).[])`
-    a[i]
-}
-
 #[rustc_move_fragments]
 pub fn test_overwrite_array_elem(mut a: [D; 3], i: usize, d: D) {
     //~^ ERROR                 parent_of_fragments: `$(local mut a)`
@@ -53,48 +44,4 @@ impl Drop for D { fn drop(&mut self) { } }
     a[i] = d;
 }
 
-// FIXME (pnkfelix): Both test_move_array_then_overwrite_elem1 and
-// test_move_array_then_overwrite_elem2 illustrate a behavior that
-// we need to make illegal if we want to get rid of drop-flags.
-// See RFC PR 320 for more discussion.
-
-#[rustc_move_fragments]
-pub fn test_move_array_then_overwrite_elem1(mut a: [D; 3], i: usize, recv: &mut [D; 3], d: D) {
-    //~^ ERROR                 parent_of_fragments: `$(local mut a)`
-    //~| ERROR                 parent_of_fragments: `$(local recv)`
-    //~| ERROR                  assigned_leaf_path: `$(local recv).*`
-    //~| ERROR                  assigned_leaf_path: `$(local i)`
-    //~| ERROR                  assigned_leaf_path: `$(local d)`
-    //~| ERROR                     moved_leaf_path: `$(local d)`
-    //~| ERROR                  assigned_leaf_path: `$(local mut a).[]`
-    //~| ERROR                    unmoved_fragment: `$(allbutone $(local mut a).[])`
-
-    // This test covers the case where the array contents have been all moved away, but
-    // we still need to deal with new initializing writes into the array.
-    *recv = a;
-    a[i] = d;
-}
-
-#[rustc_move_fragments]
-pub fn test_move_array_then_overwrite_elem2(mut a: [D; 3], i: usize, j: usize,
-                                            recv: &mut [D; 3], d1: D, d2: D) {
-    //~^^ ERROR                parent_of_fragments: `$(local mut a)`
-    //~| ERROR                 parent_of_fragments: `$(local recv)`
-    //~| ERROR                  assigned_leaf_path: `$(local recv).*`
-    //~| ERROR                  assigned_leaf_path: `$(local i)`
-    //~| ERROR                  assigned_leaf_path: `$(local j)`
-    //~| ERROR                  assigned_leaf_path: `$(local d1)`
-    //~| ERROR                  assigned_leaf_path: `$(local d2)`
-    //~| ERROR                     moved_leaf_path: `$(local d1)`
-    //~| ERROR                     moved_leaf_path: `$(local d2)`
-    //~| ERROR                  assigned_leaf_path: `$(local mut a).[]`
-    //~| ERROR                    unmoved_fragment: `$(allbutone $(local mut a).[])`
-
-    // This test covers the case where the array contents have been all moved away, but
-    // we still need to deal with new initializing writes into the array.
-    *recv = a;
-    a[i] = d1;
-    a[j] = d2;
-}
-
 pub fn main() { }
diff --git a/src/test/compile-fail/move-into-dead-array-1.rs b/src/test/compile-fail/move-into-dead-array-1.rs
new file mode 100644 (file)
index 0000000..61ccb69
--- /dev/null
@@ -0,0 +1,25 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Ensure that we cannot move into an uninitialized fixed-size array.
+
+struct D { _x: u8 }
+
+fn d() -> D { D { _x: 0 } }
+
+fn main() {
+    foo(1);
+    foo(3);
+}
+
+fn foo(i: usize) {
+    let mut a: [D; 4];
+    a[i] = d();        //~ ERROR use of possibly uninitialized variable: `a`
+}
diff --git a/src/test/compile-fail/move-into-dead-array-2.rs b/src/test/compile-fail/move-into-dead-array-2.rs
new file mode 100644 (file)
index 0000000..d484837
--- /dev/null
@@ -0,0 +1,25 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Ensure that we cannot move into an uninitialized fixed-size array.
+
+struct D { _x: u8 }
+
+fn d() -> D { D { _x: 0 } }
+
+fn main() {
+    foo([d(), d(), d(), d()], 1);
+    foo([d(), d(), d(), d()], 3);
+}
+
+fn foo(mut a: [D; 4], i: usize) {
+    drop(a);
+    a[i] = d(); //~ ERROR use of moved value: `a`
+}
diff --git a/src/test/compile-fail/move-out-of-array-1.rs b/src/test/compile-fail/move-out-of-array-1.rs
new file mode 100644 (file)
index 0000000..148dec0
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Ensure that we cannot move out of a fixed-size array (especially
+// when the element type has a destructor).
+
+
+struct D { _x: u8 }
+
+impl Drop for D { fn drop(&mut self) { } }
+
+fn main() {
+    fn d() -> D { D { _x: 0 } }
+
+    let _d1 = foo([d(), d(), d(), d()], 1);
+    let _d3 = foo([d(), d(), d(), d()], 3);
+}
+
+fn foo(a: [D; 4], i: usize) -> D {
+    a[i] //~ ERROR cannot move out of type `[D; 4]`
+}
index c9f73e86a2c4609bbdef09487aa198f1f650030c..9ad44567a41f2371ba4510731b5137b843c419a1 100644 (file)
@@ -95,7 +95,7 @@ fn f110() {
 
 fn f120() {
     let mut x = vec!("hi".to_string(), "ho".to_string());
-    x.as_mut_slice().swap(0, 1);
+    x.swap(0, 1);
     touch(&x[0]);
     touch(&x[1]);
 }
diff --git a/src/test/compile-fail/multi-plugin-attr.rs b/src/test/compile-fail/multi-plugin-attr.rs
deleted file mode 100644 (file)
index 1d98cd2..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#[plugin]
-#[plugin]  //~ ERROR #[plugin] specified multiple times
-extern crate std;
-
-fn main() {}
diff --git a/src/test/compile-fail/multiline-comment-line-tracking.rs b/src/test/compile-fail/multiline-comment-line-tracking.rs
deleted file mode 100644 (file)
index 11abe67..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern:18:3
-
-/* 1
- * 2
- * 3
- */
-fn main() {
-  %; // parse error on line 18, but is reported on line 6 instead.
-}
diff --git a/src/test/compile-fail/multitrait.rs b/src/test/compile-fail/multitrait.rs
deleted file mode 100644 (file)
index f182eb8..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct S {
- y: isize
-}
-
-impl Cmp, ToString for S {
-//~^ ERROR: expected one of `(`, `+`, `::`, `<`, `for`, `where`, or `{`, found `,`
-  fn eq(&&other: S) { false }
-  fn to_string(&self) -> String { "hi".to_string() }
-}
diff --git a/src/test/compile-fail/mut-patterns.rs b/src/test/compile-fail/mut-patterns.rs
deleted file mode 100644 (file)
index cde05bc..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// Can't put mut in non-ident pattern
-
-pub fn main() {
-    struct Foo { x: isize }
-    let mut Foo { x: x } = Foo { x: 3 }; //~ ERROR: expected one of `:`, `;`, `=`, or `@`, found `{`
-}
diff --git a/src/test/compile-fail/new-unicode-escapes-1.rs b/src/test/compile-fail/new-unicode-escapes-1.rs
deleted file mode 100644 (file)
index f242283..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 fn main() {
-    let s = "\u{2603"; //~ ERROR unterminated unicode escape (needed a `}`)
-}
diff --git a/src/test/compile-fail/new-unicode-escapes-2.rs b/src/test/compile-fail/new-unicode-escapes-2.rs
deleted file mode 100644 (file)
index 5da8674..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 fn main() {
-    let s = "\u{260311111111}"; //~ ERROR overlong unicode escape (can have at most 6 hex digits)
-}
diff --git a/src/test/compile-fail/new-unicode-escapes-3.rs b/src/test/compile-fail/new-unicode-escapes-3.rs
deleted file mode 100644 (file)
index 7c64d02..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 fn main() {
-    let s = "\u{d805}"; //~ ERROR illegal unicode character escape
-}
diff --git a/src/test/compile-fail/new-unicode-escapes-4.rs b/src/test/compile-fail/new-unicode-escapes-4.rs
deleted file mode 100644 (file)
index ffc2b11..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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 fn main() {
-    let s = "\u{lol}"; //~ ERROR illegal character in unicode escape
-}
index fce72f507b6fc56ba3057978808134358709e7de..1dec049aed5e66ce262aa78ecf0917492e08db42 100644 (file)
@@ -36,20 +36,20 @@ fn main() {
       (t::b, t::b) => {}
     }
     let vec = vec!(Some(42), None, Some(21));
-    let vec: &[Option<isize>] = vec.as_slice();
+    let vec: &[Option<isize>] = &vec;
     match vec { //~ ERROR non-exhaustive patterns: `[]` not covered
         [Some(..), None, tail..] => {}
         [Some(..), Some(..), tail..] => {}
         [None] => {}
     }
     let vec = vec!(1);
-    let vec: &[isize] = vec.as_slice();
+    let vec: &[isize] = &vec;
     match vec {
         [_, tail..] => (),
         [] => ()
     }
     let vec = vec!(0.5f32);
-    let vec: &[f32] = vec.as_slice();
+    let vec: &[f32] = &vec;
     match vec { //~ ERROR non-exhaustive patterns: `[_, _, _, _]` not covered
         [0.1, 0.2, 0.3] => (),
         [0.1, 0.2] => (),
@@ -57,7 +57,7 @@ fn main() {
         [] => ()
     }
     let vec = vec!(Some(42), None, Some(21));
-    let vec: &[Option<isize>] = vec.as_slice();
+    let vec: &[Option<isize>] = &vec;
     match vec {
         [Some(..), None, tail..] => {}
         [Some(..), Some(..), tail..] => {}
diff --git a/src/test/compile-fail/not-a-pred.rs b/src/test/compile-fail/not-a-pred.rs
deleted file mode 100644 (file)
index 782c90a..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// error-pattern: lt
-
-fn f(a: isize, b: isize) : lt(a, b) { }
-
-fn lt(a: isize, b: isize) { }
-
-fn main() { let a: isize = 10; let b: isize = 23; check (lt(a, b)); f(a, b); }
diff --git a/src/test/compile-fail/omitted-arg-in-item-fn.rs b/src/test/compile-fail/omitted-arg-in-item-fn.rs
deleted file mode 100644 (file)
index 729b45d..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn foo(x) { //~ ERROR expected one of `!`, `:`, or `@`, found `)`
-}
diff --git a/src/test/compile-fail/paamayim-nekudotayim.rs b/src/test/compile-fail/paamayim-nekudotayim.rs
deleted file mode 100644 (file)
index 4d5473f..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// http://phpsadness.com/sad/1
-
-fn main() {
-    ::; //~ ERROR expected ident, found `;`
-}
index 6b6ab3f29701953fc326385f8be4464df2092077..82425d2c22708760bc5d67ecc4683615de8b1836 100644 (file)
@@ -32,6 +32,6 @@ fn main() {
     let foo = Foo { bar: [1u8, 2, 3, 4, 5], baz: 10i32 };
     unsafe {
         let oof: Oof<[u8; 5], i32> = mem::transmute(foo);
-        println!("{:?} {:?}", &oof.rab[], oof.zab);
+        println!("{:?} {:?}", &oof.rab[..], oof.zab);
     }
 }
diff --git a/src/test/compile-fail/parenthesized-box-expr-message.rs b/src/test/compile-fail/parenthesized-box-expr-message.rs
deleted file mode 100644 (file)
index 05bbaec..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// 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 main() {
-    box(1 + 1) //~ HELP perhaps you meant `box() (foo)` instead?
-    ; //~ ERROR expected expression, found `;`
-}
diff --git a/src/test/compile-fail/pat-range-bad-dots.rs b/src/test/compile-fail/pat-range-bad-dots.rs
deleted file mode 100644 (file)
index c52fb8c..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// 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 fn main() {
-    match 22 {
-        0 .. 3 => {} //~ ERROR expected one of `...`, `=>`, `if`, or `|`, found `..`
-        _ => {}
-    }
-}
diff --git a/src/test/compile-fail/pat-ref-enum.rs b/src/test/compile-fail/pat-ref-enum.rs
deleted file mode 100644 (file)
index 062d330..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn matcher(x: Option<isize>) {
-    match x {
-      ref Some(i) => {} //~ ERROR expected identifier, found enum pattern
-      None => {}
-    }
-}
-
-fn main() {}
diff --git a/src/test/compile-fail/plugin-extern-crate-attr-deprecated.rs b/src/test/compile-fail/plugin-extern-crate-attr-deprecated.rs
new file mode 100644 (file)
index 0000000..ccda5cb
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[plugin]  //~ ERROR #[plugin] on `extern crate` is deprecated
+//~^ HELP use a crate attribute instead, i.e. #![plugin(std)]
+extern crate std;
+
+fn main() {}
index b2ee62ddabe55939fc51ba02c3e7b0b35fd0087a..7ebbcc2809a5802a42cfc4d598ed1171c2038703 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(lang_items, start)]
+#![feature(lang_items, start, no_std)]
 #![no_std] // makes debugging this test *a lot* easier (during resolve)
 
 #[lang="sized"]
index b3d7321edabd5836b386c6e7afc9c6b4184446c7..7b4a2a3595bf701a5f5353009021aab92b0c9d16 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(start)]
+#![feature(start, no_std)]
 #![no_std] // makes debugging this test *a lot* easier (during resolve)
 
 // Test to make sure that globs don't leak in regular `use` statements.
index 245a9c21a6b2e9b9ecdf6cdf51ccbbf1803c3570..8c9de1fa25ce784f2b00af2ea95816170a5bbcda 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(start)]
+#![feature(start, no_std)]
 #![no_std] // makes debugging this test *a lot* easier (during resolve)
 
 // Test to make sure that private items imported through globs remain private
index e35089b8606c2e3dd01aec9f915d345f3085d9a8..bcb46663aa849da96e36e45d9275453948cdbff0 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(lang_items, start)]
+#![feature(lang_items, start, no_std)]
 #![no_std] // makes debugging this test *a lot* easier (during resolve)
 
 #[lang = "sized"] pub trait Sized {}
diff --git a/src/test/compile-fail/range-3.rs b/src/test/compile-fail/range-3.rs
deleted file mode 100644 (file)
index 78c575d..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// 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 range syntax - syntax errors.
-
-pub fn main() {
-    let r = 1..2..3;
-    //~^ ERROR expected one of `.`, `;`, or an operator, found `..`
-}
diff --git a/src/test/compile-fail/range-4.rs b/src/test/compile-fail/range-4.rs
deleted file mode 100644 (file)
index a3e27fb..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// 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 range syntax - syntax errors.
-
-pub fn main() {
-    let r = ..1..2;
-    //~^ ERROR expected one of `.`, `;`, or an operator, found `..`
-}
diff --git a/src/test/compile-fail/raw-byte-string-eof.rs b/src/test/compile-fail/raw-byte-string-eof.rs
deleted file mode 100644 (file)
index 83ea9db..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// 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 fn main() {
-    br##"a"#;  //~ unterminated raw string
-}
-
-
diff --git a/src/test/compile-fail/raw-byte-string-literals.rs b/src/test/compile-fail/raw-byte-string-literals.rs
deleted file mode 100644 (file)
index 7a3d1b2..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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 fn main() {
-    br"é";  //~ raw byte string must be ASCII
-    br##~"a"~##;  //~ only `#` is allowed in raw string delimitation
-}
-
-
diff --git a/src/test/compile-fail/raw-str-delim.rs b/src/test/compile-fail/raw-str-delim.rs
deleted file mode 100644 (file)
index 83afb33..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-static s: &'static str =
-    r#x"#"x# //~ ERROR only `#` is allowed in raw string delimitation; found illegal character
-;
diff --git a/src/test/compile-fail/raw-str-unbalanced.rs b/src/test/compile-fail/raw-str-unbalanced.rs
deleted file mode 100644 (file)
index 3403b28..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-static s: &'static str =
-    r#"
-      "## //~ ERROR expected one of `.`, `;`, or an operator, found `#`
-;
diff --git a/src/test/compile-fail/raw-str-unterminated.rs b/src/test/compile-fail/raw-str-unterminated.rs
deleted file mode 100644 (file)
index 4151cf3..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-static s: &'static str =
-    r#" string literal goes on
-        and on
-    //~^^ ERROR unterminated raw string
index 53f923e5061967a2c809eb103fa3d70d614fe29f..be42f0f0ed8837dd5f4c7d6c7b57d34098658554 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 fn main() {
-    let f = |&: 3: isize| println!("hello");
+    let f = |3: isize| println!("hello");
     //~^ ERROR refutable pattern in function argument: `_` not covered
     f(4);
 }
index 5b04fa3d87ca5e97c2492e2733a7e32e165d3471..9f35c636b4526e18a95dd3b3c22ffd1e52dd9cf1 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 fn call_rec<F>(mut f: F) -> usize where F: FnMut(usize) -> usize {
-    (|&mut: x| f(x))(call_rec(f)) //~ ERROR cannot move out of `f`
+    (|x| f(x))(call_rec(f)) //~ ERROR cannot move out of `f`
 }
 
 fn main() {}
index cdaa3468a463cd7792ae765e1fae1988292feba8..9418156ffcd086ee6560431c84ac400f9b42de33 100644 (file)
@@ -17,7 +17,7 @@ fn main() {
     {
         let c = 1;
         let c_ref = &c; //~ ERROR `c` does not live long enough
-        f = move |&mut: a: isize, b: isize| { a + b + *c_ref };
+        f = move |a: isize, b: isize| { a + b + *c_ref };
     }
 }
 
index fa76ab758ab568a96ab55e9adc7487a69c8c45ba..70d5fe83055d35bf9ad03437bbdc4aa0044de9ae 100644 (file)
@@ -16,7 +16,7 @@ struct dog {
 
 impl dog {
     pub fn chase_cat(&mut self) {
-        let _f = |&:| {
+        let _f = || {
             let p: &'static mut usize = &mut self.food; //~ ERROR cannot infer
             *p = 3us;
         };
index acc721f26b394f5f8d23d0cc795a668c154de095..74c2c6e584b437184c642b1d46e9d25b87dcc165 100644 (file)
@@ -8,8 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(lang_items, no_std)]
 #![no_std]
-#![feature(lang_items)]
 
 // Check that explicit region bounds are allowed on the various
 // nominal types (but not on other types) and that they are type
index 06768fa68804c8506d2260fa849cbd0453179703..abbefd254888b3b8d8264cf36955bb89a7b643da 100644 (file)
@@ -15,5 +15,5 @@ fn with_int(f: &mut FnMut(&isize)) {
 
 fn main() {
     let mut x: Option<&isize> = None;
-    with_int(&mut |&mut: y| x = Some(y));   //~ ERROR cannot infer
+    with_int(&mut |y| x = Some(y));   //~ ERROR cannot infer
 }
index f43d35c579e25721c22016b3d9ec878384a1a73f..323d5360029c581b44ddb3734bb98f2ce022df82 100644 (file)
@@ -35,5 +35,5 @@ pub fn set_desc(self, s: &str) -> Flag<'a> {
 fn main () {
     let f : argparse::Flag = argparse::flag("flag", "My flag");
     let updated_flag = f.set_desc("My new flag");
-    assert_eq!(updated_flag.desc.as_slice(), "My new flag");
+    assert_eq!(updated_flag.desc, "My new flag");
 }
diff --git a/src/test/compile-fail/regions-infer-paramd-method.rs b/src/test/compile-fail/regions-infer-paramd-method.rs
deleted file mode 100644 (file)
index ef331bb..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// ignore-test
-// ignored due to problems with by value self.
-
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// Here: foo is parameterized because it contains a method that
-// refers to self.
-
-trait foo<'a> {
-    fn self_int(self) -> &'a isize;
-
-    fn any_int(self) -> &isize;
-}
-
-struct with_foo<'a> {
-    f: @foo<'a>
-}
-
-trait set_foo_foo {
-    fn set_foo(&mut self, f: @foo);
-}
-
-impl<'a> set_foo_foo for with_foo<'a> {
-    fn set_foo(&mut self, f: @foo) {
-        self.f = f; //~ ERROR mismatched types: expected `@foo/&self`, found `@foo/&`
-    }
-}
-
-// Bar is not region parameterized.
-
-trait bar {
-    fn any_int(&self) -> &isize;
-}
-
-struct with_bar {
-    f: bar
-}
-
-trait set_foo_bar {
-    fn set_foo(&mut self, f: bar);
-}
-
-impl set_foo_bar for with_bar {
-    fn set_foo(&mut self, f: bar) {
-        self.f = f;
-    }
-}
-
-fn main() {}
diff --git a/src/test/compile-fail/regions-out-of-scope-slice.rs b/src/test/compile-fail/regions-out-of-scope-slice.rs
deleted file mode 100644 (file)
index c67c14d..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// ignore-test blk region isn't supported in the front-end
-
-fn foo(cond: bool) {
-    // Here we will infer a type that uses the
-    // region of the if stmt then block, but in the scope:
-    let mut x; //~ ERROR foo
-
-    if cond {
-        x = &'blk [1,2,3];
-    }
-}
-
-fn main() {}
index 3f722c9433bb263a0ec5ef38312a08d132ecfaaf..57ea607cbf623f0cdd5c0bc9b4475a4ab8afb7eb 100644 (file)
@@ -12,7 +12,7 @@ fn assert_send<T: Send>(_t: T) {}
 
 fn main() {
     let line = String::new();
-    match [line.as_slice()] { //~ ERROR `line` does not live long enough
+    match [&*line] { //~ ERROR `line` does not live long enough
         [ word ] => { assert_send(word); }
     }
 }
index 21586f78db3424afca54de42a9fb54149de8624f..2e3531a2e8f2637ab661aa159731172ea4263bca 100644 (file)
@@ -16,7 +16,7 @@ fn main() {
     // Unboxed closure case
     {
         let mut x = 0us;
-        let mut f = |&mut:| &mut x; //~ ERROR cannot infer
+        let mut f = || &mut x; //~ ERROR cannot infer
         let x = f();
         let y = f();
     }
index 3de137a9efbd71758c6bc87288126c7aea15f74f..3b8312a30190c2b1317a5e3710881b01f4070601 100644 (file)
@@ -10,6 +10,7 @@
 
 // Various examples of structs whose fields are not well-formed.
 
+#![feature(no_std)]
 #![no_std]
 #![allow(dead_code)]
 
diff --git a/src/test/compile-fail/regions-trait-2.rs b/src/test/compile-fail/regions-trait-2.rs
deleted file mode 100644 (file)
index 8b36e87..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// ignore-test #5723
-
-// Test that you cannot escape a reference
-// into a trait.
-
-struct ctxt { v: usize }
-
-trait get_ctxt {
-    fn get_ctxt(&self) -> &'a ctxt;
-}
-
-struct has_ctxt<'a> { c: &'a ctxt }
-
-impl<'a> get_ctxt for has_ctxt<'a> {
-    fn get_ctxt(&self) -> &'a ctxt { self.c }
-}
-
-fn make_gc() -> @get_ctxt  {
-    let ctxt = ctxt { v: 22us };
-    let hc = has_ctxt { c: &ctxt };
-    return @hc as @get_ctxt;
-    //~^ ERROR source contains reference
-}
-
-fn main() {
-    make_gc().get_ctxt().v;
-}
diff --git a/src/test/compile-fail/regions-trait-3.rs b/src/test/compile-fail/regions-trait-3.rs
deleted file mode 100644 (file)
index 8943abb..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// ignore-test
-// ignore'd due to problems with by-value self.
-
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-trait get_ctxt<'a> {
-    fn get_ctxt(self) -> &'a usize;
-}
-
-fn make_gc1(gc: @get_ctxt<'a>) -> @get_ctxt<'b>  {
-    return gc; //~ ERROR mismatched types: expected `@get_ctxt/&b`, found `@get_ctxt/&a`
-}
-
-struct Foo {
-    r: &'a usize
-}
-
-impl get_ctxt for Foo<'a> {
-    fn get_ctxt(&self) -> &'a usize { self.r }
-}
-
-fn make_gc2<'a,'b>(foo: Foo<'a>) -> @get_ctxt<'b>  {
-    return @foo as @get_ctxt; //~ ERROR cannot infer
-}
-
-fn main() {
-}
diff --git a/src/test/compile-fail/removed-syntax-closure-lifetime.rs b/src/test/compile-fail/removed-syntax-closure-lifetime.rs
deleted file mode 100644 (file)
index 0cea87d..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-type closure = Box<lt/fn()>; //~ ERROR expected one of `(`, `+`, `,`, `::`, `<`, or `>`, found `/`
diff --git a/src/test/compile-fail/removed-syntax-enum-newtype.rs b/src/test/compile-fail/removed-syntax-enum-newtype.rs
deleted file mode 100644 (file)
index b067cee..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-enum e = isize; //~ ERROR expected one of `<`, `where`, or `{`, found `=`
diff --git a/src/test/compile-fail/removed-syntax-extern-const.rs b/src/test/compile-fail/removed-syntax-extern-const.rs
deleted file mode 100644 (file)
index a0e1d04..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-extern {
-    const i: isize;
-    //~^ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `const`
-}
diff --git a/src/test/compile-fail/removed-syntax-field-let.rs b/src/test/compile-fail/removed-syntax-field-let.rs
deleted file mode 100644 (file)
index c871159..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct s {
-    let foo: (),
-    //~^  ERROR expected identifier, found keyword `let`
-    //~^^ ERROR expected `:`, found `foo`
-}
diff --git a/src/test/compile-fail/removed-syntax-field-semicolon.rs b/src/test/compile-fail/removed-syntax-field-semicolon.rs
deleted file mode 100644 (file)
index 9bb3c64..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct s {
-    bar: ();
-    //~^ ERROR expected `,`, or `}`, found `;`
-}
diff --git a/src/test/compile-fail/removed-syntax-fixed-vec.rs b/src/test/compile-fail/removed-syntax-fixed-vec.rs
deleted file mode 100644 (file)
index 0e8e20b..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-type v = [isize * 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `*`
diff --git a/src/test/compile-fail/removed-syntax-fn-pure.rs b/src/test/compile-fail/removed-syntax-fn-pure.rs
deleted file mode 100644 (file)
index d569ea2..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-pure fn f() {} //~ ERROR expected item, found `pure`
diff --git a/src/test/compile-fail/removed-syntax-fn-sigil.rs b/src/test/compile-fail/removed-syntax-fn-sigil.rs
deleted file mode 100644 (file)
index 83ebe7c..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn f() {
-    let x: fn~() = || (); //~ ERROR expected `(`, found `~`
-}
diff --git a/src/test/compile-fail/removed-syntax-larrow-init.rs b/src/test/compile-fail/removed-syntax-larrow-init.rs
deleted file mode 100644 (file)
index 1474cc9..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn removed_moves() {
-    let mut x = 0;
-    let y <- x;
-    //~^ ERROR expected one of `!`, `:`, `;`, `=`, or `@`, found `<-`
-}
diff --git a/src/test/compile-fail/removed-syntax-larrow-move.rs b/src/test/compile-fail/removed-syntax-larrow-move.rs
deleted file mode 100644 (file)
index 552c9f2..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn removed_moves() {
-    let mut x = 0;
-    let y = 0;
-    y <- x;
-    //~^ ERROR expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `<-`
-}
diff --git a/src/test/compile-fail/removed-syntax-mode.rs b/src/test/compile-fail/removed-syntax-mode.rs
deleted file mode 100644 (file)
index b02de5c..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn f(+x: isize) {} //~ ERROR unexpected token: `+`
diff --git a/src/test/compile-fail/removed-syntax-mut-vec-expr.rs b/src/test/compile-fail/removed-syntax-mut-vec-expr.rs
deleted file mode 100644 (file)
index 30302bb..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn f() {
-    let v = [mut 1, 2, 3, 4];
-    //~^  ERROR expected identifier, found keyword `mut`
-    //~^^ ERROR expected one of `!`, `,`, `.`, `::`, `;`, `]`, `{`, or an operator, found `1`
-}
diff --git a/src/test/compile-fail/removed-syntax-mut-vec-ty.rs b/src/test/compile-fail/removed-syntax-mut-vec-ty.rs
deleted file mode 100644 (file)
index 9a7570a..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-type v = [mut isize];
-    //~^  ERROR expected identifier, found keyword `mut`
-    //~^^ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `isize`
diff --git a/src/test/compile-fail/removed-syntax-ptr-lifetime.rs b/src/test/compile-fail/removed-syntax-ptr-lifetime.rs
deleted file mode 100644 (file)
index 44c65d9..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-type bptr = &lifetime/isize; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `<`, found `/`
diff --git a/src/test/compile-fail/removed-syntax-record.rs b/src/test/compile-fail/removed-syntax-record.rs
deleted file mode 100644 (file)
index ae5a685..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-type t = { f: () }; //~ ERROR expected type, found `{`
diff --git a/src/test/compile-fail/removed-syntax-static-fn.rs b/src/test/compile-fail/removed-syntax-static-fn.rs
deleted file mode 100644 (file)
index caf939e..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct S;
-
-impl S {
-    static fn f() {}
-    //~^ ERROR expected one of `extern`, `fn`, `pub`, `type`, `unsafe`, or `}`, found `static`
-}
diff --git a/src/test/compile-fail/removed-syntax-uniq-mut-expr.rs b/src/test/compile-fail/removed-syntax-uniq-mut-expr.rs
deleted file mode 100644 (file)
index c5559c4..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn f() {
-    let a_box = box mut 42;
-    //~^  ERROR expected identifier, found keyword `mut`
-    //~^^ ERROR expected one of `!`, `.`, `::`, `;`, `{`, or an operator, found `42`
-}
diff --git a/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs b/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs
deleted file mode 100644 (file)
index d1c2fc6..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-type mut_box = Box<mut isize>;
-    //~^  ERROR expected identifier, found keyword `mut`
-    //~^^ ERROR expected one of `(`, `+`, `,`, `::`, `<`, or `>`, found `isize`
diff --git a/src/test/compile-fail/removed-syntax-with-1.rs b/src/test/compile-fail/removed-syntax-with-1.rs
deleted file mode 100644 (file)
index c7f3104..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn removed_with() {
-    struct S {
-        foo: (),
-        bar: (),
-    }
-
-    let a = S { foo: (), bar: () };
-    let b = S { foo: () with a };
-    //~^ ERROR expected one of `,`, `.`, `}`, or an operator, found `with`
-}
diff --git a/src/test/compile-fail/removed-syntax-with-2.rs b/src/test/compile-fail/removed-syntax-with-2.rs
deleted file mode 100644 (file)
index 83c6897..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn removed_with() {
-    struct S {
-        foo: (),
-        bar: (),
-    }
-
-    let a = S { foo: (), bar: () };
-    let b = S { foo: (), with a };
-    //~^ ERROR expected `:`, found `a`
-}
index ae561878e9ba0dcbfa9f352bb8035c32ec81dc2a..7d252604883d6e12eb185e249389150a8c93ea2a 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(lang_items)]
+#![feature(lang_items, no_std)]
 #![no_std]
 
 #[lang="sized"] pub trait Sized {}
diff --git a/src/test/compile-fail/reserved-be.rs b/src/test/compile-fail/reserved-be.rs
deleted file mode 100644 (file)
index 386d53c..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn main() {
-    let be = 0;
-    //~^ ERROR `be` is a reserved keyword
-}
index 903760caf1a1eb64bf73184e490c8ed8e24e1d72..23ad5b09950effba47277fc56bf1533bb6b3f49e 100644 (file)
@@ -8,12 +8,15 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// Test slicing expr[..] is an error and gives a helpful error message.
+// Test slicing &expr[] is deprecated and gives a helpful error message.
+//
+// ignore-test
 
 struct Foo;
 
 fn main() {
     let x = Foo;
-    &x[..]; //~ ERROR incorrect slicing expression: `[..]`
-    //~^ NOTE use `&expr[]` to construct a slice of the whole of expr
+    &x[]; //~ WARNING deprecated slicing syntax: `[]`
+          //~^ NOTE use `&expr[..]` to construct a slice of the whole of expr
+          //~^^ ERROR cannot index a value of type `Foo`
 }
index 07162293565ed2c9e3f93e4d89521212497bda44..99dc3e68c8f796d47f78ea644932096619e7dfab 100644 (file)
@@ -14,7 +14,7 @@
 
 fn main() {
     let x = Foo;
-    &x[]; //~ ERROR cannot index a value of type `Foo`
+    &x[..]; //~ ERROR cannot index a value of type `Foo`
     &x[Foo..]; //~ ERROR cannot index a value of type `Foo`
     &x[..Foo]; //~ ERROR cannot index a value of type `Foo`
     &x[Foo..Foo]; //~ ERROR cannot index a value of type `Foo`
diff --git a/src/test/compile-fail/stable-features.rs b/src/test/compile-fail/stable-features.rs
new file mode 100644 (file)
index 0000000..30eb411
--- /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.
+
+// Testing that the stable_features lint catches use of stable
+// language and lib features.
+
+#![deny(stable_features)]
+#![feature(test_accepted_feature)] //~ ERROR this feature is stable
+#![feature(rust1)] //~ ERROR this feature is stable
+
+fn main() {
+    let _foo: Vec<()> = Vec::new();
+}
diff --git a/src/test/compile-fail/struct-literal-in-for.rs b/src/test/compile-fail/struct-literal-in-for.rs
deleted file mode 100644 (file)
index 4bb5d5e..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct Foo {
-    x: isize,
-}
-
-impl Foo {
-    fn hi(&self) -> bool {
-        true
-    }
-}
-
-fn main() {
-    for x in Foo {
-        x: 3    //~ ERROR expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `:`
-    }.hi() {
-        println!("yo");
-    }
-}
-
diff --git a/src/test/compile-fail/struct-literal-in-if.rs b/src/test/compile-fail/struct-literal-in-if.rs
deleted file mode 100644 (file)
index b2bc8a4..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct Foo {
-    x: isize,
-}
-
-impl Foo {
-    fn hi(&self) -> bool {
-        true
-    }
-}
-
-fn main() {
-    if Foo {
-        x: 3    //~ ERROR expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `:`
-    }.hi() {
-        println!("yo");
-    }
-}
-
diff --git a/src/test/compile-fail/struct-literal-in-match-discriminant.rs b/src/test/compile-fail/struct-literal-in-match-discriminant.rs
deleted file mode 100644 (file)
index e6948b7..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct Foo {
-    x: isize,
-}
-
-fn main() {
-    match Foo {
-        x: 3    //~ ERROR expected one of `!`, `=>`, `@`, `if`, or `|`, found `:`
-    } {
-        Foo {
-            x: x
-        } => {}
-    }
-}
-
diff --git a/src/test/compile-fail/struct-literal-in-while.rs b/src/test/compile-fail/struct-literal-in-while.rs
deleted file mode 100644 (file)
index 05fa3a8..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct Foo {
-    x: isize,
-}
-
-impl Foo {
-    fn hi(&self) -> bool {
-        true
-    }
-}
-
-fn main() {
-    while Foo {
-        x: 3    //~ ERROR expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `:`
-    }.hi() {
-        println!("yo");
-    }
-}
-
diff --git a/src/test/compile-fail/struct-no-fields-enumlike.rs b/src/test/compile-fail/struct-no-fields-enumlike.rs
deleted file mode 100644 (file)
index 379d310..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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(); //~ ERROR unit-like struct definition should be written as `struct Foo;`
-
-fn main() {}
diff --git a/src/test/compile-fail/struct-no-fields.rs b/src/test/compile-fail/struct-no-fields.rs
deleted file mode 100644 (file)
index ee853ad..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-struct Foo {}
-//~^ ERROR: unit-like struct definition should be written as `struct Foo;`
-
-fn main() {}
index 9c78d7ea2439aa782d689793c93dde9dd52c643b..7b426a4c0331545da4961f70a408d13627fdb7cd 100644 (file)
@@ -26,7 +26,7 @@ fn f(&self, x: &'static str) {
 
 fn main() {
     let person = "Fred".to_string();
-    let person: &str = person.as_slice();  //~ ERROR `person` does not live long enough
+    let person: &str = &person;  //~ ERROR `person` does not live long enough
     let s: Box<Trait<&'static str>> = box Struct { person: person };
 }
 
diff --git a/src/test/compile-fail/trait-keyword.rs b/src/test/compile-fail/trait-keyword.rs
deleted file mode 100644 (file)
index e60be6c..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-iface foo { } //~ ERROR iface
-
-fn main() {}
diff --git a/src/test/compile-fail/unbalanced-doublequote.rs b/src/test/compile-fail/unbalanced-doublequote.rs
deleted file mode 100644 (file)
index 789cc88..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-
-// error-pattern: unterminated double quote string
-
-
-fn main() {
-    "
-}
index ebdd3c3107f3f58f871b01adf5a6744e2e40fd4e..145b2bfaeddfd70185844d794d5b5dd50245eaa8 100644 (file)
 
 fn main() {
     let x = 0us;
-    move |&mut:| x = 1; //~ ERROR cannot assign
-    move |&mut:| set(&mut x); //~ ERROR cannot borrow
-    move |:| x = 1; //~ ERROR cannot assign
-    move |:| set(&mut x); //~ ERROR cannot borrow
-    |&mut:| x = 1; //~ ERROR cannot assign
+    move || x = 1; //~ ERROR cannot assign
+    move || set(&mut x); //~ ERROR cannot borrow
+    move || x = 1; //~ ERROR cannot assign
+    move || set(&mut x); //~ ERROR cannot borrow
+    || x = 1; //~ ERROR cannot assign
     // FIXME: this should be `cannot borrow` (issue #18330)
-    |&mut:| set(&mut x); //~ ERROR cannot assign
-    |:| x = 1; //~ ERROR cannot assign
+    || set(&mut x); //~ ERROR cannot assign
+    || x = 1; //~ ERROR cannot assign
     // FIXME: this should be `cannot borrow` (issue #18330)
-    |:| set(&mut x); //~ ERROR cannot assign
+    || set(&mut x); //~ ERROR cannot assign
 }
index 9d9667986949ead5c27afaf8560ed5cad542f254..98ac54de8ad78e6ec5279198210f5196745ebfda 100644 (file)
@@ -15,6 +15,6 @@
 fn main() {
     let _f = {
         let x = 0us;
-        |:| x //~ ERROR cannot infer an appropriate lifetime due to conflicting requirements
+        || x //~ ERROR cannot infer an appropriate lifetime due to conflicting requirements
     };
 }
diff --git a/src/test/compile-fail/unboxed-closure-sugar-used-on-struct-3.rs b/src/test/compile-fail/unboxed-closure-sugar-used-on-struct-3.rs
deleted file mode 100644 (file)
index d86f55d..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-// 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 parentheses form doesn't work in expression paths.
-
-struct Bar<A,R> {
-    f: A, r: R
-}
-
-impl<A,B> Bar<A,B> {
-    fn new() -> Bar<A,B> { panic!() }
-}
-
-fn bar() {
-    let b = Box::Bar::<isize,usize>::new(); // OK
-
-    let b = Box::Bar::()::new();
-    //~^ ERROR expected ident, found `(`
-}
-
-fn main() { }
-
index bb92e57d70c0e7d3bacbe73d91cf0d390cf3bbfe..0bdc261e8c88d35b08b1423a81326e63083dddfc 100644 (file)
@@ -15,6 +15,6 @@
 
 fn main() {
     let mut x = 0us;
-    let f = |:| x += 1;
+    let f = || x += 1;
     let _y = x; //~ ERROR cannot use `x` because it was mutably borrowed
 }
index ef6c439aeb89d97e0f0f522b165df59fc8f8a349..3dd5779914d06b63d26432eb66a69ab045c2ebd5 100644 (file)
@@ -23,7 +23,7 @@ fn doit<T,F>(val: T, f: &F)
 }
 
 pub fn main() {
-    doit(0, &|&: x, y| {
+    doit(0, &|x, y| {
         x.set(y); //~ ERROR cannot infer
     });
 }
index f7ac2274ffb3a60ce97863951a0911a9ea708e82..e1192b22485c6450dfc4f4d3e3ba03723408d3d6 100644 (file)
@@ -13,7 +13,7 @@
 use std::ops::FnMut;
 
 pub fn main() {
-    let mut f = |&mut: x: isize, y: isize| -> isize { x + y };
+    let mut f = |x: isize, y: isize| -> isize { x + y };
     let z = f(1us, 2);    //~ ERROR mismatched types
     println!("{}", z);
 }
diff --git a/src/test/compile-fail/unsized.rs b/src/test/compile-fail/unsized.rs
deleted file mode 100644 (file)
index 92dbea0..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// 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 syntax checks for `type` keyword.
-
-struct S1 for type; //~ ERROR expected `where`, `{`, `(`, or `;` after struct name, found `for`
-
-pub fn main() {
-}
index 87ea56c055350da70ec7481e6a826ebf8df43252..d4dc58864ad827d9e5ea28e426c7319d8beadc6b 100644 (file)
@@ -13,5 +13,5 @@
 fn main() {
     let mut x = 1;
     //~^ ERROR: variable does not need to be mutable
-    move|:| { println!("{}", x); };
+    move|| { println!("{}", x); };
 }
diff --git a/src/test/compile-fail/use-as-where-use-ends-with-mod-sep.rs b/src/test/compile-fail/use-as-where-use-ends-with-mod-sep.rs
deleted file mode 100644 (file)
index 524fd01..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use std::any:: as foo; //~ ERROR expected identifier, found keyword `as`
-//~^ ERROR: expected one of `::`, `;`, or `as`, found `foo`
diff --git a/src/test/compile-fail/use-ends-with-mod-sep.rs b/src/test/compile-fail/use-ends-with-mod-sep.rs
deleted file mode 100644 (file)
index a375a59..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use std::any::; //~ ERROR expected identifier or `{` or `*`, found `;`
diff --git a/src/test/compile-fail/use-mod-4.rs b/src/test/compile-fail/use-mod-4.rs
deleted file mode 100644 (file)
index a8b551b..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// 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 foo::self;
-//~^ ERROR expected identifier, found keyword `self`
-
-fn main() {}
-
diff --git a/src/test/compile-fail/variadic-ffi-1.rs b/src/test/compile-fail/variadic-ffi-1.rs
deleted file mode 100644 (file)
index 34846ab..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-extern {
-    fn printf(...); //~ ERROR: variadic function must be declared with at least one named argument
-    fn printf(..., foo: isize); //~ ERROR: `...` must be last in argument list for variadic function
-}
-
-fn main() {}
diff --git a/src/test/compile-fail/variadic-ffi-3.rs b/src/test/compile-fail/variadic-ffi-3.rs
deleted file mode 100644 (file)
index 331a452..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-fn foo(x: isize, ...) {
-    //~^ ERROR: only foreign functions are allowed to be variadic
-}
-
-fn main() {}
diff --git a/src/test/compile-fail/variadic-ffi-4.rs b/src/test/compile-fail/variadic-ffi-4.rs
deleted file mode 100644 (file)
index 62e985f..0000000
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-extern "C" fn foo(x: isize, ...) {
-    //~^ ERROR: only foreign functions are allowed to be variadic
-}
-
-fn main() {}
index baac192cbf0227fd3f8accf8b81ad1a92a9a7981..42df43934a89cd19499ccbea68bf528b32f3f4a8 100644 (file)
@@ -13,6 +13,7 @@
 // error-pattern: language item required, but not found: `stack_exhausted`
 // error-pattern: language item required, but not found: `eh_personality`
 
+#![feature(no_std)]
 #![no_std]
 
 extern crate core;
diff --git a/src/test/compile-fail/where-for-self-2.rs b/src/test/compile-fail/where-for-self-2.rs
new file mode 100644 (file)
index 0000000..cd52401
--- /dev/null
@@ -0,0 +1,33 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that we can quantify lifetimes outside a constraint (i.e., including
+// the self type) in a where clause. Specifically, test that implementing for a
+// specific lifetime is not enough to satisify the `for<'a> ...` constraint, which
+// should require *all* lifetimes.
+
+static X: &'static u32 = &42;
+
+trait Bar {
+    fn bar(&self);
+}
+
+impl Bar for &'static u32 {
+    fn bar(&self) {}
+}
+
+fn foo<T>(x: &T)
+    where for<'a> &'a T: Bar
+{}
+
+fn main() {
+    foo(&X);
+    //~^ error: `for<'a> Bar` is not implemented
+}
diff --git a/src/test/compile-fail/where-for-self.rs b/src/test/compile-fail/where-for-self.rs
new file mode 100644 (file)
index 0000000..8f447fa
--- /dev/null
@@ -0,0 +1,29 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that we can quantify lifetimes outside a constraint (i.e., including
+// the self type) in a where clause. Specifically, test that we cannot nest
+// quantification in constraints (to be clear, there is no reason this should not
+// we're testing we don't crash or do something stupid).
+
+trait Bar<'a> {
+    fn bar(&self);
+}
+
+impl<'a, 'b> Bar<'b> for &'a u32 {
+    fn bar(&self) {}
+}
+
+fn foo<T>(x: &T)
+    where for<'a> &'a T: for<'b> Bar<'b>
+    //~^ error: nested quantification of lifetimes
+{}
+
+fn main() {}
index 59428a2c06f5218e819b255cd04e57e59485d3ab..ea684b1d69c523b97f48d68a6c57c10d620d5e83 100644 (file)
@@ -51,7 +51,7 @@
 
 fn some_generic_fun<T1, T2>(a: T1, b: T2) -> (T2, T1) {
 
-    let closure = |&: x, y| {
+    let closure = |x, y| {
         zzz(); // #break
         (y, x)
     };
diff --git a/src/test/debuginfo/constant-in-match-pattern.rs b/src/test/debuginfo/constant-in-match-pattern.rs
new file mode 100644 (file)
index 0000000..487c69a
--- /dev/null
@@ -0,0 +1,92 @@
+// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-android: FIXME(#10381)
+// min-lldb-version: 310
+
+// compile-flags:-g
+
+#![allow(unused_variables)]
+#![allow(dead_code)]
+#![omit_gdb_pretty_printer_section]
+
+// This test makes sure that the compiler doesn't crash when trying to assign
+// debug locations to 'constant' patterns in match expressions.
+
+const CONSTANT: u64 = 3;
+
+struct Struct {
+    a: isize,
+    b: usize,
+}
+const STRUCT: Struct = Struct { a: 1, b: 2 };
+
+struct TupleStruct(u32);
+const TUPLE_STRUCT: TupleStruct = TupleStruct(4);
+
+enum Enum {
+    Variant1(char),
+    Variant2 { a: u8 },
+    Variant3
+}
+const VARIANT1: Enum = Enum::Variant1('v');
+const VARIANT2: Enum = Enum::Variant2 { a: 2 };
+const VARIANT3: Enum = Enum::Variant3;
+
+const STRING: &'static str = "String";
+
+fn main() {
+
+    match 1 {
+        CONSTANT => {}
+        _ => {}
+    };
+
+    // if let 3 = CONSTANT {}
+
+    match (Struct { a: 2, b: 2 }) {
+        STRUCT => {}
+        _ => {}
+    };
+
+    // if let STRUCT = STRUCT {}
+
+    match TupleStruct(3) {
+        TUPLE_STRUCT => {}
+        _ => {}
+    };
+
+    // if let TupleStruct(4) = TUPLE_STRUCT {}
+
+    match VARIANT3 {
+        VARIANT1 => {},
+        VARIANT2 => {},
+        VARIANT3 => {},
+        _ => {}
+    };
+
+    match (VARIANT3, VARIANT2) {
+        (VARIANT1, VARIANT3) => {},
+        (VARIANT2, VARIANT2) => {},
+        (VARIANT3, VARIANT1) => {},
+        _ => {}
+    };
+
+    // if let VARIANT1 = Enum::Variant3 {}
+    // if let VARIANT2 = Enum::Variant3 {}
+    // if let VARIANT3 = Enum::Variant3 {}
+
+    match "abc" {
+        STRING => {},
+        _ => {}
+    }
+
+    if let STRING = "def" {}
+}
index 5e04c81cefd7657000eb81bbd0625f5e11d2659b..fb4378d5e8beca68a11c3a6ec569ccb2c7dec547 100644 (file)
@@ -18,7 +18,7 @@
 
 // Nothing to do here really, just make sure it compiles. See issue #8513.
 fn main() {
-    let _ = |&:|();
+    let _ = ||();
     let _ = (1u..3).map(|_| 5);
 }
 
index f2d092216697ff25c543c4f380daff04703f4a23..6cb1218c1233a718f372ddcce6a4d93b7c7f111d 100644 (file)
@@ -79,7 +79,7 @@ fn main() {
     zzz(); // #break
     sentinel();
 
-    let closure = |&: x: int| {
+    let closure = |x: int| {
         zzz(); // #break
         sentinel();
 
index be4085b63abe51dcacd0261647af347d9aa1632b..ba660deeca01a25738224e848a5c2a05bd74d2e8 100644 (file)
@@ -80,7 +80,7 @@ fn main() {
     zzz(); // #break
     sentinel();
 
-    let unique_closure = |x:int| {
+    let unique_closure = |x:int| {
         zzz(); // #break
         sentinel();
 
index cb7e26327c3def2f52406095226ad97a03475a21..dd0d86bf742e6415adadd180bc6e836bfee08d05 100644 (file)
@@ -24,5 +24,5 @@ struct C { θ: u8 }
 
 fn main() {
     let x =  C { θ: 0 };
-    (|&: c: C| c.θ )(x);
+    (|c: C| c.θ )(x);
 }
index 24b6df4e8f1425abbdad1f1ab17ff20e9838b0b1..adc4711b49aa2367b040988f03b371e15bbd632f 100644 (file)
@@ -283,9 +283,9 @@ fn main() {
     let fixed_size_vec2 = ([0u, 1u, 2u], 0i16);
 
     let vec1 = vec![0u, 2u, 3u];
-    let slice1 = vec1.as_slice();
+    let slice1 = &*vec1;
     let vec2 = vec![Mod1::Variant2_2(Struct1)];
-    let slice2 = vec2.as_slice();
+    let slice2 = &*vec2;
 
     // Trait Objects
     let box_trait = (box 0) as Box<Trait1>;
@@ -322,8 +322,8 @@ fn main() {
     // how that maps to rustc's internal representation of these forms.
     // Once closures have reached their 1.0 form, the tests below should
     // probably be expanded.
-    let closure1 = (|&: x:isize| {}, 0u);
-    let closure2 = (|&: x:i8, y: f32| { (x as f32) + y }, 0u);
+    let closure1 = (|x:isize| {}, 0u);
+    let closure2 = (|x:i8, y: f32| { (x as f32) + y }, 0u);
 
     zzz(); // #break
 }
index d7831c983c05014781a8603c68ad91cab3e60d69..512df3605bfcdf2ef353c49a839d5555606a6d41 100644 (file)
@@ -101,10 +101,10 @@ fn main() {
     let struct_ref = &a_struct;
     let owned = box 6;
 
-    let mut closure = |&mut:| {
+    let mut closure = || {
         let closure_local = 8;
 
-        let mut nested_closure = |&mut:| {
+        let mut nested_closure = || {
             zzz(); // #break
             variable = constant + a_struct.a + struct_ref.a + *owned + closure_local;
         };
index 30a07ea46ddd3bcca1a7a46e478d54c34a9c28e5..b07c8ffde7f8ff1310340b9ed97459c6da046dd5 100644 (file)
@@ -61,7 +61,7 @@ fn main() {
 
     let owned = box 5;
 
-    let closure = move |:| {
+    let closure = move || {
         zzz(); // #break
         do_something(&constant, &a_struct.a, &*owned);
     };
@@ -73,7 +73,7 @@ fn main() {
     // The `self` argument of the following closure should be passed by value
     // to FnOnce::call_once(self, args), which gets translated a bit differently
     // than the regular case. Let's make sure this is supported too.
-    let immedate_env = move |:| {
+    let immedate_env = move || {
         zzz(); // #break
         return constant2;
     };
index 9daf6abba11436da90195a4c37f834dd5f548672..ee706c13634f0113aec3ea6ba1fa10d208807459 100644 (file)
@@ -94,7 +94,7 @@ fn main() {
     let owned = box 6;
 
     {
-        let mut first_closure = |&mut:| {
+        let mut first_closure = || {
             zzz(); // #break
             variable = constant + a_struct.a + struct_ref.a + *owned;
         };
@@ -103,7 +103,7 @@ fn main() {
     }
 
     {
-        let mut second_closure = |&mut:| {
+        let mut second_closure = || {
             zzz(); // #break
             variable = constant + a_struct.a + struct_ref.a + *owned;
         };
diff --git a/src/test/parse-fail/array-old-syntax-1.rs b/src/test/parse-fail/array-old-syntax-1.rs
new file mode 100644 (file)
index 0000000..71c57fe
--- /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.
+
+// Test that the old fixed length array syntax is a parsing error.
+
+fn main() {
+    let _x: [isize, ..3] = [0, 1, 2]; //~ ERROR
+}
diff --git a/src/test/parse-fail/associated-types-project-from-hrtb-explicit.rs b/src/test/parse-fail/associated-types-project-from-hrtb-explicit.rs
new file mode 100644 (file)
index 0000000..917c03f
--- /dev/null
@@ -0,0 +1,26 @@
+// 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 you can't use a higher-ranked trait bound inside of a qualified
+// path (just won't parse).
+
+pub trait Foo<T> {
+    type A;
+
+    fn get(&self, t: T) -> Self::A;
+}
+
+fn foo2<I>(x: <I as for<'x> Foo<&'x isize>>::A)
+    //~^ ERROR expected identifier, found keyword `for`
+    //~| ERROR expected one of `::` or `>`
+{
+}
+
+pub fn main() {}
diff --git a/src/test/parse-fail/attr-bad-meta.rs b/src/test/parse-fail/attr-bad-meta.rs
new file mode 100644 (file)
index 0000000..dbf2929
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:expected `]`
+
+// asterisk is bogus
+#[attr*]
+mod m {}
diff --git a/src/test/parse-fail/bad-match.rs b/src/test/parse-fail/bad-match.rs
new file mode 100644 (file)
index 0000000..33043ff
--- /dev/null
@@ -0,0 +1,19 @@
+// 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.
+
+// error-pattern: expected
+
+fn main() {
+  let isize x = 5;
+  match x;
+}
+
+fn main() {
+}
diff --git a/src/test/parse-fail/bad-name.rs b/src/test/parse-fail/bad-name.rs
new file mode 100644 (file)
index 0000000..b208c6f
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern: expected
+
+fn main() {
+  let x.y::<isize>.z foo;
+}
diff --git a/src/test/parse-fail/better-expected.rs b/src/test/parse-fail/better-expected.rs
new file mode 100644 (file)
index 0000000..e07f4b8
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 main() {
+    let x: [isize 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `3`
+}
diff --git a/src/test/parse-fail/bind-struct-early-modifiers.rs b/src/test/parse-fail/bind-struct-early-modifiers.rs
new file mode 100644 (file)
index 0000000..c358a21
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn main() {
+    struct Foo { x: isize }
+    match (Foo { x: 10 }) {
+        Foo { ref x: ref x } => {}, //~ ERROR expected `,`, found `:`
+        _ => {}
+    }
+}
diff --git a/src/test/parse-fail/byte-literals.rs b/src/test/parse-fail/byte-literals.rs
new file mode 100644 (file)
index 0000000..436078f
--- /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.
+
+
+// ignore-tidy-tab
+
+static FOO: u8 = b'\f';  //~ ERROR unknown byte escape
+
+pub fn main() {
+    b'\f';  //~ ERROR unknown byte escape
+    b'\x0Z';  //~ ERROR illegal character in numeric character escape: Z
+    b' ';  //~ ERROR byte constant must be escaped
+    b''';  //~ ERROR byte constant must be escaped
+    b'é';  //~ ERROR byte constant must be ASCII
+    b'a  //~ ERROR unterminated byte constant
+}
+
+
diff --git a/src/test/parse-fail/byte-string-literals.rs b/src/test/parse-fail/byte-string-literals.rs
new file mode 100644 (file)
index 0000000..ec67cdd
--- /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.
+
+
+// ignore-tidy-tab
+
+static FOO: &'static [u8] = b"\f";  //~ ERROR unknown byte escape
+
+pub fn main() {
+    b"\f";  //~ ERROR unknown byte escape
+    b"\x0Z";  //~ ERROR illegal character in numeric character escape: Z
+    b"é";  //~ ERROR byte constant must be ASCII
+    b"a  //~ ERROR unterminated double quote byte string
+}
+
+
diff --git a/src/test/parse-fail/circular_modules_hello.rs b/src/test/parse-fail/circular_modules_hello.rs
new file mode 100644 (file)
index 0000000..3bf8516
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-test: this is an auxiliary file for circular-modules-main.rs
+
+mod circular_modules_main;
+
+pub fn say_hello() {
+    println!("{}", circular_modules_main::hi_str());
+}
diff --git a/src/test/parse-fail/circular_modules_main.rs b/src/test/parse-fail/circular_modules_main.rs
new file mode 100644 (file)
index 0000000..ac5ec12
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[path = "circular_modules_hello.rs"]
+mod circular_modules_hello; //~ERROR: circular modules
+
+pub fn hi_str() -> String {
+  "Hi!".to_string()
+}
+
+fn main() {
+    circular_modules_hello::say_hello();
+}
diff --git a/src/test/parse-fail/class-implements-bad-trait.rs b/src/test/parse-fail/class-implements-bad-trait.rs
new file mode 100644 (file)
index 0000000..d709ffd
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:nonexistent
+class cat : nonexistent {
+  let meows: usize;
+  new(in_x : usize) { self.meows = in_x; }
+}
+
+fn main() {
+  let nyan = cat(0us);
+}
diff --git a/src/test/parse-fail/column-offset-1-based.rs b/src/test/parse-fail/column-offset-1-based.rs
new file mode 100644 (file)
index 0000000..621b480
--- /dev/null
@@ -0,0 +1,11 @@
+// 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.
+
+# //~ ERROR 11:1: 11:2 error: expected one of `!` or `[`, found `<eof>`
diff --git a/src/test/parse-fail/duplicate-visibility.rs b/src/test/parse-fail/duplicate-visibility.rs
new file mode 100644 (file)
index 0000000..b213730
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:unmatched visibility `pub`
+extern {
+    pub pub fn foo();
+}
diff --git a/src/test/parse-fail/empty-impl-semicolon.rs b/src/test/parse-fail/empty-impl-semicolon.rs
new file mode 100644 (file)
index 0000000..70c7d42
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+impl Foo; //~ ERROR expected one of `(`, `+`, `::`, `<`, `for`, `where`, or `{`, found `;`
diff --git a/src/test/parse-fail/extern-expected-fn-or-brace.rs b/src/test/parse-fail/extern-expected-fn-or-brace.rs
new file mode 100644 (file)
index 0000000..7d1110c
--- /dev/null
@@ -0,0 +1,14 @@
+// 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.
+
+// Verifies that the expected token errors for `extern crate` are
+// raised
+
+extern "C" mod foo; //~ERROR expected `{` or `fn`, found `mod`
diff --git a/src/test/parse-fail/extern-foreign-crate.rs b/src/test/parse-fail/extern-foreign-crate.rs
new file mode 100644 (file)
index 0000000..24b978b
--- /dev/null
@@ -0,0 +1,14 @@
+// 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.
+
+// Verifies that the expected token errors for `extern crate` are
+// raised
+
+extern crate foo {} //~ERROR expected `;`, found `{`
diff --git a/src/test/parse-fail/extern-no-fn.rs b/src/test/parse-fail/extern-no-fn.rs
new file mode 100644 (file)
index 0000000..69e2f3a
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+extern {
+    f(); //~ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `f`
+}
+
+fn main() {
+}
diff --git a/src/test/parse-fail/import-from-path.rs b/src/test/parse-fail/import-from-path.rs
new file mode 100644 (file)
index 0000000..ce91de7
--- /dev/null
@@ -0,0 +1,12 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:expected
+use foo::{bar}::baz
diff --git a/src/test/parse-fail/import-from-rename.rs b/src/test/parse-fail/import-from-rename.rs
new file mode 100644 (file)
index 0000000..ebd897a
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:expected
+
+use foo::{bar} as baz;
+
+mod foo {
+    pub fn bar() {}
+}
+
+fn main() {
+}
diff --git a/src/test/parse-fail/import-glob-path.rs b/src/test/parse-fail/import-glob-path.rs
new file mode 100644 (file)
index 0000000..b6bc53f
--- /dev/null
@@ -0,0 +1,12 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:expected
+use foo::*::bar
diff --git a/src/test/parse-fail/import-glob-rename.rs b/src/test/parse-fail/import-glob-rename.rs
new file mode 100644 (file)
index 0000000..fb400b6
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:expected
+
+use foo::* as baz;
+
+mod foo {
+    pub fn bar() {}
+}
+
+fn main() {
+}
diff --git a/src/test/parse-fail/issue-10392-2.rs b/src/test/parse-fail/issue-10392-2.rs
new file mode 100644 (file)
index 0000000..b077081
--- /dev/null
@@ -0,0 +1,18 @@
+// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct A { foo: isize }
+
+fn a() -> A { panic!() }
+
+fn main() {
+    let A { .., } = a(); //~ ERROR: expected `}`
+}
+
diff --git a/src/test/parse-fail/issue-10392.rs b/src/test/parse-fail/issue-10392.rs
new file mode 100644 (file)
index 0000000..3f8d26b
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct A { foo: isize }
+
+fn a() -> A { panic!() }
+
+fn main() {
+    let A { , } = a(); //~ ERROR: expected ident
+}
diff --git a/src/test/parse-fail/issue-10636-1.rs b/src/test/parse-fail/issue-10636-1.rs
new file mode 100644 (file)
index 0000000..bb020d5
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Obj { //~ NOTE: unclosed delimiter
+    member: usize
+) //~ ERROR: incorrect close delimiter
diff --git a/src/test/parse-fail/issue-10636-2.rs b/src/test/parse-fail/issue-10636-2.rs
new file mode 100644 (file)
index 0000000..a92ef24
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub fn trace_option(option: Option<isize>) {
+    option.map(|some| 42; //~ NOTE: unclosed delimiter
+} //~ ERROR: incorrect close delimiter
diff --git a/src/test/parse-fail/issue-14303-enum.rs b/src/test/parse-fail/issue-14303-enum.rs
new file mode 100644 (file)
index 0000000..a26b7fd
--- /dev/null
@@ -0,0 +1,14 @@
+// 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.
+
+enum X<'a, T, 'b> {
+//~^ ERROR lifetime parameters must be declared prior to type parameters
+    A(&'a T)
+}
diff --git a/src/test/parse-fail/issue-14303-fn-def.rs b/src/test/parse-fail/issue-14303-fn-def.rs
new file mode 100644 (file)
index 0000000..aaf9541
--- /dev/null
@@ -0,0 +1,12 @@
+// 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<'a, T, 'b>(x: &'a T) {}
+//~^ ERROR lifetime parameters must be declared prior to type parameters
diff --git a/src/test/parse-fail/issue-14303-fncall.rs b/src/test/parse-fail/issue-14303-fncall.rs
new file mode 100644 (file)
index 0000000..a7adaac
--- /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.
+
+fn main() {
+    (0..4)
+    .map(|x| x * 2)
+    .collect::<Vec<'a, usize, 'b>>()
+    //~^ ERROR lifetime parameters must be declared prior to type parameters
+}
diff --git a/src/test/parse-fail/issue-14303-impl.rs b/src/test/parse-fail/issue-14303-impl.rs
new file mode 100644 (file)
index 0000000..c4a0058
--- /dev/null
@@ -0,0 +1,14 @@
+// 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 X { x: isize }
+
+impl<'a, T, 'b> X {}
+//~^ ERROR lifetime parameters must be declared prior to type parameters
diff --git a/src/test/parse-fail/issue-14303-path.rs b/src/test/parse-fail/issue-14303-path.rs
new file mode 100644 (file)
index 0000000..30cc41c
--- /dev/null
@@ -0,0 +1,12 @@
+// 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 bar<'a, T>(x: mymodule::X<'a, T, 'b, 'c>) {}
+//~^ ERROR lifetime parameters must be declared prior to type parameters
diff --git a/src/test/parse-fail/issue-14303-struct.rs b/src/test/parse-fail/issue-14303-struct.rs
new file mode 100644 (file)
index 0000000..6edd808
--- /dev/null
@@ -0,0 +1,14 @@
+// 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 X<'a, T, 'b> {
+//~^ ERROR lifetime parameters must be declared prior to type parameters
+    x: &'a T
+}
diff --git a/src/test/parse-fail/issue-14303-trait.rs b/src/test/parse-fail/issue-14303-trait.rs
new file mode 100644 (file)
index 0000000..753acdd
--- /dev/null
@@ -0,0 +1,12 @@
+// 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<'a, T, 'b> {}
+//~^ ERROR lifetime parameters must be declared prior to type parameters
diff --git a/src/test/parse-fail/issue-15914.rs b/src/test/parse-fail/issue-15914.rs
new file mode 100644 (file)
index 0000000..45b3abf
--- /dev/null
@@ -0,0 +1,14 @@
+// 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 main() {
+    let ref
+        (); //~ ERROR expected identifier, found `(`
+}
diff --git a/src/test/parse-fail/issue-1655.rs b/src/test/parse-fail/issue-1655.rs
new file mode 100644 (file)
index 0000000..a8704f7
--- /dev/null
@@ -0,0 +1,21 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:expected one of `!` or `[`, found `vec`
+mod blade_runner {
+    #vec[doc(
+        brief = "Blade Runner is probably the best movie ever",
+        desc = "I like that in the world of Blade Runner it is always
+                raining, and that it's always night time. And Aliens
+                was also a really good movie.
+
+                Alien 3 was crap though."
+    )]
+}
diff --git a/src/test/parse-fail/issue-17904.rs b/src/test/parse-fail/issue-17904.rs
new file mode 100644 (file)
index 0000000..96ba712
--- /dev/null
@@ -0,0 +1,17 @@
+// 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 Baz<U> where U: Eq(U); //This is parsed as the new Fn* style parenthesis syntax.
+struct Baz<U> where U: Eq(U) -> R; // Notice this parses as well.
+struct Baz<U>(U) where U: Eq; // This rightfully signals no error as well.
+struct Foo<T> where T: Copy, (T); //~ ERROR unexpected token in `where` clause
+struct Bar<T> { x: T } where T: Copy //~ ERROR expected item, found `where`
+
+fn main() {}
diff --git a/src/test/parse-fail/issue-1802-1.rs b/src/test/parse-fail/issue-1802-1.rs
new file mode 100644 (file)
index 0000000..8ce99f5
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:no valid digits found for number
+fn main() {
+    log(error, 0b42);
+}
diff --git a/src/test/parse-fail/issue-19096.rs b/src/test/parse-fail/issue-19096.rs
new file mode 100644 (file)
index 0000000..90d2acb
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn main() {
+    let t = (42, 42);
+    t.0::<isize>; //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `::`
+}
diff --git a/src/test/parse-fail/issue-19398.rs b/src/test/parse-fail/issue-19398.rs
new file mode 100644 (file)
index 0000000..3a6d15e
--- /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 T {
+    extern "Rust" unsafe fn foo(); //~ ERROR expected `fn`, found `unsafe`
+}
+
+fn main() {}
diff --git a/src/test/parse-fail/issue-20711-2.rs b/src/test/parse-fail/issue-20711-2.rs
new file mode 100644 (file)
index 0000000..a6c4570
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo;
+
+impl Foo {
+    fn foo() {}
+
+    #[stable(feature = "rust1", since = "1.0.0")]
+} //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `}`
+
+fn main() {}
+
diff --git a/src/test/parse-fail/issue-20711.rs b/src/test/parse-fail/issue-20711.rs
new file mode 100644 (file)
index 0000000..3b329d7
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo;
+
+impl Foo {
+    #[stable(feature = "rust1", since = "1.0.0")]
+} //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `}`
+
+fn main() {}
diff --git a/src/test/parse-fail/issue-21153.rs b/src/test/parse-fail/issue-21153.rs
new file mode 100644 (file)
index 0000000..e2b6deb
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 MyTrait<T>: Iterator {
+    Item = T; //~ ERROR expected one of `extern`, `fn`, `pub`, `type`, or `unsafe`, found `Item`
+}
diff --git a/src/test/parse-fail/issue-2354-1.rs b/src/test/parse-fail/issue-2354-1.rs
new file mode 100644 (file)
index 0000000..d37837b
--- /dev/null
@@ -0,0 +1,12 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+static foo: isize = 2; } //~ ERROR incorrect close delimiter:
+
diff --git a/src/test/parse-fail/issue-2354.rs b/src/test/parse-fail/issue-2354.rs
new file mode 100644 (file)
index 0000000..cc219a6
--- /dev/null
@@ -0,0 +1,22 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn foo() { //~ HELP did you mean to close this delimiter?
+  match Some(x) {
+      Some(y) { panic!(); }
+      None    { panic!(); }
+}
+
+fn bar() {
+    let mut i = 0;
+    while (i < 1000) {}
+}
+
+fn main() {} //~ ERROR this file contains an un-closed delimiter
diff --git a/src/test/parse-fail/issue-3036.rs b/src/test/parse-fail/issue-3036.rs
new file mode 100644 (file)
index 0000000..16834f4
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Testing that semicolon tokens are printed correctly in errors
+
+fn main()
+{
+    let x = 3
+} //~ ERROR: expected one of `.`, `;`, or an operator, found `}`
diff --git a/src/test/parse-fail/issue-5806.rs b/src/test/parse-fail/issue-5806.rs
new file mode 100644 (file)
index 0000000..597366a
--- /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.
+
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[path = "../compile-fail"]
+mod foo; //~ ERROR: a directory
+
+fn main() {}
diff --git a/src/test/parse-fail/issue-6610.rs b/src/test/parse-fail/issue-6610.rs
new file mode 100644 (file)
index 0000000..166e91b
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+trait Foo { fn a() } //~ ERROR expected `;` or `{`, found `}`
+
+fn main() {}
diff --git a/src/test/parse-fail/keyword-abstract.rs b/src/test/parse-fail/keyword-abstract.rs
new file mode 100644 (file)
index 0000000..1f1360e
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 main() {
+    let abstract = (); //~ ERROR `abstract` is a reserved keyword
+}
diff --git a/src/test/parse-fail/keyword-do-as-identifier.rs b/src/test/parse-fail/keyword-do-as-identifier.rs
new file mode 100644 (file)
index 0000000..90f73f8
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn main() {
+    let do = "bar"; //~ error: ident
+}
diff --git a/src/test/parse-fail/keyword-final.rs b/src/test/parse-fail/keyword-final.rs
new file mode 100644 (file)
index 0000000..305ef0e
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 main() {
+    let final = (); //~ ERROR `final` is a reserved keyword
+}
diff --git a/src/test/parse-fail/keyword-mut-as-identifier.rs b/src/test/parse-fail/keyword-mut-as-identifier.rs
new file mode 100644 (file)
index 0000000..b5d36e5
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This file was auto-generated using 'src/etc/generate-keyword-tests.py mut'
+
+fn main() {
+    let mut = "foo"; //~ error: ident
+}
diff --git a/src/test/parse-fail/keyword-override.rs b/src/test/parse-fail/keyword-override.rs
new file mode 100644 (file)
index 0000000..f70e6b9
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 main() {
+    let override = (); //~ ERROR `override` is a reserved keyword
+}
diff --git a/src/test/parse-fail/keyword-priv-as-identifier.rs b/src/test/parse-fail/keyword-priv-as-identifier.rs
new file mode 100644 (file)
index 0000000..7cbaeb9
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This file was auto-generated using 'src/etc/generate-keyword-tests.py priv'
+
+fn main() {
+    let priv = "foo"; //~ error: ident
+}
diff --git a/src/test/parse-fail/keyword-ref-as-identifier.rs b/src/test/parse-fail/keyword-ref-as-identifier.rs
new file mode 100644 (file)
index 0000000..72af521
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This file was auto-generated using 'src/etc/generate-keyword-tests.py ref'
+
+fn main() {
+    let ref = "foo"; //~ error: ident
+}
diff --git a/src/test/parse-fail/keyword-typeof.rs b/src/test/parse-fail/keyword-typeof.rs
new file mode 100644 (file)
index 0000000..c428753
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn main() {
+    let typeof = (); //~ ERROR `typeof` is a reserved keyword
+}
diff --git a/src/test/parse-fail/lex-bad-char-literals.rs b/src/test/parse-fail/lex-bad-char-literals.rs
new file mode 100644 (file)
index 0000000..fbe03e3
--- /dev/null
@@ -0,0 +1,53 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+static c: char =
+    '\u539_' //~ ERROR: illegal character in numeric character escape
+    //~^ WARNING: \uABCD escapes are deprecated
+;
+
+static c2: char =
+    '\Uffffffff' //~ ERROR: illegal numeric character escape
+    //~^ WARNING: \uABCD escapes are deprecated
+;
+
+static c3: char =
+    '\x1' //~ ERROR: numeric character escape is too short
+;
+
+static c4: char =
+    '\u23q' //~  ERROR: illegal character in numeric character escape
+    //~^ WARNING: \uABCD escapes are deprecated
+;
+//~^^^ ERROR: numeric character escape is too short
+
+static s: &'static str =
+    "\x1" //~ ERROR: numeric character escape is too short
+;
+
+static s2: &'static str =
+    "\u23q" //~ ERROR: illegal character in numeric character escape
+    //~^ ERROR: numeric character escape is too short
+    //~^^ WARNING: \uABCD escapes are deprecated
+;
+
+static c: char =
+    '\●' //~ ERROR: unknown character escape
+;
+
+static s: &'static str =
+    "\●" //~ ERROR: unknown character escape
+;
+
+// THIS MUST BE LAST, since unterminated character constants kill the lexer
+
+static c: char =
+    '●  //~ ERROR: unterminated character constant
+;
diff --git a/src/test/parse-fail/lex-bad-token.rs b/src/test/parse-fail/lex-bad-token.rs
new file mode 100644 (file)
index 0000000..d28d9a2
--- /dev/null
@@ -0,0 +1,11 @@
+// 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.
+
+● //~ ERROR: unknown start of token
diff --git a/src/test/parse-fail/macro-attribute.rs b/src/test/parse-fail/macro-attribute.rs
new file mode 100644 (file)
index 0000000..77ea0c9
--- /dev/null
@@ -0,0 +1,13 @@
+// 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.
+
+#[doc = $not_there] //~ error: unexpected token: `$`
+fn main() { }
+
diff --git a/src/test/parse-fail/macro-bad-delimiter-ident.rs b/src/test/parse-fail/macro-bad-delimiter-ident.rs
new file mode 100644 (file)
index 0000000..75f7b5d
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 main() {
+    foo! bar < //~ ERROR expected `(` or `{`, found `<`
+}
diff --git a/src/test/parse-fail/macro-keyword.rs b/src/test/parse-fail/macro-keyword.rs
new file mode 100644 (file)
index 0000000..9d4ec9c
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn macro() {  //~ ERROR `macro` is a reserved keyword
+}
+
+pub fn main() {
+}
diff --git a/src/test/parse-fail/macro-mismatched-delim-brace-paren.rs b/src/test/parse-fail/macro-mismatched-delim-brace-paren.rs
new file mode 100644 (file)
index 0000000..d03698c
--- /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.
+
+fn main() {
+    foo! {
+        bar, "baz", 1, 2.0
+    ) //~ ERROR incorrect close delimiter
+}
diff --git a/src/test/parse-fail/macro-mismatched-delim-paren-brace.rs b/src/test/parse-fail/macro-mismatched-delim-paren-brace.rs
new file mode 100644 (file)
index 0000000..d80f93d
--- /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.
+
+fn main() {
+    foo! (
+        bar, "baz", 1, 2.0
+    } //~ ERROR incorrect close delimiter
+}
diff --git a/src/test/parse-fail/macros-no-semicolon.rs b/src/test/parse-fail/macros-no-semicolon.rs
new file mode 100644 (file)
index 0000000..0e85551
--- /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.
+
+fn main() {
+    assert!(1 == 2)
+    assert!(3 == 4) //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `assert`
+    println!("hello");
+}
+
diff --git a/src/test/parse-fail/match-arrows-block-then-binop.rs b/src/test/parse-fail/match-arrows-block-then-binop.rs
new file mode 100644 (file)
index 0000000..b6b2313
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn main() {
+
+    match 0 {
+      0 => {
+      } + 5 //~ ERROR unexpected token: `+`
+    }
+}
diff --git a/src/test/parse-fail/match-vec-invalid.rs b/src/test/parse-fail/match-vec-invalid.rs
new file mode 100644 (file)
index 0000000..3e073d3
--- /dev/null
@@ -0,0 +1,17 @@
+// 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 main() {
+    let a = Vec::new();
+    match a {
+        [1, tail.., tail..] => {}, //~ ERROR: expected one of `!`, `,`, or `@`, found `..`
+        _ => ()
+    }
+}
diff --git a/src/test/parse-fail/mod_file_disambig.rs b/src/test/parse-fail/mod_file_disambig.rs
new file mode 100644 (file)
index 0000000..48bd00a
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+mod mod_file_disambig_aux; //~ ERROR file for module `mod_file_disambig_aux` found at both
+
+fn main() {
+    assert_eq!(mod_file_aux::bar(), 10);
+}
diff --git a/src/test/parse-fail/mod_file_not_exist.rs b/src/test/parse-fail/mod_file_not_exist.rs
new file mode 100644 (file)
index 0000000..bbf2152
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+mod not_a_real_file; //~ ERROR file not found for module `not_a_real_file`
+//~^ HELP name the file either not_a_real_file.rs or not_a_real_file/mod.rs inside the directory
+
+fn main() {
+    assert_eq!(mod_file_aux::bar(), 10);
+}
diff --git a/src/test/parse-fail/mod_file_not_owning.rs b/src/test/parse-fail/mod_file_not_owning.rs
new file mode 100644 (file)
index 0000000..adbcedd
--- /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.
+
+// error-pattern: cannot declare a new module at this location
+
+mod mod_file_not_owning_aux1;
+
+fn main() {}
diff --git a/src/test/parse-fail/mod_file_with_path_attr.rs b/src/test/parse-fail/mod_file_with_path_attr.rs
new file mode 100644 (file)
index 0000000..ff33004
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[path = "not_a_real_file.rs"]
+mod m; //~ ERROR not_a_real_file.rs
+
+fn main() {
+    assert_eq!(m::foo(), 10);
+}
diff --git a/src/test/parse-fail/multiline-comment-line-tracking.rs b/src/test/parse-fail/multiline-comment-line-tracking.rs
new file mode 100644 (file)
index 0000000..11abe67
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern:18:3
+
+/* 1
+ * 2
+ * 3
+ */
+fn main() {
+  %; // parse error on line 18, but is reported on line 6 instead.
+}
diff --git a/src/test/parse-fail/multitrait.rs b/src/test/parse-fail/multitrait.rs
new file mode 100644 (file)
index 0000000..f182eb8
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct S {
+ y: isize
+}
+
+impl Cmp, ToString for S {
+//~^ ERROR: expected one of `(`, `+`, `::`, `<`, `for`, `where`, or `{`, found `,`
+  fn eq(&&other: S) { false }
+  fn to_string(&self) -> String { "hi".to_string() }
+}
diff --git a/src/test/parse-fail/mut-patterns.rs b/src/test/parse-fail/mut-patterns.rs
new file mode 100644 (file)
index 0000000..cde05bc
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Can't put mut in non-ident pattern
+
+pub fn main() {
+    struct Foo { x: isize }
+    let mut Foo { x: x } = Foo { x: 3 }; //~ ERROR: expected one of `:`, `;`, `=`, or `@`, found `{`
+}
diff --git a/src/test/parse-fail/new-unicode-escapes-1.rs b/src/test/parse-fail/new-unicode-escapes-1.rs
new file mode 100644 (file)
index 0000000..f242283
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 fn main() {
+    let s = "\u{2603"; //~ ERROR unterminated unicode escape (needed a `}`)
+}
diff --git a/src/test/parse-fail/new-unicode-escapes-2.rs b/src/test/parse-fail/new-unicode-escapes-2.rs
new file mode 100644 (file)
index 0000000..5da8674
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 fn main() {
+    let s = "\u{260311111111}"; //~ ERROR overlong unicode escape (can have at most 6 hex digits)
+}
diff --git a/src/test/parse-fail/new-unicode-escapes-3.rs b/src/test/parse-fail/new-unicode-escapes-3.rs
new file mode 100644 (file)
index 0000000..7c64d02
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 fn main() {
+    let s = "\u{d805}"; //~ ERROR illegal unicode character escape
+}
diff --git a/src/test/parse-fail/new-unicode-escapes-4.rs b/src/test/parse-fail/new-unicode-escapes-4.rs
new file mode 100644 (file)
index 0000000..ffc2b11
--- /dev/null
@@ -0,0 +1,13 @@
+// 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 fn main() {
+    let s = "\u{lol}"; //~ ERROR illegal character in unicode escape
+}
diff --git a/src/test/parse-fail/not-a-pred.rs b/src/test/parse-fail/not-a-pred.rs
new file mode 100644 (file)
index 0000000..782c90a
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// error-pattern: lt
+
+fn f(a: isize, b: isize) : lt(a, b) { }
+
+fn lt(a: isize, b: isize) { }
+
+fn main() { let a: isize = 10; let b: isize = 23; check (lt(a, b)); f(a, b); }
diff --git a/src/test/parse-fail/omitted-arg-in-item-fn.rs b/src/test/parse-fail/omitted-arg-in-item-fn.rs
new file mode 100644 (file)
index 0000000..729b45d
--- /dev/null
@@ -0,0 +1,12 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn foo(x) { //~ ERROR expected one of `!`, `:`, or `@`, found `)`
+}
diff --git a/src/test/parse-fail/paamayim-nekudotayim.rs b/src/test/parse-fail/paamayim-nekudotayim.rs
new file mode 100644 (file)
index 0000000..4d5473f
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// http://phpsadness.com/sad/1
+
+fn main() {
+    ::; //~ ERROR expected ident, found `;`
+}
diff --git a/src/test/parse-fail/parenthesized-box-expr-message.rs b/src/test/parse-fail/parenthesized-box-expr-message.rs
new file mode 100644 (file)
index 0000000..05bbaec
--- /dev/null
@@ -0,0 +1,14 @@
+// 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 main() {
+    box(1 + 1) //~ HELP perhaps you meant `box() (foo)` instead?
+    ; //~ ERROR expected expression, found `;`
+}
diff --git a/src/test/parse-fail/pat-range-bad-dots.rs b/src/test/parse-fail/pat-range-bad-dots.rs
new file mode 100644 (file)
index 0000000..c52fb8c
--- /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.
+
+pub fn main() {
+    match 22 {
+        0 .. 3 => {} //~ ERROR expected one of `...`, `=>`, `if`, or `|`, found `..`
+        _ => {}
+    }
+}
diff --git a/src/test/parse-fail/pat-ref-enum.rs b/src/test/parse-fail/pat-ref-enum.rs
new file mode 100644 (file)
index 0000000..062d330
--- /dev/null
@@ -0,0 +1,18 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn matcher(x: Option<isize>) {
+    match x {
+      ref Some(i) => {} //~ ERROR expected identifier, found enum pattern
+      None => {}
+    }
+}
+
+fn main() {}
diff --git a/src/test/parse-fail/range-3.rs b/src/test/parse-fail/range-3.rs
new file mode 100644 (file)
index 0000000..78c575d
--- /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.
+
+// Test range syntax - syntax errors.
+
+pub fn main() {
+    let r = 1..2..3;
+    //~^ ERROR expected one of `.`, `;`, or an operator, found `..`
+}
diff --git a/src/test/parse-fail/range-4.rs b/src/test/parse-fail/range-4.rs
new file mode 100644 (file)
index 0000000..a3e27fb
--- /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.
+
+// Test range syntax - syntax errors.
+
+pub fn main() {
+    let r = ..1..2;
+    //~^ ERROR expected one of `.`, `;`, or an operator, found `..`
+}
diff --git a/src/test/parse-fail/raw-byte-string-eof.rs b/src/test/parse-fail/raw-byte-string-eof.rs
new file mode 100644 (file)
index 0000000..83ea9db
--- /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.
+
+
+pub fn main() {
+    br##"a"#;  //~ unterminated raw string
+}
+
+
diff --git a/src/test/parse-fail/raw-byte-string-literals.rs b/src/test/parse-fail/raw-byte-string-literals.rs
new file mode 100644 (file)
index 0000000..7a3d1b2
--- /dev/null
@@ -0,0 +1,17 @@
+// 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 fn main() {
+    br"é";  //~ raw byte string must be ASCII
+    br##~"a"~##;  //~ only `#` is allowed in raw string delimitation
+}
+
+
diff --git a/src/test/parse-fail/raw-str-delim.rs b/src/test/parse-fail/raw-str-delim.rs
new file mode 100644 (file)
index 0000000..83afb33
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+static s: &'static str =
+    r#x"#"x# //~ ERROR only `#` is allowed in raw string delimitation; found illegal character
+;
diff --git a/src/test/parse-fail/raw-str-unbalanced.rs b/src/test/parse-fail/raw-str-unbalanced.rs
new file mode 100644 (file)
index 0000000..3403b28
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+static s: &'static str =
+    r#"
+      "## //~ ERROR expected one of `.`, `;`, or an operator, found `#`
+;
diff --git a/src/test/parse-fail/raw-str-unterminated.rs b/src/test/parse-fail/raw-str-unterminated.rs
new file mode 100644 (file)
index 0000000..4151cf3
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+static s: &'static str =
+    r#" string literal goes on
+        and on
+    //~^^ ERROR unterminated raw string
diff --git a/src/test/parse-fail/regions-infer-paramd-method.rs b/src/test/parse-fail/regions-infer-paramd-method.rs
new file mode 100644 (file)
index 0000000..ef331bb
--- /dev/null
@@ -0,0 +1,67 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-test
+// ignored due to problems with by value self.
+
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Here: foo is parameterized because it contains a method that
+// refers to self.
+
+trait foo<'a> {
+    fn self_int(self) -> &'a isize;
+
+    fn any_int(self) -> &isize;
+}
+
+struct with_foo<'a> {
+    f: @foo<'a>
+}
+
+trait set_foo_foo {
+    fn set_foo(&mut self, f: @foo);
+}
+
+impl<'a> set_foo_foo for with_foo<'a> {
+    fn set_foo(&mut self, f: @foo) {
+        self.f = f; //~ ERROR mismatched types: expected `@foo/&self`, found `@foo/&`
+    }
+}
+
+// Bar is not region parameterized.
+
+trait bar {
+    fn any_int(&self) -> &isize;
+}
+
+struct with_bar {
+    f: bar
+}
+
+trait set_foo_bar {
+    fn set_foo(&mut self, f: bar);
+}
+
+impl set_foo_bar for with_bar {
+    fn set_foo(&mut self, f: bar) {
+        self.f = f;
+    }
+}
+
+fn main() {}
diff --git a/src/test/parse-fail/regions-out-of-scope-slice.rs b/src/test/parse-fail/regions-out-of-scope-slice.rs
new file mode 100644 (file)
index 0000000..c67c14d
--- /dev/null
@@ -0,0 +1,23 @@
+// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-test blk region isn't supported in the front-end
+
+fn foo(cond: bool) {
+    // Here we will infer a type that uses the
+    // region of the if stmt then block, but in the scope:
+    let mut x; //~ ERROR foo
+
+    if cond {
+        x = &'blk [1,2,3];
+    }
+}
+
+fn main() {}
diff --git a/src/test/parse-fail/regions-trait-2.rs b/src/test/parse-fail/regions-trait-2.rs
new file mode 100644 (file)
index 0000000..8b36e87
--- /dev/null
@@ -0,0 +1,37 @@
+// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-test #5723
+
+// Test that you cannot escape a reference
+// into a trait.
+
+struct ctxt { v: usize }
+
+trait get_ctxt {
+    fn get_ctxt(&self) -> &'a ctxt;
+}
+
+struct has_ctxt<'a> { c: &'a ctxt }
+
+impl<'a> get_ctxt for has_ctxt<'a> {
+    fn get_ctxt(&self) -> &'a ctxt { self.c }
+}
+
+fn make_gc() -> @get_ctxt  {
+    let ctxt = ctxt { v: 22us };
+    let hc = has_ctxt { c: &ctxt };
+    return @hc as @get_ctxt;
+    //~^ ERROR source contains reference
+}
+
+fn main() {
+    make_gc().get_ctxt().v;
+}
diff --git a/src/test/parse-fail/regions-trait-3.rs b/src/test/parse-fail/regions-trait-3.rs
new file mode 100644 (file)
index 0000000..8943abb
--- /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.
+
+// ignore-test
+// ignore'd due to problems with by-value self.
+
+// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+trait get_ctxt<'a> {
+    fn get_ctxt(self) -> &'a usize;
+}
+
+fn make_gc1(gc: @get_ctxt<'a>) -> @get_ctxt<'b>  {
+    return gc; //~ ERROR mismatched types: expected `@get_ctxt/&b`, found `@get_ctxt/&a`
+}
+
+struct Foo {
+    r: &'a usize
+}
+
+impl get_ctxt for Foo<'a> {
+    fn get_ctxt(&self) -> &'a usize { self.r }
+}
+
+fn make_gc2<'a,'b>(foo: Foo<'a>) -> @get_ctxt<'b>  {
+    return @foo as @get_ctxt; //~ ERROR cannot infer
+}
+
+fn main() {
+}
diff --git a/src/test/parse-fail/removed-syntax-closure-lifetime.rs b/src/test/parse-fail/removed-syntax-closure-lifetime.rs
new file mode 100644 (file)
index 0000000..0cea87d
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+type closure = Box<lt/fn()>; //~ ERROR expected one of `(`, `+`, `,`, `::`, `<`, or `>`, found `/`
diff --git a/src/test/parse-fail/removed-syntax-enum-newtype.rs b/src/test/parse-fail/removed-syntax-enum-newtype.rs
new file mode 100644 (file)
index 0000000..b067cee
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+enum e = isize; //~ ERROR expected one of `<`, `where`, or `{`, found `=`
diff --git a/src/test/parse-fail/removed-syntax-extern-const.rs b/src/test/parse-fail/removed-syntax-extern-const.rs
new file mode 100644 (file)
index 0000000..a0e1d04
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+extern {
+    const i: isize;
+    //~^ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `const`
+}
diff --git a/src/test/parse-fail/removed-syntax-field-let.rs b/src/test/parse-fail/removed-syntax-field-let.rs
new file mode 100644 (file)
index 0000000..c871159
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct s {
+    let foo: (),
+    //~^  ERROR expected identifier, found keyword `let`
+    //~^^ ERROR expected `:`, found `foo`
+}
diff --git a/src/test/parse-fail/removed-syntax-field-semicolon.rs b/src/test/parse-fail/removed-syntax-field-semicolon.rs
new file mode 100644 (file)
index 0000000..9bb3c64
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct s {
+    bar: ();
+    //~^ ERROR expected `,`, or `}`, found `;`
+}
diff --git a/src/test/parse-fail/removed-syntax-fixed-vec.rs b/src/test/parse-fail/removed-syntax-fixed-vec.rs
new file mode 100644 (file)
index 0000000..0e8e20b
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+type v = [isize * 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `*`
diff --git a/src/test/parse-fail/removed-syntax-fn-pure.rs b/src/test/parse-fail/removed-syntax-fn-pure.rs
new file mode 100644 (file)
index 0000000..d569ea2
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pure fn f() {} //~ ERROR expected item, found `pure`
diff --git a/src/test/parse-fail/removed-syntax-fn-sigil.rs b/src/test/parse-fail/removed-syntax-fn-sigil.rs
new file mode 100644 (file)
index 0000000..83ebe7c
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn f() {
+    let x: fn~() = || (); //~ ERROR expected `(`, found `~`
+}
diff --git a/src/test/parse-fail/removed-syntax-larrow-init.rs b/src/test/parse-fail/removed-syntax-larrow-init.rs
new file mode 100644 (file)
index 0000000..1474cc9
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn removed_moves() {
+    let mut x = 0;
+    let y <- x;
+    //~^ ERROR expected one of `!`, `:`, `;`, `=`, or `@`, found `<-`
+}
diff --git a/src/test/parse-fail/removed-syntax-larrow-move.rs b/src/test/parse-fail/removed-syntax-larrow-move.rs
new file mode 100644 (file)
index 0000000..552c9f2
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn removed_moves() {
+    let mut x = 0;
+    let y = 0;
+    y <- x;
+    //~^ ERROR expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `<-`
+}
diff --git a/src/test/parse-fail/removed-syntax-mode.rs b/src/test/parse-fail/removed-syntax-mode.rs
new file mode 100644 (file)
index 0000000..b02de5c
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn f(+x: isize) {} //~ ERROR unexpected token: `+`
diff --git a/src/test/parse-fail/removed-syntax-mut-vec-expr.rs b/src/test/parse-fail/removed-syntax-mut-vec-expr.rs
new file mode 100644 (file)
index 0000000..30302bb
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn f() {
+    let v = [mut 1, 2, 3, 4];
+    //~^  ERROR expected identifier, found keyword `mut`
+    //~^^ ERROR expected one of `!`, `,`, `.`, `::`, `;`, `]`, `{`, or an operator, found `1`
+}
diff --git a/src/test/parse-fail/removed-syntax-mut-vec-ty.rs b/src/test/parse-fail/removed-syntax-mut-vec-ty.rs
new file mode 100644 (file)
index 0000000..9a7570a
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+type v = [mut isize];
+    //~^  ERROR expected identifier, found keyword `mut`
+    //~^^ ERROR expected one of `(`, `+`, `::`, `;`, `<`, or `]`, found `isize`
diff --git a/src/test/parse-fail/removed-syntax-ptr-lifetime.rs b/src/test/parse-fail/removed-syntax-ptr-lifetime.rs
new file mode 100644 (file)
index 0000000..44c65d9
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+type bptr = &lifetime/isize; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `<`, found `/`
diff --git a/src/test/parse-fail/removed-syntax-record.rs b/src/test/parse-fail/removed-syntax-record.rs
new file mode 100644 (file)
index 0000000..ae5a685
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+type t = { f: () }; //~ ERROR expected type, found `{`
diff --git a/src/test/parse-fail/removed-syntax-static-fn.rs b/src/test/parse-fail/removed-syntax-static-fn.rs
new file mode 100644 (file)
index 0000000..caf939e
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct S;
+
+impl S {
+    static fn f() {}
+    //~^ ERROR expected one of `extern`, `fn`, `pub`, `type`, `unsafe`, or `}`, found `static`
+}
diff --git a/src/test/parse-fail/removed-syntax-uniq-mut-expr.rs b/src/test/parse-fail/removed-syntax-uniq-mut-expr.rs
new file mode 100644 (file)
index 0000000..c5559c4
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn f() {
+    let a_box = box mut 42;
+    //~^  ERROR expected identifier, found keyword `mut`
+    //~^^ ERROR expected one of `!`, `.`, `::`, `;`, `{`, or an operator, found `42`
+}
diff --git a/src/test/parse-fail/removed-syntax-uniq-mut-ty.rs b/src/test/parse-fail/removed-syntax-uniq-mut-ty.rs
new file mode 100644 (file)
index 0000000..d1c2fc6
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+type mut_box = Box<mut isize>;
+    //~^  ERROR expected identifier, found keyword `mut`
+    //~^^ ERROR expected one of `(`, `+`, `,`, `::`, `<`, or `>`, found `isize`
diff --git a/src/test/parse-fail/removed-syntax-with-1.rs b/src/test/parse-fail/removed-syntax-with-1.rs
new file mode 100644 (file)
index 0000000..c7f3104
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn removed_with() {
+    struct S {
+        foo: (),
+        bar: (),
+    }
+
+    let a = S { foo: (), bar: () };
+    let b = S { foo: () with a };
+    //~^ ERROR expected one of `,`, `.`, `}`, or an operator, found `with`
+}
diff --git a/src/test/parse-fail/removed-syntax-with-2.rs b/src/test/parse-fail/removed-syntax-with-2.rs
new file mode 100644 (file)
index 0000000..83c6897
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn removed_with() {
+    struct S {
+        foo: (),
+        bar: (),
+    }
+
+    let a = S { foo: (), bar: () };
+    let b = S { foo: (), with a };
+    //~^ ERROR expected `:`, found `a`
+}
diff --git a/src/test/parse-fail/reserved-be.rs b/src/test/parse-fail/reserved-be.rs
new file mode 100644 (file)
index 0000000..386d53c
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn main() {
+    let be = 0;
+    //~^ ERROR `be` is a reserved keyword
+}
diff --git a/src/test/parse-fail/struct-literal-in-for.rs b/src/test/parse-fail/struct-literal-in-for.rs
new file mode 100644 (file)
index 0000000..4bb5d5e
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo {
+    x: isize,
+}
+
+impl Foo {
+    fn hi(&self) -> bool {
+        true
+    }
+}
+
+fn main() {
+    for x in Foo {
+        x: 3    //~ ERROR expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `:`
+    }.hi() {
+        println!("yo");
+    }
+}
+
diff --git a/src/test/parse-fail/struct-literal-in-if.rs b/src/test/parse-fail/struct-literal-in-if.rs
new file mode 100644 (file)
index 0000000..b2bc8a4
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo {
+    x: isize,
+}
+
+impl Foo {
+    fn hi(&self) -> bool {
+        true
+    }
+}
+
+fn main() {
+    if Foo {
+        x: 3    //~ ERROR expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `:`
+    }.hi() {
+        println!("yo");
+    }
+}
+
diff --git a/src/test/parse-fail/struct-literal-in-match-discriminant.rs b/src/test/parse-fail/struct-literal-in-match-discriminant.rs
new file mode 100644 (file)
index 0000000..e6948b7
--- /dev/null
@@ -0,0 +1,24 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo {
+    x: isize,
+}
+
+fn main() {
+    match Foo {
+        x: 3    //~ ERROR expected one of `!`, `=>`, `@`, `if`, or `|`, found `:`
+    } {
+        Foo {
+            x: x
+        } => {}
+    }
+}
+
diff --git a/src/test/parse-fail/struct-literal-in-while.rs b/src/test/parse-fail/struct-literal-in-while.rs
new file mode 100644 (file)
index 0000000..05fa3a8
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo {
+    x: isize,
+}
+
+impl Foo {
+    fn hi(&self) -> bool {
+        true
+    }
+}
+
+fn main() {
+    while Foo {
+        x: 3    //~ ERROR expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `:`
+    }.hi() {
+        println!("yo");
+    }
+}
+
diff --git a/src/test/parse-fail/struct-no-fields-enumlike.rs b/src/test/parse-fail/struct-no-fields-enumlike.rs
new file mode 100644 (file)
index 0000000..379d310
--- /dev/null
@@ -0,0 +1,13 @@
+// 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(); //~ ERROR unit-like struct definition should be written as `struct Foo;`
+
+fn main() {}
diff --git a/src/test/parse-fail/struct-no-fields.rs b/src/test/parse-fail/struct-no-fields.rs
new file mode 100644 (file)
index 0000000..ee853ad
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct Foo {}
+//~^ ERROR: unit-like struct definition should be written as `struct Foo;`
+
+fn main() {}
diff --git a/src/test/parse-fail/trait-keyword.rs b/src/test/parse-fail/trait-keyword.rs
new file mode 100644 (file)
index 0000000..e60be6c
--- /dev/null
@@ -0,0 +1,13 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+iface foo { } //~ ERROR iface
+
+fn main() {}
diff --git a/src/test/parse-fail/unbalanced-doublequote.rs b/src/test/parse-fail/unbalanced-doublequote.rs
new file mode 100644 (file)
index 0000000..789cc88
--- /dev/null
@@ -0,0 +1,17 @@
+// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+
+// error-pattern: unterminated double quote string
+
+
+fn main() {
+    "
+}
diff --git a/src/test/parse-fail/unboxed-closure-sugar-used-on-struct-3.rs b/src/test/parse-fail/unboxed-closure-sugar-used-on-struct-3.rs
new file mode 100644 (file)
index 0000000..d86f55d
--- /dev/null
@@ -0,0 +1,29 @@
+// 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 parentheses form doesn't work in expression paths.
+
+struct Bar<A,R> {
+    f: A, r: R
+}
+
+impl<A,B> Bar<A,B> {
+    fn new() -> Bar<A,B> { panic!() }
+}
+
+fn bar() {
+    let b = Box::Bar::<isize,usize>::new(); // OK
+
+    let b = Box::Bar::()::new();
+    //~^ ERROR expected ident, found `(`
+}
+
+fn main() { }
+
diff --git a/src/test/parse-fail/unsized.rs b/src/test/parse-fail/unsized.rs
new file mode 100644 (file)
index 0000000..92dbea0
--- /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.
+
+// Test syntax checks for `type` keyword.
+
+struct S1 for type; //~ ERROR expected `where`, `{`, `(`, or `;` after struct name, found `for`
+
+pub fn main() {
+}
diff --git a/src/test/parse-fail/use-as-where-use-ends-with-mod-sep.rs b/src/test/parse-fail/use-as-where-use-ends-with-mod-sep.rs
new file mode 100644 (file)
index 0000000..524fd01
--- /dev/null
@@ -0,0 +1,12 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::any:: as foo; //~ ERROR expected identifier, found keyword `as`
+//~^ ERROR: expected one of `::`, `;`, or `as`, found `foo`
diff --git a/src/test/parse-fail/use-ends-with-mod-sep.rs b/src/test/parse-fail/use-ends-with-mod-sep.rs
new file mode 100644 (file)
index 0000000..a375a59
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::any::; //~ ERROR expected identifier or `{` or `*`, found `;`
diff --git a/src/test/parse-fail/use-mod-4.rs b/src/test/parse-fail/use-mod-4.rs
new file mode 100644 (file)
index 0000000..a8b551b
--- /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.
+
+use foo::self;
+//~^ ERROR expected identifier, found keyword `self`
+
+fn main() {}
+
diff --git a/src/test/parse-fail/variadic-ffi-1.rs b/src/test/parse-fail/variadic-ffi-1.rs
new file mode 100644 (file)
index 0000000..34846ab
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+extern {
+    fn printf(...); //~ ERROR: variadic function must be declared with at least one named argument
+    fn printf(..., foo: isize); //~ ERROR: `...` must be last in argument list for variadic function
+}
+
+fn main() {}
diff --git a/src/test/parse-fail/variadic-ffi-3.rs b/src/test/parse-fail/variadic-ffi-3.rs
new file mode 100644 (file)
index 0000000..331a452
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+fn foo(x: isize, ...) {
+    //~^ ERROR: only foreign functions are allowed to be variadic
+}
+
+fn main() {}
diff --git a/src/test/parse-fail/variadic-ffi-4.rs b/src/test/parse-fail/variadic-ffi-4.rs
new file mode 100644 (file)
index 0000000..62e985f
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+extern "C" fn foo(x: isize, ...) {
+    //~^ ERROR: only foreign functions are allowed to be variadic
+}
+
+fn main() {}
index cc8337027b092e8a8cdbeca7f76bffe41bcb2340..60660d482742dfbbf0711db3110c92c2ad5eb9a9 100644 (file)
@@ -1,3 +1,4 @@
+#![feature(no_std)]
 #![no_std]
 #[prelude_import]
 use std::prelude::v1::*;
@@ -41,41 +42,41 @@ pub fn bar() {
 
 
     ((::std::fmt::format as
-         fn(core::fmt::Arguments<'_>) -> collections::string::String {std::fmt::format})(((::std::fmt::Arguments::new_v1
-                                                                                              as
-                                                                                              fn(&[&str], &[core::fmt::ArgumentV1<'_>]) -> core::fmt::Arguments<'_> {core::fmt::Arguments<'a>::new_v1})(({
-                                                                                                                                                                                                             static __STATIC_FMTSTR:
-                                                                                                                                                                                                                    &'static [&'static str]
-                                                                                                                                                                                                                    =
-                                                                                                                                                                                                                 (&([("test"
+         fn(core::fmt::Arguments<'_>) -> collections::string::String {collections::fmt::format})(((::std::fmt::Arguments::new_v1
+                                                                                                      as
+                                                                                                      fn(&[&str], &[core::fmt::ArgumentV1<'_>]) -> core::fmt::Arguments<'_> {core::fmt::Arguments<'a>::new_v1})(({
+                                                                                                                                                                                                                     static __STATIC_FMTSTR:
+                                                                                                                                                                                                                            &'static [&'static str]
+                                                                                                                                                                                                                            =
+                                                                                                                                                                                                                         (&([("test"
+                                                                                                                                                                                                                                 as
+                                                                                                                                                                                                                                 &'static str)]
+                                                                                                                                                                                                                               as
+                                                                                                                                                                                                                               [&'static str; 1])
+                                                                                                                                                                                                                             as
+                                                                                                                                                                                                                             &'static [&'static str; 1]);
+                                                                                                                                                                                                                     (__STATIC_FMTSTR
                                                                                                                                                                                                                          as
-                                                                                                                                                                                                                         &'static str)]
-                                                                                                                                                                                                                       as
-                                                                                                                                                                                                                       [&'static str; 1])
-                                                                                                                                                                                                                     as
-                                                                                                                                                                                                                     &'static [&'static str; 1]);
-                                                                                                                                                                                                             (__STATIC_FMTSTR
-                                                                                                                                                                                                                 as
-                                                                                                                                                                                                                 &'static [&'static str])
-                                                                                                                                                                                                         }
-                                                                                                                                                                                                            as
-                                                                                                                                                                                                            &[&str]),
-                                                                                                                                                                                                        (&(match (()
-                                                                                                                                                                                                                     as
-                                                                                                                                                                                                                     ())
-                                                                                                                                                                                                               {
-                                                                                                                                                                                                               ()
-                                                                                                                                                                                                               =>
-                                                                                                                                                                                                               ([]
-                                                                                                                                                                                                                   as
-                                                                                                                                                                                                                   [core::fmt::ArgumentV1<'_>; 0]),
-                                                                                                                                                                                                           }
-                                                                                                                                                                                                              as
-                                                                                                                                                                                                              [core::fmt::ArgumentV1<'_>; 0])
-                                                                                                                                                                                                            as
-                                                                                                                                                                                                            &[core::fmt::ArgumentV1<'_>; 0]))
-                                                                                             as
-                                                                                             core::fmt::Arguments<'_>))
+                                                                                                                                                                                                                         &'static [&'static str])
+                                                                                                                                                                                                                 }
+                                                                                                                                                                                                                    as
+                                                                                                                                                                                                                    &[&str]),
+                                                                                                                                                                                                                (&(match (()
+                                                                                                                                                                                                                             as
+                                                                                                                                                                                                                             ())
+                                                                                                                                                                                                                       {
+                                                                                                                                                                                                                       ()
+                                                                                                                                                                                                                       =>
+                                                                                                                                                                                                                       ([]
+                                                                                                                                                                                                                           as
+                                                                                                                                                                                                                           [core::fmt::ArgumentV1<'_>; 0]),
+                                                                                                                                                                                                                   }
+                                                                                                                                                                                                                      as
+                                                                                                                                                                                                                      [core::fmt::ArgumentV1<'_>; 0])
+                                                                                                                                                                                                                    as
+                                                                                                                                                                                                                    &[core::fmt::ArgumentV1<'_>; 0]))
+                                                                                                     as
+                                                                                                     core::fmt::Arguments<'_>))
         as collections::string::String);
 }
 pub type Foo = [i32; (3us as usize)];
index 0cb73bc98a45aec9b71a07250abe3bad25a32f75..72e9c4849c62922f2c688956447807c30e06e0a7 100644 (file)
@@ -29,12 +29,12 @@ fn main() {
            idx as uint);
 
     // This should panic.
-    println!("ov3 0x%x",  x.as_slice()[idx]);
+    println!("ov3 0x%x",  x[idx]);
 }
 
 #[cfg(any(target_arch="x86_64", target_arch = "aarch64"))]
 fn main() {
     // This version just panics anyways, for symmetry on 64-bit hosts.
     let x = vec!(1u,2u,3u);
-    error!("ov3 0x%x",  x.as_slice()[200]);
+    error!("ov3 0x%x",  x[200]);
 }
diff --git a/src/test/run-make/alloc-extern-crates/Makefile b/src/test/run-make/alloc-extern-crates/Makefile
new file mode 100644 (file)
index 0000000..b8c5237
--- /dev/null
@@ -0,0 +1,5 @@
+-include ../tools.mk
+
+all:
+       $(RUSTC) fakealloc.rs
+       $(RUSTC) ../../../liballoc/lib.rs --cfg feature=\"external_crate\" --extern external=$(TMPDIR)/$(shell $(RUSTC) --print file-names fakealloc.rs)
diff --git a/src/test/run-make/alloc-extern-crates/fakealloc.rs b/src/test/run-make/alloc-extern-crates/fakealloc.rs
new file mode 100644 (file)
index 0000000..6d30956
--- /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.
+
+#![crate_type = "rlib"]
+#![feature(no_std, core)]
+#![no_std]
+extern crate core;
+
+
+#[inline]
+pub unsafe fn allocate(_size: usize, _align: usize) -> *mut u8 { 0 as *mut u8 }
+
+#[inline]
+pub unsafe fn deallocate(_ptr: *mut u8, _old_size: usize, _align: usize) { }
+
+#[inline]
+pub unsafe fn reallocate(_ptr: *mut u8, _old_size: usize, _size: usize, _align: usize) -> *mut u8 {
+    0 as *mut u8
+}
+
+#[inline]
+pub unsafe fn reallocate_inplace(_ptr: *mut u8, old_size: usize, _size: usize,
+                                    _align: usize) -> usize { old_size }
+
+#[inline]
+pub fn usable_size(size: usize, _align: usize) -> usize { size }
+
+#[inline]
+pub fn stats_print() { }
index 9fe07f82f9ed1495b13e4e4dcd2e092115b01b25..113717a776a99f8f533c6d77622170a747568e35 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 int foo() { return 0; }
index 9fe07f82f9ed1495b13e4e4dcd2e092115b01b25..113717a776a99f8f533c6d77622170a747568e35 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 int foo() { return 0; }
index bb4036b06e13b79a32ec78ae04db97590f54b2cc..5729d411c5bcd9a974e321a4a535e0b08c7dfc0b 100644 (file)
@@ -1,3 +1,4 @@
+// ignore-license
 void foo();
 
 int main() {
index bb4036b06e13b79a32ec78ae04db97590f54b2cc..5729d411c5bcd9a974e321a4a535e0b08c7dfc0b 100644 (file)
@@ -1,3 +1,4 @@
+// ignore-license
 void foo();
 
 int main() {
index 9fe07f82f9ed1495b13e4e4dcd2e092115b01b25..113717a776a99f8f533c6d77622170a747568e35 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 int foo() { return 0; }
index 9fe07f82f9ed1495b13e4e4dcd2e092115b01b25..113717a776a99f8f533c6d77622170a747568e35 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 int foo() { return 0; }
index f7c581172e2fe7069c3a32083ea771703bb97870..c8156b95dcfcb4d696db4a2f108a530b31a28f36 100644 (file)
@@ -17,8 +17,8 @@
 
 fn main() {
     let args = os::args();
-    let rustc = args[1].as_slice();
-    let tmpdir = Path::new(args[2].as_slice());
+    let rustc = &args[1];
+    let tmpdir = Path::new(&args[2]);
 
     let main_file = tmpdir.join("broken.rs");
     let _ = File::create(&main_file).unwrap()
@@ -31,12 +31,12 @@ fn main() {
     // can't exec it directly
     let result = Command::new("sh")
         .arg("-c")
-        .arg(format!("{} {}",
-                     rustc,
-                     main_file.as_str()
-                     .unwrap()).as_slice())
+        .arg(&format!("{} {}",
+                      rustc,
+                      main_file.as_str()
+                      .unwrap()))
         .output().unwrap();
-    let err = String::from_utf8_lossy(result.error.as_slice());
+    let err = String::from_utf8_lossy(&result.error);
 
     // positive test so that this test will be updated when the
     // compiler changes.
diff --git a/src/test/run-make/error-found-staticlib-instead-crate/Makefile b/src/test/run-make/error-found-staticlib-instead-crate/Makefile
new file mode 100644 (file)
index 0000000..46be238
--- /dev/null
@@ -0,0 +1,5 @@
+-include ../tools.mk
+
+all:
+       $(RUSTC) foo.rs --crate-type staticlib
+       $(RUSTC) bar.rs 2>&1 | grep "error: found staticlib"
diff --git a/src/test/run-make/error-found-staticlib-instead-crate/bar.rs b/src/test/run-make/error-found-staticlib-instead-crate/bar.rs
new file mode 100644 (file)
index 0000000..5ab3e5e
--- /dev/null
@@ -0,0 +1,15 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+extern crate foo;
+
+fn main() {
+    foo::foo();
+}
diff --git a/src/test/run-make/error-found-staticlib-instead-crate/foo.rs b/src/test/run-make/error-found-staticlib-instead-crate/foo.rs
new file mode 100644 (file)
index 0000000..222d98a
--- /dev/null
@@ -0,0 +1,11 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub fn foo() {}
index f23dd1eb1462cffe054ec7165139c4bf4c71fd7d..f9faef64afc41a519832a2372d48e7cea401fad4 100644 (file)
@@ -1,16 +1,17 @@
+// ignore-license
 #include <stdint.h>
 
 typedef struct TestStruct {
-       uint8_t x;
-       int32_t y;
+        uint8_t x;
+        int32_t y;
 } TestStruct;
 
 typedef int callback(TestStruct s);
 
 uint32_t call(callback *c) {
-       TestStruct s;
-       s.x = 'a';
-       s.y = 3;
+        TestStruct s;
+        s.x = 'a';
+        s.y = 3;
 
-       return c(s);
+        return c(s);
 }
index 8d93917ade03ea4f8d1c67e8b54a80b725341abb..1a9855dedec490f85bcec3c5efc8212d19f44fb6 100644 (file)
@@ -1,8 +1,9 @@
+// ignore-license
 #include <stdint.h>
 
 uint32_t foo();
 uint32_t bar();
 
 uint32_t add() {
-       return foo() + bar();
+        return foo() + bar();
 }
index c3456a64b9bc40bdcbc7af04ba00be8f5e6e30e6..121e48e84e46fd8ba2fbbbbf1eb32c99f4859a37 100644 (file)
@@ -1,3 +1,4 @@
+// ignore-license
 // Pragma needed cause of gcc bug on windows: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52991
 #pragma pack(1)
 struct __attribute__((packed)) Foo {
index 86cb64537236e1611f877a64a32a1b52d06c5904..8c87c230693d1d0d490d2028ac9b302f2c0d12f3 100644 (file)
@@ -1,3 +1,4 @@
+// ignore-license
 #include <stdio.h>
 #include <stdint.h>
 
index 812c97535287233599c6f936f6cd97be7f3ea5e6..c761f029effbec56ea1bf0e5a7690eb3f3baa57c 100644 (file)
@@ -1,3 +1,4 @@
+// ignore-license
 void foo();
 
 void bar() { foo(); }
index 85e6cd8c3909a7e67c41750f5210b1463dd7a90c..2895ad473bf966158015a0295e161767b673f29a 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 void foo() {}
index a58cd8bb7c98f32cba0afd0b60a4082884f01203..186a0046e80ac2dc6a9c56a245a247f80946083e 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 void some_c_symbol() {}
index 85e6cd8c3909a7e67c41750f5210b1463dd7a90c..2895ad473bf966158015a0295e161767b673f29a 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 void foo() {}
index 867008cd25917f75195f72b833ad69eaf2ed80e8..808417d6521eabb341ce6a27087cf76955f8c7ea 100644 (file)
@@ -28,9 +28,9 @@ fn main() {}
         panic!("expected rustc path");
     }
 
-    let tmpdir = Path::new(args[1].as_slice());
+    let tmpdir = Path::new(&args[1]);
 
-    let mut sysroot = Path::new(args[3].as_slice());
+    let mut sysroot = Path::new(&args[3]);
     sysroot.pop();
     sysroot.pop();
 
index 3064af952f898dd0af82955b866136b66867c114..a595939f92e8ceaed80490e0752c7472df873c63 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 int should_return_one() { return 1; }
index 64275b3ad6bb0f78f4edd2abee386e200c445bff..c53e7e3c48c058cdf12cf54043aa94e4882d71ec 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 int should_return_one() { return 0; }
index 78a6934f57f76766182836819f92e94c3d513a4c..d7d33ea12e8061544e43400232159f3fe500ecf8 100644 (file)
@@ -1,3 +1,4 @@
+// ignore-license
 #include <stdint.h>
 
 extern int32_t BAZ;
index bb4036b06e13b79a32ec78ae04db97590f54b2cc..5729d411c5bcd9a974e321a4a535e0b08c7dfc0b 100644 (file)
@@ -1,3 +1,4 @@
+// ignore-license
 void foo();
 
 int main() {
index e42599986781fe984a2c1427a3373cf439a34f60..3c167b45af98d47cac41dffb772ea7a054f83c94 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 void bar() {}
index e42599986781fe984a2c1427a3373cf439a34f60..3c167b45af98d47cac41dffb772ea7a054f83c94 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 void bar() {}
index ed15e5d880a9baa5b7e76077dcbe869d890c795e..8695ab58e5fe597748b5d503076038e61461a9b1 100755 (executable)
@@ -7,5 +7,6 @@
 // <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(no_std)]
 #![no_std]
 extern crate foo;
index 8afa43710dd93cc01a2412d6497d49dbbf580fa8..afd4f298a97ddc600357cf4167670acbdf40811e 100755 (executable)
@@ -7,5 +7,6 @@
 // <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(no_std)]
 #![no_std]
 #![crate_type = "lib"]
index 330d914a011e2955a3e663229950be2988bc0832..a7b02a2f10b635341d9dc9f3239a4f39fa3b6c60 100644 (file)
@@ -1,3 +1,4 @@
+// ignore-license
 extern void foo();
 
 void bar() { foo(); }
index 1183475610584d0cab9ec404dd6bd1d13b1ff28b..0bec6148189a908ea43df5f599c278c5f76236db 100644 (file)
@@ -8,8 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(lang_items, no_std)]
 #![no_std]
-#![feature(lang_items)]
 #![crate_type = "dylib"]
 
 extern crate libc;
index 85e6cd8c3909a7e67c41750f5210b1463dd7a90c..2895ad473bf966158015a0295e161767b673f29a 100644 (file)
@@ -1 +1,2 @@
+// ignore-license
 void foo() {}
index 61a2a51da08644e51bc09f7878e06e94af25053d..9e8afdc5696ed6dd604cd78a4acc655ad207517d 100644 (file)
@@ -8,8 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(lang_items, no_std)]
 #![no_std]
-#![feature(lang_items)]
 #![crate_type = "dylib"]
 
 extern crate libc;
index 6febe2ff7c1d324c76239c574a68c0b4a3fdb46c..6aff4c9b3d5a3c1cb03d52fe67281ae870d51b2c 100755 (executable)
@@ -9,6 +9,7 @@
 // except according to those terms.
 
 // minimal junk
+#![feature(no_std)]
 #![no_std]
 
 
index c31b67b8043ae400303e47c2a336e1db328231e5..a46fa12ac05201c595ab0f215c6d662b29abad52 100755 (executable)
@@ -9,6 +9,7 @@
 // except according to those terms.
 
 // minimal junk
+#![feature(no_std)]
 #![no_std]
 
 macro_rules! foo {
diff --git a/src/test/run-make/rustdoc-assoc-types/Makefile b/src/test/run-make/rustdoc-assoc-types/Makefile
new file mode 100644 (file)
index 0000000..74fca83
--- /dev/null
@@ -0,0 +1,5 @@
+-include ../tools.mk
+
+all: lib.rs
+       $(HOST_RPATH_ENV) $(RUSTDOC) -w html -o $(TMPDIR)/doc lib.rs
+       $(HTMLDOCCK) $(TMPDIR)/doc lib.rs
diff --git a/src/test/run-make/rustdoc-assoc-types/lib.rs b/src/test/run-make/rustdoc-assoc-types/lib.rs
new file mode 100644 (file)
index 0000000..3e6e0ad
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type="lib"]
+
+// @has lib/trait.Index.html
+pub trait Index<I: ?Sized> {
+    // @has - '//*[@id="associatedtype.Output"]//code' 'type Output: ?Sized'
+    type Output: ?Sized;
+    // @has - '//*[@id="tymethod.index"]//code' \
+    //      "fn index<'a>(&'a self, index: I) -> &'a Self::Output"
+    fn index<'a>(&'a self, index: I) -> &'a Self::Output;
+}
diff --git a/src/test/run-make/rustdoc-extern-method/Makefile b/src/test/run-make/rustdoc-extern-method/Makefile
new file mode 100644 (file)
index 0000000..c87684f
--- /dev/null
@@ -0,0 +1,8 @@
+-include ../tools.mk
+
+all: foo.rs bar.rs
+       $(HOST_RPATH_ENV) $(RUSTC) foo.rs
+       $(HOST_RPATH_ENV) $(RUSTDOC) -w html -o $(TMPDIR)/doc foo.rs
+       $(HOST_RPATH_ENV) $(RUSTDOC) -L $(TMPDIR) -w html -o $(TMPDIR)/doc bar.rs
+       $(HTMLDOCCK) $(TMPDIR)/doc bar.rs
+
diff --git a/src/test/run-make/rustdoc-extern-method/bar.rs b/src/test/run-make/rustdoc-extern-method/bar.rs
new file mode 100644 (file)
index 0000000..672090c
--- /dev/null
@@ -0,0 +1,24 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+extern crate foo;
+
+// @has bar/trait.Foo.html //pre "pub trait Foo"
+// @has - '//*[@id="tymethod.foo"]//code' 'extern "rust-call" fn foo'
+// @has - '//*[@id="tymethod.foo_"]//code' 'extern "rust-call" fn foo_'
+pub use foo::Foo;
+
+// @has bar/trait.Bar.html //pre "pub trait Bar"
+pub trait Bar {
+    // @has - '//*[@id="tymethod.bar"]//code' 'extern "rust-call" fn bar'
+    extern "rust-call" fn bar(&self, _: ());
+    // @has - '//*[@id="method.bar_"]//code' 'extern "rust-call" fn bar_'
+    extern "rust-call" fn bar_(&self, _: ()) { }
+}
diff --git a/src/test/run-make/rustdoc-extern-method/foo.rs b/src/test/run-make/rustdoc-extern-method/foo.rs
new file mode 100644 (file)
index 0000000..fc5f03e
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type="lib"]
+
+pub trait Foo {
+    extern "rust-call" fn foo(&self, _: ()) -> i32;
+    extern "rust-call" fn foo_(&self, _: ()) -> i32 { 0 }
+}
diff --git a/src/test/run-make/rustdoc-ffi/Makefile b/src/test/run-make/rustdoc-ffi/Makefile
new file mode 100644 (file)
index 0000000..c312efe
--- /dev/null
@@ -0,0 +1,8 @@
+-include ../tools.mk
+
+all: lib.rs
+       $(HOST_RPATH_ENV) $(RUSTC) lib.rs
+       $(HOST_RPATH_ENV) $(RUSTDOC) -w html -o $(TMPDIR)/doc lib.rs
+       $(HOST_RPATH_ENV) $(RUSTDOC) -L $(TMPDIR) -w html -o $(TMPDIR)/doc user.rs
+       $(HTMLDOCCK) $(TMPDIR)/doc lib.rs
+       $(HTMLDOCCK) $(TMPDIR)/doc user.rs
diff --git a/src/test/run-make/rustdoc-ffi/lib.rs b/src/test/run-make/rustdoc-ffi/lib.rs
new file mode 100644 (file)
index 0000000..e06dbe7
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type="lib"]
+
+extern "C" {
+    // @has lib/fn.foreigner.html //pre 'pub unsafe fn foreigner(cold_as_ice: u32)'
+    pub fn foreigner(cold_as_ice: u32);
+}
diff --git a/src/test/run-make/rustdoc-ffi/user.rs b/src/test/run-make/rustdoc-ffi/user.rs
new file mode 100644 (file)
index 0000000..09d7a7c
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type="lib"]
+
+extern crate lib;
+
+// @has user/fn.foreigner.html //pre 'pub unsafe fn foreigner(cold_as_ice: u32)'
+pub use lib::foreigner;
index c538a132fb1bcc2e5ff379f8d8346f8abf0a8334..3906d9ee8ae84833c951a3df0d0fb202592c03bb 100644 (file)
@@ -32,5 +32,4 @@
 pub fn foo() {}
 
 // @!has foo/fn.foo.html invisible
-// @matches - //pre '#.*\[.*derive.*\(.*Eq.*\).*\].*//.*Bar'
-
+// @matches - //pre "#\[derive\(PartialEq\)\] // Bar"
index eaa3af8656371981d8cc78d6351a915b720591ed..b5fcbf46c5c98207eec54bd47fda67f5c2b4744d 100644 (file)
@@ -15,8 +15,8 @@
 // @matches foo/struct.Bravo.html '//pre' "pub struct Bravo<B>"
 pub struct Bravo<B>;
 
-// @matches foo/struct.Alpha.html '//*[@class="impl"]//code' "impl !.*Send.* for .*Alpha"
+// @matches foo/struct.Alpha.html '//*[@class="impl"]//code' "impl !Send for Alpha"
 impl !Send for Alpha {}
 
-// @matches foo/struct.Bravo.html '//*[@class="impl"]//code' "impl<B> !.*Send.* for .*Bravo.*<B>"
+// @matches foo/struct.Bravo.html '//*[@class="impl"]//code' "impl<B> !Send for Bravo<B>"
 impl<B> !Send for Bravo<B> {}
index 9f38ff138051c81a39da2a24e25158e087d196e4..68fde60564e2a8c96bdc25f29029eec503c42a73 100644 (file)
 
 pub trait MyTrait {}
 
-// @matches foo/struct.Alpha.html '//pre' "Alpha.*where.*A:.*MyTrait"
+// @has foo/struct.Alpha.html '//pre' "pub struct Alpha<A> where A: MyTrait"
 pub struct Alpha<A> where A: MyTrait;
-// @matches foo/trait.Bravo.html '//pre' "Bravo.*where.*B:.*MyTrait"
+// @has foo/trait.Bravo.html '//pre' "pub trait Bravo<B> where B: MyTrait"
 pub trait Bravo<B> where B: MyTrait {}
-// @matches foo/fn.charlie.html '//pre' "charlie.*where.*C:.*MyTrait"
+// @has foo/fn.charlie.html '//pre' "pub fn charlie<C>() where C: MyTrait"
 pub fn charlie<C>() where C: MyTrait {}
 
 pub struct Delta<D>;
-// @matches foo/struct.Delta.html '//*[@class="impl"]//code' "impl.*Delta.*where.*D:.*MyTrait"
+// @has foo/struct.Delta.html '//*[@class="impl"]//code' \
+//          "impl<D> Delta<D> where D: MyTrait"
 impl<D> Delta<D> where D: MyTrait {
     pub fn delta() {}
 }
 
 pub struct Echo<E>;
-// @matches foo/struct.Echo.html '//*[@class="impl"]//code' \
-//          "impl.*MyTrait.*for.*Echo.*where.*E:.*MyTrait"
-// @matches foo/trait.MyTrait.html '//*[@id="implementors-list"]//code' \
-//          "impl.*MyTrait.*for.*Echo.*where.*E:.*MyTrait"
+// @has foo/struct.Echo.html '//*[@class="impl"]//code' \
+//          "impl<E> MyTrait for Echo<E> where E: MyTrait"
+// @has foo/trait.MyTrait.html '//*[@id="implementors-list"]//code' \
+//          "impl<E> MyTrait for Echo<E> where E: MyTrait"
 impl<E> MyTrait for Echo<E> where E: MyTrait {}
 
 pub enum Foxtrot<F> {}
-// @matches foo/enum.Foxtrot.html '//*[@class="impl"]//code' \
-//          "impl.*MyTrait.*for.*Foxtrot.*where.*F:.*MyTrait"
-// @matches foo/trait.MyTrait.html '//*[@id="implementors-list"]//code' \
-//          "impl.*MyTrait.*for.*Foxtrot.*where.*F:.*MyTrait"
+// @has foo/enum.Foxtrot.html '//*[@class="impl"]//code' \
+//          "impl<F> MyTrait for Foxtrot<F> where F: MyTrait"
+// @has foo/trait.MyTrait.html '//*[@id="implementors-list"]//code' \
+//          "impl<F> MyTrait for Foxtrot<F> where F: MyTrait"
 impl<F> MyTrait for Foxtrot<F> where F: MyTrait {}
index cb3b3d9af38b2064500c0726aebfab1dd59b3239..d90219b4221ebcc83a68a62abb6245a2b08c02a5 100644 (file)
@@ -17,7 +17,6 @@
 
 extern crate "flate" as myflate;
 
-use graphviz::maybe_owned_vec::MaybeOwnedVector;
 use std::collections::{HashMap,HashSet};
 use std::cell::RefCell;
 use std::old_io::stdio::println;
@@ -35,7 +34,7 @@
 static uni: &'static str = "Les Miséééééééérables";
 static yy: usize = 25us;
 
-static bob: Option<graphviz::maybe_owned_vec::MaybeOwnedVector<'static, isize>> = None;
+static bob: Option<std::vec::CowVec<'static, isize>> = None;
 
 // buglink test - see issue #1337.
 
@@ -106,7 +105,7 @@ trait SomeTrait: SuperTrait {
     fn Method(&self, x: u32) -> u32;
 
     fn prov(&self, x: u32) -> u32 {
-        println(x.to_string().as_slice());
+        println(&x.to_string());
         42
     }
     fn provided_method(&self) -> u32 {
@@ -122,7 +121,7 @@ fn stat2(x: &Self) -> u32 {
 
 impl SomeTrait for some_fields {
     fn Method(&self, x: u32) -> u32 {
-        println(x.to_string().as_slice());
+        println(&x.to_string());
         self.field1
     }
 }
@@ -134,7 +133,7 @@ impl SubTrait for some_fields {}
 
 impl some_fields {
     fn stat(x: u32) -> u32 {
-        println(x.to_string().as_slice());
+        println(&x.to_string());
         42
     }
     fn stat2(x: &some_fields) -> u32 {
@@ -194,20 +193,20 @@ enum SomeStructEnum {
 
 fn matchSomeEnum(val: SomeEnum) {
     match val {
-        SomeEnum::Ints(int1, int2) => { println((int1+int2).to_string().as_slice()); }
-        SomeEnum::Floats(float1, float2) => { println((float2*float1).to_string().as_slice()); }
+        SomeEnum::Ints(int1, int2) => { println(&(int1+int2).to_string()); }
+        SomeEnum::Floats(float1, float2) => { println(&(float2*float1).to_string()); }
         SomeEnum::Strings(_, _, s3) => { println(s3); }
         SomeEnum::MyTypes(mt1, mt2) => {
-            println((mt1.field1 - mt2.field1).to_string().as_slice());
+            println(&(mt1.field1 - mt2.field1).to_string());
         }
     }
 }
 
 fn matchSomeStructEnum(se: SomeStructEnum) {
     match se {
-        SomeStructEnum::EnumStruct{a:a, ..} => println(a.to_string().as_slice()),
-        SomeStructEnum::EnumStruct2{f1:f1, f2:f_2} => println(f_2.field1.to_string().as_slice()),
-        SomeStructEnum::EnumStruct3{f1, ..} => println(f1.field1.to_string().as_slice()),
+        SomeStructEnum::EnumStruct{a:a, ..} => println(&a.to_string()),
+        SomeStructEnum::EnumStruct2{f1:f1, f2:f_2} => println(&f_2.field1.to_string()),
+        SomeStructEnum::EnumStruct3{f1, ..} => println(&f1.field1.to_string()),
     }
 }
 
@@ -215,9 +214,9 @@ fn matchSomeStructEnum(se: SomeStructEnum) {
 fn matchSomeStructEnum2(se: SomeStructEnum) {
     use SomeStructEnum::*;
     match se {
-        EnumStruct{a: ref aaa, ..} => println(aaa.to_string().as_slice()),
-        EnumStruct2{f1, f2: f2} => println(f1.field1.to_string().as_slice()),
-        EnumStruct3{f1, f3: SomeEnum::Ints(_, _), f2} => println(f1.field1.to_string().as_slice()),
+        EnumStruct{a: ref aaa, ..} => println(&aaa.to_string()),
+        EnumStruct2{f1, f2: f2} => println(&f1.field1.to_string()),
+        EnumStruct3{f1, f3: SomeEnum::Ints(_, _), f2} => println(&f1.field1.to_string()),
         _ => {},
     }
 }
@@ -233,12 +232,12 @@ fn matchSomeOtherEnum(val: SomeOtherEnum) {
 fn hello<X: SomeTrait>((z, a) : (u32, String), ex: X) {
     SameDir2::hello(43);
 
-    println(yy.to_string().as_slice());
+    println(&yy.to_string());
     let (x, y): (u32, u32) = (5, 3);
-    println(x.to_string().as_slice());
-    println(z.to_string().as_slice());
+    println(&x.to_string());
+    println(&z.to_string());
     let x: u32 = x;
-    println(x.to_string().as_slice());
+    println(&x.to_string());
     let x = "hello";
     println(x);
 
@@ -269,7 +268,7 @@ fn hello<X: SomeTrait>((z, a) : (u32, String), ex: X) {
     s4.provided_method();
     s2.prov(45);
 
-    let closure = |&: x: u32, s: &SomeTrait| {
+    let closure = |x: u32, s: &SomeTrait| {
         s.Method(23);
         return x + y;
     };
@@ -311,7 +310,7 @@ macro_rules! variable_str(($name:expr) => (
     let s3: some_fields = some_fields{ field1: 55};
     let s4: msalias::nested_struct = sub::sub2::nested_struct{ field2: 55};
     let s4: msalias::nested_struct = sub2::nested_struct{ field2: 55};
-    println(s2.field1.to_string().as_slice());
+    println(&s2.field1.to_string());
     let s5: MyType = box some_fields{ field1: 55};
     let s = SameDir::SameStruct{name: "Bob".to_string()};
     let s = SubDir::SubStruct{name:"Bob".to_string()};
index 76079ddb8bd910bca3cc111905ce02db0b9e86d4..834a2adf01fd3075bfa44ef33454e2504f68f3fd 100755 (executable)
@@ -12,6 +12,7 @@
 #![crate_type = "lib"]
 // we can compile to a variety of platforms, because we don't need
 // cross-compiled standard libraries.
+#![feature(no_std)]
 #![no_std]
 
 #![feature(simd, simd_ffi, link_llvm_intrinsics, lang_items)]
@@ -74,7 +75,7 @@ trait Sized {}
 #[lang = "copy"]
 trait Copy {}
 
-mod std {
+mod core {
     pub mod marker {
         pub use Copy;
     }
index fd112034f40c50d3f53be37539e919fde84369d1..365fc039a4ec37a6f8a2f93da4d6d437ecea7dc2 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(lang_items)]
+#![feature(lang_items, no_std)]
 #![no_std]
 
 #[lang="copy"]
index f9ffdffb4647ae98daace7106d7d5800d4633b73..be67e5a066acb90596256545070040c90e7b9d76 100644 (file)
@@ -34,8 +34,8 @@ fn random_char() -> char {
 
 fn main() {
     let args = os::args();
-    let rustc = args[1].as_slice();
-    let tmpdir = Path::new(args[2].as_slice());
+    let rustc = &args[1];
+    let tmpdir = Path::new(&args[2]);
 
     let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
     {
@@ -56,12 +56,12 @@ fn main() {
         // can't exec it directly
         let result = Command::new("sh")
                              .arg("-c")
-                             .arg(format!("{} {}",
-                                          rustc,
-                                          main_file.as_str()
-                                                   .unwrap()).as_slice())
+                             .arg(&format!("{} {}",
+                                           rustc,
+                                           main_file.as_str()
+                                                    .unwrap()))
                              .output().unwrap();
-        let err = String::from_utf8_lossy(result.error.as_slice());
+        let err = String::from_utf8_lossy(&result.error);
 
         // positive test so that this test will be updated when the
         // compiler changes.
index 9ee7516c7baeb91eadcf31be2f3e4ba5d4ee3186..95ce57da4e110c60c977e11a2857abf305340c80 100644 (file)
@@ -34,8 +34,8 @@ fn random_char() -> char {
 
 fn main() {
     let args = os::args();
-    let rustc = args[1].as_slice();
-    let tmpdir = Path::new(args[2].as_slice());
+    let rustc = &args[1];
+    let tmpdir = Path::new(&args[2]);
     let main_file = tmpdir.join("span_main.rs");
 
     for _ in 0u..100 {
@@ -52,18 +52,18 @@ fn main() {
         // can't exec it directly
         let result = Command::new("sh")
                              .arg("-c")
-                             .arg(format!("{} {}",
-                                          rustc,
-                                          main_file.as_str()
-                                                   .unwrap()).as_slice())
+                             .arg(&format!("{} {}",
+                                           rustc,
+                                           main_file.as_str()
+                                                    .unwrap()))
                              .output().unwrap();
 
-        let err = String::from_utf8_lossy(result.error.as_slice());
+        let err = String::from_utf8_lossy(&result.error);
 
         // the span should end the line (e.g no extra ~'s)
         let expected_span = format!("^{}\n", repeat("~").take(n - 1)
                                                         .collect::<String>());
-        assert!(err.contains(expected_span.as_slice()));
+        assert!(err.contains(&expected_span));
     }
 
     // Test multi-column characters and tabs
diff --git a/src/test/run-make/use-extern-for-plugins/Makefile b/src/test/run-make/use-extern-for-plugins/Makefile
new file mode 100644 (file)
index 0000000..84032b4
--- /dev/null
@@ -0,0 +1,13 @@
+-include ../tools.mk
+
+HOST := $(shell $(RUSTC) -vV | grep 'host:' | sed 's/host: //')
+ifeq ($(findstring i686,$(HOST)),i686)
+TARGET := $(subst i686,x86_64,$(HOST))
+else
+TARGET := $(subst x86_64,i686,$(HOST))
+endif
+
+all:
+       $(RUSTC) foo.rs -C extra-filename=-host
+       $(RUSTC) bar.rs -C extra-filename=-targ --target $(TARGET)
+       $(RUSTC) baz.rs --extern a=$(TMPDIR)/liba-targ.rlib --target $(TARGET)
diff --git a/src/test/run-make/use-extern-for-plugins/bar.rs b/src/test/run-make/use-extern-for-plugins/bar.rs
new file mode 100644 (file)
index 0000000..f279893
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(no_std)]
+#![no_std]
+#![crate_type = "lib"]
+#![crate_name = "a"]
+
+#[macro_export]
+macro_rules! bar {
+    () => ()
+}
diff --git a/src/test/run-make/use-extern-for-plugins/baz.rs b/src/test/run-make/use-extern-for-plugins/baz.rs
new file mode 100644 (file)
index 0000000..89d6c6b
--- /dev/null
@@ -0,0 +1,18 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(no_std)]
+#![no_std]
+#![crate_type = "lib"]
+
+#[macro_use]
+extern crate a;
+
+bar!();
diff --git a/src/test/run-make/use-extern-for-plugins/foo.rs b/src/test/run-make/use-extern-for-plugins/foo.rs
new file mode 100644 (file)
index 0000000..554c0fe
--- /dev/null
@@ -0,0 +1,19 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(no_std)]
+#![no_std]
+#![crate_type = "lib"]
+#![crate_name = "a"]
+
+#[macro_export]
+macro_rules! foo {
+    () => ()
+}
diff --git a/src/test/run-pass-fulldeps/compiler-calls.rs b/src/test/run-pass-fulldeps/compiler-calls.rs
new file mode 100644 (file)
index 0000000..9e16452
--- /dev/null
@@ -0,0 +1,81 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that the CompilerCalls interface to the compiler works.
+
+// ignore-android
+
+#![feature(rustc_private)]
+#![feature(core)]
+
+extern crate getopts;
+extern crate rustc;
+extern crate rustc_driver;
+extern crate syntax;
+
+use rustc::session::Session;
+use rustc::session::config::{self, Input};
+use rustc_driver::{driver, CompilerCalls, Compilation};
+use syntax::diagnostics;
+
+
+struct TestCalls {
+    count: u32
+}
+
+impl<'a> CompilerCalls<'a> for TestCalls {
+    fn early_callback(&mut self,
+                      _: &getopts::Matches,
+                      _: &diagnostics::registry::Registry)
+                      -> Compilation {
+        self.count *= 2;
+        Compilation::Continue
+    }
+
+    fn late_callback(&mut self,
+                     _: &getopts::Matches,
+                     _: &Session,
+                     _: &Input,
+                     _: &Option<Path>,
+                     _: &Option<Path>)
+                     -> Compilation {
+        self.count *= 3;
+        Compilation::Stop
+    }
+
+    fn some_input(&mut self, input: Input, input_path: Option<Path>) -> (Input, Option<Path>) {
+        self.count *= 5;
+        (input, input_path)
+    }
+
+    fn no_input(&mut self,
+                _: &getopts::Matches,
+                _: &config::Options,
+                _: &Option<Path>,
+                _: &Option<Path>,
+                _: &diagnostics::registry::Registry)
+                -> Option<(Input, Option<Path>)> {
+        panic!("This shouldn't happen");
+    }
+
+    fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
+        panic!("This shouldn't be called");
+    }
+}
+
+
+fn main() {
+    let mut tc = TestCalls { count: 1 };
+    // we should never get use this filename, but lets make sure they are valid args.
+    let args = vec!["compiler-calls".to_string(), "foo.rs".to_string()];
+    rustc_driver::run_compiler(args.as_slice(), &mut tc);
+    assert!(tc.count == 30);
+}
+
index 11e7da770291a309e45b0d675bc92a1e237a80a8..c59a3589c04af3eded86a01ca5d88d38038e6e55 100644 (file)
@@ -12,8 +12,7 @@
 // ignore-android
 // aux-build:issue_16723_multiple_items_syntax_ext.rs
 #![feature(plugin)]
-
-#[plugin] #[no_link] extern crate issue_16723_multiple_items_syntax_ext;
+#![plugin(issue_16723_multiple_items_syntax_ext)]
 
 multiple_items!();
 
index 7615b25f9e40cacab27a0915db68c4ca523800ce..1a639cdb9ddfa24e3edbd479e50f4f0b02250b4c 100644 (file)
@@ -13,9 +13,7 @@
 // ignore-pretty
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate lint_group_plugin_test;
+#![plugin(lint_group_plugin_test)]
 
 fn lintme() { } //~ WARNING item is named 'lintme'
 fn pleaselintme() { } //~ WARNING item is named 'pleaselintme'
index 7144d2b0f1e7162ac22652f586b82f78ad6bcba0..204312064b582aee3be39012549a86f3b128205e 100644 (file)
@@ -13,9 +13,7 @@
 // compile-flags: -A test-lint
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate lint_plugin_test;
+#![plugin(lint_plugin_test)]
 
 fn lintme() { }
 
index d11242f4fe643e92f07282bc0b898bf7a52b1c82..8311e188f922935c29517e1f74013c0c3bc01bce 100644 (file)
@@ -13,9 +13,7 @@
 // ignore-pretty
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate lint_plugin_test;
+#![plugin(lint_plugin_test)]
 
 fn lintme() { } //~ WARNING item is named 'lintme'
 
index 497afae6189986480bba9e340e1175e2c9d6d5eb..8ed47fe1f6f200127f4c821aa8be75cdaa93abb3 100644 (file)
@@ -15,9 +15,7 @@
 // uses `quote_expr!` to rearrange it should be hygiene-preserving.
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate macro_crate_test;
+#![plugin(macro_crate_test)]
 
 fn main() {
     let x = 3;
index d943cf0457b4feace6006a53515159ba934fa64e..9573d0c8c403044e57413f5011fdc2c5ae4d8edd 100644 (file)
@@ -12,8 +12,6 @@
 // ignore-stage1
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate plugin_crate_outlive_expansion_phase;
+#![plugin(plugin_crate_outlive_expansion_phase)]
 
 pub fn main() {}
index a9e93aa8df5cfe2f3f6133295867a6a95a2d335f..58ccd79b7121dbe9afe8201db76283556de8a170 100644 (file)
@@ -12,8 +12,9 @@
 // ignore-stage1
 
 #![feature(plugin)]
+#![plugin(macro_crate_test)]
 
-#[macro_use] #[plugin] #[no_link]
+#[macro_use] #[no_link]
 extern crate macro_crate_test;
 
 #[into_foo]
index 5a91f603f9681cac54062e9ddad404e9e1893d5a..4d4f9092bc8251d377df2f1ced6cd1a90ead99c5 100644 (file)
 // ignore-stage1
 
 #![feature(plugin)]
-
-#[no_link]
-#[plugin]
-extern crate plugin_args;
+#![plugin(plugin_args)]
 
 fn main() {
-    assert_eq!(plugin_args!(), "#[plugin]");
+    assert_eq!(plugin_args!(), "");
 }
index d0ac22a529021641694689a24771f47ddfcddad4..4da566aec4282f1c869f2d6df81bf8c4f3183511 100644 (file)
 // ignore-stage1
 
 #![feature(plugin)]
-
-#[no_link]
-#[plugin()]
-extern crate plugin_args;
+#![plugin(plugin_args())]
 
 fn main() {
-    assert_eq!(plugin_args!(), "#[plugin()]");
+    assert_eq!(plugin_args!(), "");
 }
index 7cac8ac57e55c09d31b9da0c21ac32afbd71f9c7..0a064933aec4a4bb32cfa7bb7e1bca49a451b7b9 100644 (file)
 // ignore-stage1
 
 #![feature(plugin)]
-
-#[no_link]
-#[plugin(hello(there), how(are="you"))]
-extern crate plugin_args;
+#![plugin(plugin_args(hello(there), how(are="you")))]
 
 fn main() {
-    assert_eq!(plugin_args!(), "#[plugin(hello(there), how(are = \"you\"))]");
+    assert_eq!(plugin_args!(), "hello(there), how(are = \"you\")");
 }
diff --git a/src/test/run-pass-fulldeps/plugin-args-4.rs b/src/test/run-pass-fulldeps/plugin-args-4.rs
deleted file mode 100644 (file)
index 8563c8c..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// aux-build:plugin_args.rs
-// ignore-stage1
-
-#![feature(plugin)]
-
-#[no_link]
-#[plugin="foobar"]
-extern crate plugin_args;
-
-fn main() {
-    assert_eq!(plugin_args!(), "#[plugin = \"foobar\"]");
-}
diff --git a/src/test/run-pass-fulldeps/plugin-link-does-resolve.rs b/src/test/run-pass-fulldeps/plugin-link-does-resolve.rs
deleted file mode 100644 (file)
index 518d02e..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2013-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.
-
-// aux-build:macro_crate_test.rs
-// ignore-stage1
-// ignore-cross-compile
-//
-// macro_crate_test will not compile on a cross-compiled target because
-// libsyntax is not compiled for it.
-
-#![feature(plugin)]
-
-#[plugin]
-extern crate macro_crate_test;
-
-fn main() {
-    assert_eq!(1, make_a_1!());
-    macro_crate_test::foo();
-}
diff --git a/src/test/run-pass-fulldeps/plugin-plus-extern-crate.rs b/src/test/run-pass-fulldeps/plugin-plus-extern-crate.rs
new file mode 100644 (file)
index 0000000..0c27dba
--- /dev/null
@@ -0,0 +1,26 @@
+// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// aux-build:macro_crate_test.rs
+// ignore-stage1
+// ignore-cross-compile
+//
+// macro_crate_test will not compile on a cross-compiled target because
+// libsyntax is not compiled for it.
+
+#![feature(plugin)]
+#![plugin(macro_crate_test)]
+
+extern crate macro_crate_test;
+
+fn main() {
+    assert_eq!(1, make_a_1!());
+    macro_crate_test::foo();
+}
index d76766094ed773d40974da44a142b0ff8b728116..81f5c649626c35f9eb375613b05fc840dd1085c2 100644 (file)
@@ -12,9 +12,7 @@
 // ignore-stage1
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate roman_numerals;
+#![plugin(roman_numerals)]
 
 pub fn main() {
     assert_eq!(rn!(MMXV), 2015);
index 1c74c8ad08eec0bb64bfbbc338853b7f9bdb7d97..b7570eb09261286a84f9830a5fe7066bf1464639 100644 (file)
@@ -8,14 +8,12 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// aux-build:syntax-extension-with-dll-deps-1.rs
-// aux-build:syntax-extension-with-dll-deps-2.rs
+// aux-build:syntax_extension_with_dll_deps_1.rs
+// aux-build:syntax_extension_with_dll_deps_2.rs
 // ignore-stage1
 
 #![feature(plugin)]
-
-#[plugin] #[no_link]
-extern crate "syntax-extension-with-dll-deps-2" as extension;
+#![plugin(syntax_extension_with_dll_deps_2)]
 
 fn main() {
     foo!();
index b7e3480c076262aeeac3ef82e38d4dfc49f7ff68..57c50511604ca3f095418cac0f56ca53e264191a 100644 (file)
@@ -47,7 +47,7 @@ pub fn main() {
     assert_eq!(length(x.clone()), x.len());
     // Call a parameterized function, with type arguments that require
     // a borrow
-    assert_eq!(length::<int, &[int]>(x.as_slice()), x.len());
+    assert_eq!(length::<int, &[int]>(&*x), x.len());
 
     // Now try it with a type that *needs* to be borrowed
     let z = [0,1,2,3];
index 6d59161ff93456fdaf1163bc02cc17033d8b30e2..f21b7183d70c46c5445081f762ed18c55af6f41f 100644 (file)
@@ -36,7 +36,7 @@ fn eq(&self, other: &[B]) -> bool {
     where A: MyEq<B>, Lhs: Deref<Target=[A]>
 {
     fn eq(&self, other: &[B; 0]) -> bool {
-        MyEq::eq(&**self, other.as_slice())
+        MyEq::eq(&**self, other)
     }
 }
 
diff --git a/src/test/run-pass/associated-types-duplicate-binding-in-env-hrtb.rs b/src/test/run-pass/associated-types-duplicate-binding-in-env-hrtb.rs
new file mode 100644 (file)
index 0000000..8b7ea61
--- /dev/null
@@ -0,0 +1,23 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Check that we do not report ambiguities when equivalent predicates
+// (modulo bound lifetime names) appears in the environment
+// twice. Issue #21965.
+
+fn foo<T>(t: T) -> i32
+    where T : for<'a> Fn(&'a u8) -> i32,
+          T : for<'b> Fn(&'b u8) -> i32,
+{
+    t(&3)
+}
+
+fn main() {
+}
diff --git a/src/test/run-pass/associated-types-duplicate-binding-in-env.rs b/src/test/run-pass/associated-types-duplicate-binding-in-env.rs
new file mode 100644 (file)
index 0000000..62ac218
--- /dev/null
@@ -0,0 +1,27 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Check that we do not report ambiguities when the same predicate
+// appears in the environment twice. Issue #21965.
+
+trait Foo {
+    type B;
+
+    fn get() -> Self::B;
+}
+
+fn foo<T>() -> ()
+    where T : Foo<B=()>, T : Foo<B=()>
+{
+    <T as Foo>::get()
+}
+
+fn main() {
+}
index 9b030de998373be9b62b6b9542d8de7fbb5c4a11..1fcbae833dc7f00342660e55494a2c375917d521 100644 (file)
@@ -35,7 +35,7 @@ fn test_rbml<'a, 'b, A:
     let mut rbml_w = EBwriter::Encoder::new(&mut wr);
     a1.encode(&mut rbml_w);
 
-    let d: serialize::rbml::Doc<'a> = EBDoc::new(&wr[]);
+    let d: serialize::rbml::Doc<'a> = EBDoc::new(&wr);
     let mut decoder: EBReader::Decoder<'a> = EBreader::Decoder::new(d);
     let a2: A = Decodable::decode(&mut decoder);
     assert!(*a1 == a2);
index e9a3ab6be35c385ef3889493ea80450c512aa42d..2cb6cf99d662e48194a48c4439bebddc44c39461 100644 (file)
@@ -48,7 +48,7 @@ fn runtest(me: &str) {
     let p = template.clone().arg("fail").env("RUST_BACKTRACE", "1").spawn().unwrap();
     let out = p.wait_with_output().unwrap();
     assert!(!out.status.success());
-    let s = str::from_utf8(out.error.as_slice()).unwrap();
+    let s = str::from_utf8(&out.error).unwrap();
     assert!(s.contains("stack backtrace") && s.contains("foo::h"),
             "bad output: {}", s);
 
@@ -56,7 +56,7 @@ fn runtest(me: &str) {
     let p = template.clone().arg("fail").spawn().unwrap();
     let out = p.wait_with_output().unwrap();
     assert!(!out.status.success());
-    let s = str::from_utf8(out.error.as_slice()).unwrap();
+    let s = str::from_utf8(&out.error).unwrap();
     assert!(!s.contains("stack backtrace") && !s.contains("foo::h"),
             "bad output2: {}", s);
 
@@ -64,7 +64,7 @@ fn runtest(me: &str) {
     let p = template.clone().arg("double-fail").spawn().unwrap();
     let out = p.wait_with_output().unwrap();
     assert!(!out.status.success());
-    let s = str::from_utf8(out.error.as_slice()).unwrap();
+    let s = str::from_utf8(&out.error).unwrap();
     // loosened the following from double::h to double:: due to
     // spurious failures on mac, 32bit, optimized
     assert!(s.contains("stack backtrace") && s.contains("double::"),
@@ -75,7 +75,7 @@ fn runtest(me: &str) {
                                 .env("RUST_BACKTRACE", "1").spawn().unwrap();
     let out = p.wait_with_output().unwrap();
     assert!(!out.status.success());
-    let s = str::from_utf8(out.error.as_slice()).unwrap();
+    let s = str::from_utf8(&out.error).unwrap();
     let mut i = 0;
     for _ in 0..2 {
         i += s[i + 10..].find_str("stack backtrace").unwrap() + 10;
@@ -86,12 +86,12 @@ fn runtest(me: &str) {
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() >= 2 && args[1].as_slice() == "fail" {
+    let args = args;
+    if args.len() >= 2 && args[1] == "fail" {
         foo();
-    } else if args.len() >= 2 && args[1].as_slice() == "double-fail" {
+    } else if args.len() >= 2 && args[1] == "double-fail" {
         double();
     } else {
-        runtest(args[0].as_slice());
+        runtest(&args[0]);
     }
 }
index fae83d4aa6563632eca12028ad420553141ded4e..758776298e1463cc94699fc4f563dd4ecb94da23 100644 (file)
@@ -26,13 +26,13 @@ fn call_g<G:FnMut(String,String) -> String>(mut g: G, x: String, y: String)
 }
 
 fn g(mut x: String, y: String) -> String {
-    x.push_str(y.as_slice());
+    x.push_str(&y);
     x
 }
 
 fn main() {
     call_f(f);
-    assert_eq!(call_g(g, "foo".to_string(), "bar".to_string()).as_slice(),
+    assert_eq!(call_g(g, "foo".to_string(), "bar".to_string()),
                "foobar");
 }
 
index fe52b1a693cdcb9f76f71ac95c94fcb7450f5f05..f3c874a5afcec13b801d006a754704754ea55b32 100644 (file)
@@ -13,6 +13,6 @@
 pub fn main() {
     fn f() -> int { return 7; }
     assert_eq!(force(f), 7);
-    let g = {|&:|force(f)};
+    let g = {||force(f)};
     assert_eq!(g(), 7);
 }
index b3c4802530ed3c9f7aa38a0ea43af498648f91d1..edf6b397ff8c8c7703a3a1bb1ade80ba8b41a9f8 100644 (file)
@@ -53,9 +53,9 @@ fn main() {
     assert_eq!(!false, true);
 
     let s = false.to_string();
-    assert_eq!(s.as_slice(), "false");
+    assert_eq!(s, "false");
     let s = true.to_string();
-    assert_eq!(s.as_slice(), "true");
+    assert_eq!(s, "true");
 
     assert!(true > false);
     assert!(!(false > true));
index 6624136544dded6d8b59154babf86989a4a056b1..34ad2b2def03f82a5d4de6a5838ff9064ce50931 100644 (file)
@@ -19,7 +19,7 @@ pub fn main() {
 
     match x {
       F {f: ref mut v} => {
-        impure(v.as_slice());
+        impure(v);
       }
     }
 }
index df8dbdd03c740c1fd96e6be488111f9ef84c57af..c907778339ec50b64e72f42343c9b25321975bd1 100644 (file)
@@ -17,8 +17,8 @@
 fn a() -> i32 {
     let mut x = 3i32;
     x += 1;
-    let c1 = |&:| x * 4;
-    let c2 = |&:| x * 5;
+    let c1 = || x * 4;
+    let c2 = || x * 5;
     c1() * c2() * x
 }
 
@@ -29,16 +29,16 @@ fn get(x: &i32) -> i32 {
 fn b() -> i32 {
     let mut x = 3i32;
     x += 1;
-    let c1 = |&:| get(&x);
-    let c2 = |&:| get(&x);
+    let c1 = || get(&x);
+    let c2 = || get(&x);
     c1() * c2() * x
 }
 
 fn c() -> i32 {
     let mut x = 3i32;
     x += 1;
-    let c1 = |&:| x * 5;
-    let c2 = |&:| get(&x);
+    let c1 = || x * 5;
+    let c2 = || get(&x);
     c1() * c2() * x
 }
 
index 773780ffb0953f8e95f51387cba0a3483cd925d3..1be57674fa1ff4ad9c981e3bd59c924029011e39 100644 (file)
@@ -14,7 +14,7 @@
 
 pub fn main() {
     let bar = box 3;
-    let h = |:| -> int *bar;
+    let h = || -> int *bar;
     assert_eq!(h(), 3);
 }
 
index 94c7c2b13cec4cfc146c8990151d45255407516d..092d7c1317029be72ec0abe99ec82fcae68a08e0 100644 (file)
@@ -16,7 +16,7 @@ fn want_slice(v: &[int]) -> int {
 }
 
 fn has_mut_vec(v: Vec<int> ) -> int {
-    want_slice(v.as_slice())
+    want_slice(&v)
 }
 
 pub fn main() {
index 75b54b1af86bd4e45eb8a4b5becbe7254e17adc2..efd932933db333504992493df3a2457ff88f6f7d 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 fn foo(s: &String) -> bool {
-    match s.as_slice() {
+    match &**s {
         "kitty" => true,
         _ => false
     }
index de1196e10d88c0f7a7b4861870359decb5a3b4c3..ca315b7a9f1dbb05f6436899606e9a27a26e5934 100644 (file)
@@ -19,6 +19,6 @@ fn each<'a,T,F:FnMut(&'a T)>(x: &'a [T], mut f: F) {
 fn main() {
     let mut sum = 0u;
     let elems = [ 1u, 2, 3, 4, 5 ];
-    each(&elems, |&mut: val: &uint| sum += *val);
+    each(&elems, |val: &uint| sum += *val);
     assert_eq!(sum, 15);
 }
index 04ab0d881a84d66cf912231abc7cd9ab15e32ed1..edb3d72483b471663e7892107ba2e0e8ead5d853 100644 (file)
@@ -44,7 +44,7 @@ fn get_bar(x: uint) -> Vec<uint> { vec!(x * 2) }
 pub fn fails() {
     let x = 2;
     let mut y = Vec::new();
-    y.push(box Conzabble::Bickwick(do_it(get_bar(x).as_slice())));
+    y.push(box Conzabble::Bickwick(do_it(&get_bar(x))));
 }
 
 pub fn main() {
index 7dd46e7b01702b8ff41c08a7eebfdc34a784fd37..b776f098b1db2f550b7850149b1ae97cba083818 100644 (file)
@@ -24,7 +24,7 @@
 
 pub fn main() {
     let args = os::args();
-    let args = args.as_slice();
+    let args = args;
 
     // Here, the rvalue `"signal".to_string()` requires cleanup. Older versions
     // of the code had a problem that the cleanup scope for this
@@ -32,7 +32,7 @@ pub fn main() {
     // expression was never evaluated, we wound up trying to clean
     // uninitialized memory.
 
-    if args.len() >= 2 && args[1].as_slice() == "signal" {
+    if args.len() >= 2 && args[1] == "signal" {
         // Raise a segfault.
         unsafe { *(0 as *mut int) = 0; }
     }
index c0877568b72aaca50a4a08d6e4e44bb972cae1c5..fa16ea001452c79a52e825264ed202193dd55ace 100644 (file)
@@ -11,7 +11,7 @@
 // Test a rather underspecified example:
 
 pub fn main() {
-    let f = {|&: i| i};
+    let f = {|i| i};
     assert_eq!(f(2), 2);
     assert_eq!(f(5), 5);
 }
index ae4db40411553d4efb4f165f9e97218c76d25b5c..ec8d58616dc0fc66c902c48226b32a1d0fdaeb59 100644 (file)
@@ -47,11 +47,11 @@ fn use_slice(_: &[u8]) {}
 fn use_slice_mut(_: &mut [u8]) {}
 
 fn use_vec(mut v: Vec<u8>) {
-    use_slice_mut(&mut v[]); // what you have to write today
-    use_slice_mut(&mut v);   // what you'd be able to write
+    use_slice_mut(&mut v[..]); // what you have to write today
+    use_slice_mut(&mut v);     // what you'd be able to write
     use_slice_mut(&mut &mut &mut v);
 
-    use_slice(&v[]);    // what you have to write today
+    use_slice(&v[..]);  // what you have to write today
     use_slice(&v);      // what you'd be able to write
     use_slice(&&&&&&v);
     use_slice(&mut &&&&&v);
@@ -59,7 +59,7 @@ fn use_vec(mut v: Vec<u8>) {
 }
 
 fn use_vec_ref(v: &Vec<u8>) {
-    use_slice(&v[]);    // what you have to write today
+    use_slice(&v[..]);  // what you have to write today
     use_slice(v);       // what you'd be able to write
     use_slice(&&&&&&v);
     use_slice(&mut &&&&&v);
index 646eed5de7537b43dd6ec37bb9521ea2d95a5369..69bb3579720b1ccd37bb149fb5ec4f8f3a916996 100644 (file)
@@ -19,6 +19,6 @@ fn bip(v: &[uint]) -> Vec<uint> {
 
 pub fn main() {
     let mut the_vec = vec!(1u, 2, 3, 100);
-    assert_eq!(the_vec.clone(), bar(the_vec.as_mut_slice()));
-    assert_eq!(the_vec.clone(), bip(the_vec.as_slice()));
+    assert_eq!(the_vec.clone(), bar(&mut the_vec));
+    assert_eq!(the_vec.clone(), bip(&the_vec));
 }
index 10d747bf41408c3c3deaf742be0a93b7354a8573..f87f2e07c9de0f0ee2507023a37286cb905f3bee 100644 (file)
@@ -21,6 +21,6 @@ fn bar(v: &mut [uint]) {
 
 pub fn main() {
     let mut the_vec = vec!(1, 2, 3, 100);
-    bar(the_vec.as_mut_slice());
+    bar(&mut the_vec);
     assert_eq!(the_vec, vec!(100, 3, 2, 1));
 }
index 6820aa4d186efd8ea89103d1cdffc72917faa7cd..4f97e6a20815d0014f06a8581abac69b50d8f69e 100644 (file)
@@ -17,6 +17,6 @@ fn bar(v: &mut [uint]) {
 
 pub fn main() {
     let mut the_vec = vec!(1, 2, 3, 100);
-    bar(the_vec.as_mut_slice());
+    bar(&mut the_vec);
     assert_eq!(the_vec, vec!(100, 3, 2, 1));
 }
diff --git a/src/test/run-pass/copy-out-of-array-1.rs b/src/test/run-pass/copy-out-of-array-1.rs
new file mode 100644 (file)
index 0000000..2b57c1e
--- /dev/null
@@ -0,0 +1,28 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Ensure that we can copy out of a fixed-size array.
+//
+// (Compare with compile-fail/move-out-of-array-1.rs)
+
+struct C { _x: u8 }
+
+impl Copy for C { }
+
+fn main() {
+    fn d() -> C { C { _x: 0 } }
+
+    let _d1 = foo([d(), d(), d(), d()], 1);
+    let _d3 = foo([d(), d(), d(), d()], 3);
+}
+
+fn foo(a: [C; 4], i: usize) -> C {
+    a[i]
+}
diff --git a/src/test/run-pass/derive-no-std.rs b/src/test/run-pass/derive-no-std.rs
new file mode 100644 (file)
index 0000000..d3034c2
--- /dev/null
@@ -0,0 +1,41 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(no_std)]
+#![no_std]
+
+extern crate core;
+extern crate rand;
+extern crate "serialize" as rustc_serialize;
+extern crate collections;
+
+// Issue #16803
+
+#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord,
+         Debug, Default, Copy)]
+struct Foo {
+    x: u32,
+}
+
+#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord,
+         Debug, Copy)]
+enum Bar {
+    Qux,
+    Quux(u32),
+}
+
+#[derive(FromPrimitive)]
+enum Baz { A=0, B=5, }
+
+fn main() {
+    Foo { x: 0 };
+    Bar::Quux(3);
+    Baz::A;
+}
index a0888850aaf1408104bd6442fb2dc362300b5011..838d05cf0d53084873383d4c3cabd51529818619 100644 (file)
@@ -25,6 +25,6 @@ struct A {
 fn main() {
     let obj = A { foo: box [true, false] };
     let s = json::encode(&obj).unwrap();
-    let obj2: A = json::decode(s.as_slice()).unwrap();
+    let obj2: A = json::decode(&s).unwrap();
     assert!(obj.foo == obj2.foo);
 }
index a5453d26170ad62833dfa45d88d3d6583bc3ea78..7d581927c30b460a1aafd7dac9182fb90a294a11 100644 (file)
@@ -36,7 +36,7 @@ fn main() {
         bar: RefCell::new( A { baz: 2 } )
     };
     let s = json::encode(&obj).unwrap();
-    let obj2: B = json::decode(s.as_slice()).unwrap();
+    let obj2: B = json::decode(&s).unwrap();
     assert!(obj.foo.get() == obj2.foo.get());
     assert!(obj.bar.borrow().baz == obj2.bar.borrow().baz);
 }
index 8c93f1ec78dc1f0849834b265db35c362dd6aedc..ea43163775ce908172c827ff386abd5dc89a9847 100644 (file)
@@ -59,7 +59,7 @@ fn roundtrip<'a, T: Rand + Eq + Encodable<Encoder<'a>> +
     let mut w = Vec::new();
     let mut e = Encoder::new(&mut w);
     obj.encode(&mut e);
-    let doc = rbml::Doc::new(&w[]);
+    let doc = rbml::Doc::new(&w);
     let mut dec = Decoder::new(doc);
     let obj2 = Decodable::decode(&mut dec);
     assert!(obj == obj2);
diff --git a/src/test/run-pass/destructure-array-1.rs b/src/test/run-pass/destructure-array-1.rs
new file mode 100644 (file)
index 0000000..4327116
--- /dev/null
@@ -0,0 +1,35 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Ensure that we can do a destructuring bind of a fixed-size array,
+// even when the element type has a destructor.
+
+struct D { x: u8 }
+
+impl Drop for D { fn drop(&mut self) { } }
+
+fn main() {
+    fn d(x: u8) -> D { D { x: x } }
+
+    let d1 = foo([d(1), d(2), d(3), d(4)], 1);
+    let d3 = foo([d(5), d(6), d(7), d(8)], 3);
+    assert_eq!(d1.x, 2);
+    assert_eq!(d3.x, 8);
+}
+
+fn foo([a, b, c, d]: [D; 4], i: usize) -> D {
+    match i {
+        0 => a,
+        1 => b,
+        2 => c,
+        3 => d,
+        _ => panic!("unmatched"),
+    }
+}
index 6557594594565f33639b764f41644346338e8a69..95af729e5e16545d88022e321a1b84e4d4bdde11 100644 (file)
@@ -23,6 +23,6 @@ fn wrapper3(i: chan) {
 }
 
 pub fn main() {
-    let wrapped = {|&:|wrapper3(chan::chan_t)};
+    let wrapped = {||wrapper3(chan::chan_t)};
     wrapped();
 }
index 24bf1f94d887b49fe156fe0bbb8e0e85d2ab97c8..3e81ca5125ba4b84fa16383770577d52027dd7ce 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 pub fn main() {
-    let f = |&: (x, y): (int, int)| {
+    let f = |(x, y): (int, int)| {
         assert_eq!(x, 1);
         assert_eq!(y, 2);
     };
index 785abbe449bb47057f61869bfe71151bcc42c734..34417891197a422dd6db05cf34c80eabec933198 100644 (file)
@@ -12,7 +12,7 @@
 
 pub fn main() {
     // We should be able to type infer inside of ||s.
-    let _f = |&:| {
+    let _f = || {
         let i = 10;
     };
 }
diff --git a/src/test/run-pass/for-loop-no-std.rs b/src/test/run-pass/for-loop-no-std.rs
new file mode 100644 (file)
index 0000000..30c2aec
--- /dev/null
@@ -0,0 +1,25 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(lang_items, start, no_std)]
+#![no_std]
+
+extern crate "std" as other;
+
+#[macro_use] extern crate core;
+#[macro_use] extern crate collections;
+
+use core::slice::SliceExt;
+
+#[start]
+fn start(_argc: int, _argv: *const *const u8) -> int {
+    for _ in [1,2,3].iter() { }
+    0
+}
index e9e8c3f09290d784e1999f3d802a330747248423..25d625e27f6ddd40578fad4ef9424085a830778b 100644 (file)
@@ -11,7 +11,7 @@
 pub fn main() {
     let x = [1; 100];
     let mut y = 0;
-    for i in &x[] {
+    for i in &x[..] {
         if y > 10 {
             break;
         }
index 6acfbc95317627bc9213fa92eb18032f6e7aed15..3817e1b0edace950ce3f320474ef3881e92cf4d5 100644 (file)
@@ -13,8 +13,8 @@ pub fn main() {
     let y = [2; 100];
     let mut p = 0;
     let mut q = 0;
-    for i in &x[] {
-        for j in &y[] {
+    for i in &x[..] {
+        for j in &y[..] {
             p += *j;
         }
         q += *i + p;
index 2f154be659d888538de644a2f2cc1da4405bfb55..8403a1669ffcf5fecd6e2fe8f688fab6f1ec4fe0 100644 (file)
@@ -11,7 +11,7 @@
 pub fn main() {
     let x = [1; 100];
     let mut y = 0;
-    for i in &x[] {
+    for i in &x[..] {
         y += *i
     }
     assert!(y == 100);
diff --git a/src/test/run-pass/format-no-std.rs b/src/test/run-pass/format-no-std.rs
new file mode 100644 (file)
index 0000000..44d8049
--- /dev/null
@@ -0,0 +1,36 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(lang_items, start, no_std)]
+#![no_std]
+
+extern crate "std" as other;
+
+#[macro_use] extern crate core;
+#[macro_use] extern crate collections;
+
+use collections::string::ToString;
+
+#[start]
+fn start(_argc: int, _argv: *const *const u8) -> int {
+    let s = format!("{}", 1i);
+    assert_eq!(s, "1".to_string());
+
+    let s = format!("test");
+    assert_eq!(s, "test".to_string());
+
+    let s = format!("{test}", test=3i);
+    assert_eq!(s, "3".to_string());
+
+    let s = format!("hello {}", "world");
+    assert_eq!(s, "hello world".to_string());
+
+    0
+}
index a3df98afcb0c52e39c06908bdc7f315065f87b49..3c89900fe493bad40d3d106d3948b9cfebe9c862 100644 (file)
@@ -16,7 +16,7 @@ pub fn main() {
     let args = Vec::new();
     let opts = vec!(optopt("b", "", "something", "SMTHNG"));
 
-    match getopts(args.as_slice(), opts.as_slice()) {
+    match getopts(&args, &opts) {
         Ok(ref m)  =>
             assert!(!m.opt_present("b")),
         Err(ref f) => panic!("{}", *f)
index 651ac632439fa5f0c49598b1cbe1cede2f263216..677038af9a9c4e0de4609f0622e812f17f377486 100644 (file)
@@ -84,8 +84,7 @@ pub fn map_reduce(inputs: Vec<String>) {
               ctrl_proto::mapper_done => { num_mappers -= 1; }
               ctrl_proto::find_reducer(k, cc) => {
                 let mut c;
-                match reducers.get(&str::from_utf8(
-                        k.as_slice()).unwrap().to_string()) {
+                match reducers.get(&str::from_utf8(&k).unwrap().to_string()) {
                   Some(&_c) => { c = _c; }
                   None => { c = 0; }
                 }
index 1d1e744ef0802d8ff47fd3c2033c4e398e2f2b42..b59e7b67d4eddb4ad11b80ede4fe0193feb0ad4e 100644 (file)
@@ -17,7 +17,7 @@
 // cause a compilation error. Issue #18772.
 
 fn adder(y: int) -> Box<Fn(int) -> int + 'static> {
-    box move |&: x| y + x
+    box move |x| y + x
 }
 
 fn main() {}
index fea628177da41c4933caf9650e3e847dd9f755f5..c34e1a4862f828502032508d0af68fe704b1f1a2 100644 (file)
@@ -18,5 +18,5 @@ fn foo<F:Fn(&int)>(f: F) {
 }
 
 fn main() {
-    foo(|&: x: &int| println!("{}", *x));
+    foo(|x: &int| println!("{}", *x));
 }
index 5d97b886e8e5e4988546424ced05bb8569086d15..06294696bc937dc11ad5110487671b2d8f17ad84 100644 (file)
@@ -50,7 +50,7 @@ enum Foo {
     } else if let Foo::Two(_x) = foo {
         panic!("bad pattern match");
     } else if let Foo::Three(s, _) = foo {
-        assert_eq!(s.as_slice(), "three");
+        assert_eq!(s, "three");
     } else {
         panic!("bad else");
     }
index ce628668996b7566ab68a40174fc1fc4e045b9ba..5d157d875fa4dbec76c3d25e5853c5c21da5e5f3 100644 (file)
@@ -39,7 +39,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 }
 
 macro_rules! t {
-    ($a:expr, $b:expr) => { assert_eq!($a.as_slice(), $b) }
+    ($a:expr, $b:expr) => { assert_eq!($a, $b) }
 }
 
 pub fn main() {
index b30583c666888bc7358074541915c49548e5c8cb..d87b59537df8f120968480a5940df427dfc4dd62 100644 (file)
@@ -15,7 +15,7 @@ fn bad(a: &str, b: &str) {
 }
 
 fn good(a: &str, b: &str) {
-    foo(&[a.as_slice(), b.as_slice()]);
+    foo(&[a, b]);
 }
 
 fn main() {}
index 79a0a54f834ad32de4400931221e008182608140..9150920cf2cc7e5feb79b97ea1649a3c01d50ab1 100644 (file)
@@ -17,8 +17,8 @@
 
 pub fn main () {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() > 1 && args[1].as_slice() == "child" {
+    let args = args;
+    if args.len() > 1 && args[1] == "child" {
         for _ in 0..1000 {
             println!("hello?");
         }
@@ -28,7 +28,7 @@ pub fn main () {
         return;
     }
 
-    let mut p = process::Command::new(args[0].as_slice());
+    let mut p = process::Command::new(&args[0]);
     p.arg("child").stdout(process::Ignored).stderr(process::Ignored);
     println!("{:?}", p.spawn().unwrap().wait());
 }
index 26ee65fa565e2bb3588ed261fcec0e35177e8026..a01d2e6f1a9ed90873de03e2efd58fa2e64f1c41 100644 (file)
@@ -13,7 +13,7 @@
 static NAME: &'static str = "hello world";
 
 fn main() {
-    match NAME.to_ascii_lowercase().as_slice() {
+    match &*NAME.to_ascii_lowercase() {
         "foo" => {}
         _ => {}
     }
index 71b4cbe933427fc9175e6c395d85585bf2da4a08..c3ec3fc40e30a77559d095e4d16ddef29ff17fbe 100644 (file)
@@ -15,6 +15,6 @@ fn f<F:FnOnce()>(p: F) {
 }
 
 pub fn main() {
-    let p = |:| ();
+    let p = || ();
     f(p);
 }
index c75d02c632863413966e3cb493e4e2695a98b13a..12a6d9a82c7b014d2b019eeaa9df4ede82d44ddb 100644 (file)
@@ -13,7 +13,7 @@ struct A {
 }
 
 fn borrow<'a>(binding: &'a A) -> &'a str {
-    match binding.a.as_slice() {
+    match &*binding.a {
         "in" => "in_",
         "ref" => "ref_",
         ident => ident
index 649cf63e84a08a4c3739e3e999c4382bae45cf69..056c86b01f7346c92ab6c179f0a7bbfebd567dc1 100644 (file)
@@ -179,7 +179,7 @@ enum Foo {
     // This test basically mimics how trace_macros! macro is implemented,
     // which is a rare combination of vector patterns, multiple wild-card
     // patterns and guard functions.
-    let r = match [Foo::Bar(0, false)].as_slice() {
+    let r = match [Foo::Bar(0, false)] {
         [Foo::Bar(_, pred)] if pred => 1,
         [Foo::Bar(_, pred)] if !pred => 2,
         _ => 0,
index f2a8bc47db86ed27d47a9c9d53a521ccea6a9bb0..f979235da7197bee2a207c4aa4f3dea501ff2b02 100644 (file)
@@ -16,8 +16,8 @@
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() > 1 && args[1].as_slice() == "child" {
+    let args = args;
+    if args.len() > 1 && args[1] == "child" {
         child();
     } else {
         parent();
@@ -26,13 +26,13 @@ fn main() {
 
 fn parent() {
     let args = os::args();
-    let args = args.as_slice();
-    let mut p = old_io::process::Command::new(args[0].as_slice())
+    let args = args;
+    let mut p = old_io::process::Command::new(&args[0])
                                      .arg("child").spawn().unwrap();
     p.stdin.as_mut().unwrap().write_str("test1\ntest2\ntest3").unwrap();
     let out = p.wait_with_output().unwrap();
     assert!(out.status.success());
-    let s = str::from_utf8(out.output.as_slice()).unwrap();
+    let s = str::from_utf8(&out.output).unwrap();
     assert_eq!(s, "test1\n\ntest2\n\ntest3\n");
 }
 
index 75d3c6f334d071774799677ae2c157b0ab0ccd42..44167ad2096decc595eb7e352de1ebeb11bc8740 100644 (file)
@@ -21,7 +21,7 @@ fn new(s: &str) -> StrWrap {
     }
 
     fn get_s<'a>(&'a self) -> &'a str {
-        self.s.as_slice()
+        &self.s
     }
 }
 
index 953701441256abde027776311a340dad9d102d16..5d7a84d80d4c33910210469ef503108cb677bd0a 100644 (file)
@@ -26,5 +26,5 @@ fn do_stuff<R: Repro>(r: R) -> String {
 }
 
 pub fn main() {
-  assert_eq!("MyStruct".to_string(), do_stuff(|s: MyStruct| format!("{:?}", s)));
+  assert_eq!("MyStruct".to_string(), do_stuff(|s: MyStruct| format!("{:?}", s)));
 }
index ab085be9bc358b32609475ae77e772c653462a80..e850ecbba6e560d6d2ad12b0ac9c0153a44f47b1 100644 (file)
@@ -22,7 +22,7 @@ pub fn main() {
     let obj = UnitLikeStruct;
     let json_str: String = json::encode(&obj).unwrap();
 
-    let json_object = json::from_str(json_str.as_slice());
+    let json_object = json::from_str(&json_str);
     let mut decoder = json::Decoder::new(json_object.unwrap());
     let mut decoded_obj: UnitLikeStruct = Decodable::decode(&mut decoder).unwrap();
 
index a41e57f10025d2e32dfa1429a03db8261783b397..5f44eb7dcd23e2ed6a987e2b9b1e9a7efffbfac8 100644 (file)
@@ -16,7 +16,7 @@
 
 fn main() {
     let args = os::args();
-    if args.len() > 1 && args[1].as_slice() == "child" {
+    if args.len() > 1 && args[1] == "child" {
         return child()
     }
 
@@ -32,7 +32,7 @@ fn child() {
 
 fn test() {
     let args = os::args();
-    let mut p = Command::new(args[0].as_slice()).arg("child")
+    let mut p = Command::new(&args[0]).arg("child")
                                      .stdin(process::Ignored)
                                      .stdout(process::Ignored)
                                      .stderr(process::Ignored)
index e7516639db0c39dd5dd1b3c3aabb22ccad59ec8d..44465fe5f80ee493fdacb95d5c2245638483c9f6 100644 (file)
@@ -10,5 +10,5 @@
 
 
 pub fn main() {
-    {|&: i| if 1 == i { }};
+    {|i| if 1 == i { }};
 }
index 4d05b98147bd6237ec9ba8b5c065a8d0c02f5cb6..933e7e40f06d34ce23ae96de299da6a594acb62b 100644 (file)
@@ -58,6 +58,6 @@ fn match_indices<'a, M, T: IntoMatcher<'a, M>>(s: &'a str, from: T) -> MatchIndi
 
 fn main() {
     let s = "abcbdef";
-    match_indices(s, |&mut: c: char| c == 'b')
+    match_indices(s, |c: char| c == 'b')
         .collect::<Vec<(uint, uint)>>();
 }
index a441729e2d0ba015287dad9217a5a823f59a9a4a..ace1f00b023b58a8847ab40dae2cf496d1c98cd7 100644 (file)
@@ -31,7 +31,7 @@ macro_rules! demo {
             }
             assert_eq!((x,y), (1,1));
             let b: &[_] = &["out", "in"];
-            assert_eq!(history.as_slice(), b);
+            assert_eq!(history, b);
         }
     }
 }
index 5ae0ad6c3e97453231f00f4783e8d9cc9a901226..e5fead72bebeb44b5aa4acd15f83c2ad31bc6ce8 100644 (file)
@@ -17,7 +17,7 @@ fn main() {
         let mut out = stdio::stdout();
         out.write(&['a' as u8; 128 * 1024]).unwrap();
     } else {
-        let out = Command::new(args[0].as_slice()).arg("child").output();
+        let out = Command::new(&args[0]).arg("child").output();
         let out = out.unwrap();
         assert!(out.status.success());
     }
index b37c71bc326270ba0d745fe883275e2fd44d9f4c..30a3183c808560d99b06a4a1e041e844f61bfdf4 100644 (file)
@@ -1,3 +1,5 @@
+// no-prefer-dynamic
+
 // 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.
@@ -17,7 +19,7 @@
 fn main() {
     // If we're the child, make sure we were invoked correctly
     let args = os::args();
-    if args.len() > 1 && args[1].as_slice() == "child" {
+    if args.len() > 1 && args[1] == "child" {
         // FIXME: This should check the whole `args[0]` instead of just
         // checking that it ends_with the executable name. This
         // is needed because of Windows, which has a different behavior.
@@ -45,9 +47,9 @@ fn test() {
     // Append the new directory to our own PATH.
     let mut path = os::split_paths(os::getenv("PATH").unwrap_or(String::new()));
     path.push(child_dir.clone());
-    let path = os::join_paths(path.as_slice()).unwrap();
+    let path = os::join_paths(&path).unwrap();
 
-    let child_output = Command::new("mytest").env("PATH", path.as_slice())
+    let child_output = Command::new("mytest").env("PATH", path)
                                              .arg("child")
                                              .output().unwrap();
 
index 7d53b6729516da2dbbcb08dfde8b9024b058cc76..ab9554f65d4c89d93aa6c813b883551d737809ea 100644 (file)
@@ -48,7 +48,7 @@ fn match_on_binding() {
 
 fn match_on_upvar() {
     let mut foo = Some(box 8i32);
-    let f = move|:| {
+    let f = move|| {
         match foo {
             None => {},
             Some(x) => {
index e7422e233a62903385b1a0b8823eb7c6de44b47d..48ea3a93296e3194420f2e9c79c05e23c907cade 100644 (file)
@@ -10,5 +10,5 @@
 
 fn main() {
     let mut buf = Vec::new();
-    |&mut: c: u8| buf.push(c);
+    |c: u8| buf.push(c);
 }
index 6b03a499f15773728e54d603a344f929bfa4d8d5..ca40b2fe4c7d06fce8db083777c5aa4c88454ab5 100644 (file)
@@ -15,7 +15,7 @@
 
 fn main() {
     let y = 0u8;
-    let closure = move |&: x| y + x;
+    let closure = move |x| y + x;
 
     // Check that both closures are capturing by value
     assert_eq!(1, mem::size_of_val(&closure));
index 95b7728b47f993766bf149c6401987feb5cf2c20..daf09047bef723649a519d9d5a952376ce28b4ec 100644 (file)
@@ -21,7 +21,7 @@ struct Parser<'a, I, O> {
 impl<'a, I: 'a, O: 'a> Parser<'a, I, O> {
     fn compose<K: 'a>(mut self, mut rhs: Parser<'a, O, K>) -> Parser<'a, I, K> {
         Parser {
-            parse: box move |&mut: x: I| {
+            parse: box move |x: I| {
                 match (self.parse)(x) {
                     Ok(r) => (rhs.parse)(r),
                     Err(e) => Err(e)
index d426f82f89fc96fdce9c20f6888520c23e251291..cc427dd941b73d7b67d90f986d7e216efb3e37e5 100644 (file)
@@ -47,7 +47,7 @@ fn main() {
     {
         let mut test = X(box 5);
         {
-            let mut change = |&mut:| { *test = 10 };
+            let mut change = || { *test = 10 };
             change();
         }
         assert_eq!(*test, 10);
index cb12d138a5f29ce4b2a880968a0f311c0852f0ab..c2bcbe045c0cc07ac5c51e59a4cbfffd1e46893b 100644 (file)
@@ -10,5 +10,5 @@
 
 pub fn main() {
     let x = [1, 2, 3];
-    let y = x.as_slice();
+    let y = x;
 }
index e58fbe0b4c2830d0756e1f7cb81bb84a8fff5c98..3cff16409cb9b811c2b6fdf782bb18fdb7824578 100644 (file)
@@ -21,6 +21,6 @@ fn main() {
     // There is currently no safe way to construct a `Box<str>`, so improvise
     let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8];
     let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) };
-    assert_eq!(box_str.as_slice(), "hello");
+    assert_eq!(&*box_str, "hello");
     f(box_str);
 }
index d9d2c771390fdfacccef56382ca63d93f0d5b698..f8fbd680dcb9ecfddc59a9668fb9a5be4a065d8d 100644 (file)
@@ -12,7 +12,7 @@
 
 fn main() {
     struct Symbol<'a, F: Fn(Vec<&'a str>) -> &'a str> { function: F }
-    let f = |&: x: Vec<&str>| -> &str "foobar";
+    let f = |x: Vec<&str>| -> &str "foobar";
     let sym = Symbol { function: f };
     (sym.function)(vec![]);
 }
index da6c83142eab62c3a20244c07b8b4354adc93bbe..3774aaa190333b97e687a0e4d76842c3e5781cfb 100644 (file)
@@ -17,5 +17,5 @@ fn action(cb: Thunk<uint, uint>) -> uint {
 }
 
 pub fn main() {
-    println!("num: {}", action(Thunk::with_arg(move |:u| u)));
+    println!("num: {}", action(Thunk::with_arg(move |u| u)));
 }
index a2152db6884ac9fd269c26296cf286d438e85f22..7a5a86822afda0233e98aa0e2222b44804994ae8 100644 (file)
@@ -20,7 +20,7 @@ pub fn propagate<T, E, F, G>(action: F) -> Thunk<Result<T, E>, Result<T, E>>
         E: Promisable + Clone,
         F: FnOnce(&T) -> Result<T, E> + Send,
         G: FnOnce(Result<T, E>) -> Result<T, E> {
-    Thunk::with_arg(move |result: Result<T, E>| {
+    Thunk::with_arg(move |result: Result<T, E>| {
         match result {
             Ok(ref t) => action(t),
             Err(ref e) => Err(e.clone()),
index 7878d698e52ae148190fd3ce9b69aaec3e2cc279..e5532b4550baab32c48a59b2191a8ee617f53141 100644 (file)
@@ -11,7 +11,7 @@
 const X: &'static str = "12345";
 
 fn test(s: String) -> bool {
-    match s.as_slice() {
+    match &*s {
         X => true,
         _ => false
     }
index ef2c15c748ca36a317efa02f7993daf4215a9d20..8f560258d9f4795fe0aae54431c215b2df1d184b 100644 (file)
@@ -17,5 +17,5 @@
 fn main() {
     let x = 2u8;
     let y = 3u8;
-    assert_eq!((move |:| x + y)(), 5);
+    assert_eq!((move || x + y)(), 5);
 }
index 6a2f73a787a4835c1d54df7682cf467965d6a69e..bb2907241c2c6bfc06c5754f46f79e04c2f7bc09 100644 (file)
@@ -20,7 +20,7 @@ pub fn inside<F: Fn()>(c: F) {
 // Use different number of type parameters and closure type to trigger
 // an obvious ICE when param environments are mixed up
 pub fn outside<A,B>() {
-    inside(|&:| {});
+    inside(|| {});
 }
 
 fn main() {
index be6dd583132ecf742f94741a236a5dd8505d3e4e..698b61e5759ad98268aece46d4ccec0bbf109963 100644 (file)
@@ -17,7 +17,7 @@ trait Tr {
     fn foo(&self);
 
     fn bar(&self) {
-        (|:| { self.foo() })()
+        (|| { self.foo() })()
     }
 }
 
index 6a04e68af0cb3c028abcd5119523dba397f7599e..0338a4eff22389e2ac1dc9a88dc51459437dcddd 100644 (file)
@@ -17,5 +17,5 @@
 extern crate "issue-18711" as issue;
 
 fn main() {
-    (|:| issue::inner(()))();
+    (|| issue::inner(()))();
 }
index 9557d7e4fa816d5f8afa37fd16551f05f447d8e1..031a63ba474c181ae7b2a81438decc4a1c6a2627 100644 (file)
@@ -14,7 +14,7 @@
 struct LifetimeStruct<'a>;
 
 fn main() {
-    takes_hrtb_closure(|&mut: lts| println!("{:?}", lts));
+    takes_hrtb_closure(|lts| println!("{:?}", lts));
 }
 
 fn takes_hrtb_closure<F: for<'a>FnMut(LifetimeStruct<'a>)>(mut f: F) {
index 120ada96c15b731c932c0f5e74f680ddb94556c2..5f2805ed354553f58dfd5d28847b20adea5cc15d 100644 (file)
 #![allow(non_camel_case_types)]
 
 pub fn main() {
-    let one = |&:| {
+    let one = || {
         enum r { a };
         r::a as uint
     };
-    let two = |&:| {
+    let two = || {
         enum r { a };
         r::a as uint
     };
index c75abd88963433dbb92f6901e3d8a738f43cad96..ca2a4e546b7c8abd8aa9ada2868c2c34dccc3a41 100644 (file)
@@ -12,6 +12,6 @@
 
 fn main() {
     let x = 5us;
-    let command = Arc::new(Box::new(|&:| { x*2 }));
+    let command = Arc::new(Box::new(|| { x*2 }));
     assert_eq!(command(), 10);
 }
diff --git a/src/test/run-pass/issue-21891.rs b/src/test/run-pass/issue-21891.rs
new file mode 100644 (file)
index 0000000..d6e6f23
--- /dev/null
@@ -0,0 +1,16 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+static foo: [uint; 3] = [1, 2, 3];
+
+static slice_1: &'static [uint] = &foo;
+static slice_2: &'static [uint] = &foo;
+
+fn main() {}
index c08bdf54408122447313c8e026d7b6fa6e532964..3e7deee6ec10720b4690df4336df72e1beae4bca 100644 (file)
@@ -14,7 +14,7 @@
 type Connection = Box<FnMut(Vec<u8>) + 'static>;
 
 fn f() -> Option<Connection> {
-    let mock_connection: Connection = box |&mut: _| {};
+    let mock_connection: Connection = box |_| {};
     Some(mock_connection)
 }
 
index 60c53450004363917843728b96dda31d397ed800..6fc8c9c6843ee2cb3eeea4536f508e31221e4282 100644 (file)
@@ -10,6 +10,6 @@
 
 pub fn main() {
   let x = 1u;
-  let y = |&:| x;
+  let y = || x;
   let _z = y();
 }
index 69a148d4108ea1c5c7e1adee6247ee6f83916627..754412ea949381c7059b1a6d6472d9f7a76d2489 100644 (file)
@@ -24,6 +24,6 @@ pub fn main() {
     let mut table = HashMap::new();
     table.insert("one".to_string(), 1);
     table.insert("two".to_string(), 2);
-    assert!(check_strs(format!("{:?}", table).as_slice(), "HashMap {\"one\": 1, \"two\": 2}") ||
-            check_strs(format!("{:?}", table).as_slice(), "HashMap {\"two\": 2, \"one\": 1}"));
+    assert!(check_strs(&format!("{:?}", table), "HashMap {\"one\": 1, \"two\": 2}") ||
+            check_strs(&format!("{:?}", table), "HashMap {\"two\": 2, \"one\": 1}"));
 }
index 5d02a1b2bd2982a52d1c6958c23e1527e8de9385..f4b85e03eaeac031dfb37f2e8de0f9cb7effcdbe 100644 (file)
@@ -162,7 +162,7 @@ pub fn check_strs(actual: &str, expected: &str) -> bool {
 
 fn test_ascii_art_ctor() {
     let art = AsciiArt(3, 3, '*');
-    assert!(check_strs(art.to_string().as_slice(), "...\n...\n..."));
+    assert!(check_strs(&art.to_string(), "...\n...\n..."));
 }
 
 
@@ -171,7 +171,7 @@ fn test_add_pt() {
     art.add_pt(0, 0);
     art.add_pt(0, -10);
     art.add_pt(1, 2);
-    assert!(check_strs(art.to_string().as_slice(), "*..\n...\n.*."));
+    assert!(check_strs(&art.to_string(), "*..\n...\n.*."));
 }
 
 
@@ -179,7 +179,7 @@ fn test_shapes() {
     let mut art = AsciiArt(4, 4, '*');
     art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}});
     art.add_point(Point {x: 2, y: 2});
-    assert!(check_strs(art.to_string().as_slice(), "****\n*..*\n*.**\n****"));
+    assert!(check_strs(&art.to_string(), "****\n*..*\n*.**\n****"));
 }
 
 pub fn main() {
index c9baab3cfa49e054c5638a7d3513501e9caf4b84..f10303e8d8479a1eb433c4dbe1122628e3a84de5 100644 (file)
 
 fn parse_args() -> String {
     let args = ::std::os::args();
-    let args = args.as_slice();
+    let args = args;
     let mut n = 0;
 
     while n < args.len() {
-        match args[n].as_slice() {
+        match &*args[n] {
             "-v" => (),
             s => {
                 return s.to_string();
index 69255c576811fd075b8c5b039e276f92a75e950f..dd9a6fb35439e99929ab417e0e8a3ce46e6cd1c8 100644 (file)
@@ -11,7 +11,7 @@
 // Regression test for issue #5239
 
 pub fn main() {
-    let _f = |&: ref x: int| { *x };
+    let _f = |ref x: int| { *x };
     let foo = 10;
     assert!(_f(foo) == 10);
 }
index 7f56e42a4830863d6ccaa82df9c88ab53f59e123..f87f1d8af7649fb723fdd9c707311c72059207dd 100644 (file)
@@ -12,6 +12,6 @@
 
 pub fn main() {
     let s: String = "foobar".to_string();
-    let mut t: &str = s.as_slice();
+    let mut t: &str = &s;
     t = &t[0..3]; // for master: str::view(t, 0, 3) maybe
 }
index 07c7c6888e1ebdb4780246c8c35c016d86179722..39f387afaba048905de543623e8600b6f4c7b14b 100644 (file)
@@ -21,7 +21,7 @@ fn squarei<'a>(x: int, op: &'a mut OpInt) -> int { op.call(x, x) }
 fn muli(x:int, y:int) -> int { x * y }
 
 pub fn main() {
-    let mut f = |&mut: x, y| muli(x, y);
+    let mut f = |x, y| muli(x, y);
     {
         let g = &mut f;
         let h = g as &mut OpInt;
index 8a953cea9048dd02463c64e8586f75e696e3038b..9e36b1f5082d03dad3f1a48bc3ed9a38326eb600 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// Regresion test for issue 7660
+// Regression test for issue 7660
 // rvalue lifetime too short when equivalent `match` works
 
 extern crate collections;
index b2ccc092358e2ed96d270fffb2d89bfeedf334a3..e47999fc468607c2dc3a13ff6df57c67c76554a2 100644 (file)
@@ -20,5 +20,5 @@ pub fn main() {
     let _: () = f(| | { });
     // empty block with no type info should compile too
     let _ = f(||{});
-    let _ = (|&:|{});
+    let _ = (||{});
 }
index 379b8f7700e594fb66d8b043a8ab6ceda260f74b..b1c443dd0c51b5713a2721c538bf0d84b18bbc5d 100644 (file)
@@ -18,9 +18,9 @@ pub fn main() {
     let x  = [(), ()];
     let slice = &x[..1];
 
-    assert_repr_eq(&abc[], "[1, 2, 3]".to_string());
-    assert_repr_eq(&tf[], "[true, false]".to_string());
-    assert_repr_eq(&x[], "[(), ()]".to_string());
+    assert_repr_eq(&abc[..], "[1, 2, 3]".to_string());
+    assert_repr_eq(&tf[..], "[true, false]".to_string());
+    assert_repr_eq(&x[..], "[(), ()]".to_string());
     assert_repr_eq(slice, "[()]".to_string());
-    assert_repr_eq(&x[], "[(), ()]".to_string());
+    assert_repr_eq(&x[..], "[(), ()]".to_string());
 }
index 2ef1c1d264a409b396eb60008e7f3fde064c19da..6c843993040f38d65dcf0a77c0bb90801c982265 100644 (file)
@@ -29,7 +29,7 @@ fn Ident_new() -> Ident {
 
 pub fn light_fuse(fld: Box<bomb>) {
     int3!();
-    let f = |&:| {
+    let f = || {
         int3!();
         fld.boom(Ident_new()); // *** 1
     };
index 0fe520e59d622050bec7e282a3248b9d4f6795e7..da5338b8c3c61438bdfdf74362909e788cb94fda 100644 (file)
@@ -19,5 +19,5 @@ pub fn main() {
         a: &["test".to_string()],
         b: Some(b),
     };
-    assert_eq!(a.b.as_ref().unwrap()[0].as_slice(), "foo");
+    assert_eq!(a.b.as_ref().unwrap()[0], "foo");
 }
index 07212237305efa7903f92bb06ad29d93e81347c6..c501420fa617a00c212fc6f5c2a609512da99d3e 100644 (file)
@@ -34,7 +34,7 @@ pub fn main() {
         bar: box 32,
     };
     Thing1 {
-        baz: Vec::new().as_slice(),
+        baz: &Vec::new(),
         bar: box 32,
     };
     let _t2_fixed = Thing2 {
@@ -42,7 +42,7 @@ pub fn main() {
         bar: 32,
     };
     Thing2 {
-        baz: Vec::new().as_slice(),
+        baz: &Vec::new(),
         bar: 32,
     };
 }
index af60f18e542283168fc8d63baedc618ce5c1a5fb..15195482ed693921f39beac19f320a62450fb2a0 100644 (file)
@@ -37,19 +37,19 @@ fn test_heap_log() {
 fn test_append() {
     let mut s = String::new();
     s.push_str("a");
-    assert_eq!(s.as_slice(), "a");
+    assert_eq!(s, "a");
 
     let mut s = String::from_str("a");
     s.push_str("b");
     println!("{}", s.clone());
-    assert_eq!(s.as_slice(), "ab");
+    assert_eq!(s, "ab");
 
     let mut s = String::from_str("c");
     s.push_str("offee");
-    assert!(s.as_slice() == "coffee");
+    assert!(s == "coffee");
 
     s.push_str("&tea");
-    assert!(s.as_slice() == "coffee&tea");
+    assert!(s == "coffee&tea");
 }
 
 pub fn main() {
index b33e6512b18bdafab6c280bc5755150237ab6ec9..3c2a3f355b412e15ecf549bba8e8318d559fc438 100644 (file)
@@ -16,7 +16,7 @@ struct Refs { refs: Vec<int> , n: int }
 
 pub fn main() {
     let mut e = Refs{refs: vec!(), n: 0};
-    let _f = |&:| println!("{}", e.n);
-    let x: &[int] = e.refs.as_slice();
+    let _f = || println!("{}", e.n);
+    let x: &[int] = &e.refs;
     assert_eq!(x.len(), 0);
 }
index 2d70fa0c8198932d9599f52ef3c15f0fe480a826..350ec68a7d1495347ffe02ba11595b627cdb5ef9 100644 (file)
@@ -12,8 +12,8 @@
 // ignore-android
 // ignore-windows #13361
 
+#![feature(lang_items, start, no_std)]
 #![no_std]
-#![feature(lang_items, start)]
 
 extern crate "lang-item-public" as lang_lib;
 
index 0cd8c13a4e10a60644ec0c80d887de9f236d1919..4231e5dba9f0f416b86b2f61b7713551a7a68a3b 100644 (file)
@@ -19,7 +19,8 @@ struct A { a: Box<isize> }
 fn foo() -> Box<FnMut() -> isize + 'static> {
     let k = box 22;
     let _u = A {a: k.clone()};
-    let result  = |&mut:| 22;
+    // FIXME(#16640) suffix in `22i` suffix shouldn't be necessary
+    let result  = || 22i;
     box result
 }
 
index 44daa52886cf85872156234107c813c6439bd79b..1be0ee4a285514c4ab5c23db4f92f866a521c083 100644 (file)
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() > 1 && args[1].as_slice() == "child" {
+    let args = args;
+    if args.len() > 1 && args[1] == "child" {
         debug!("foo");
         debug!("bar");
         return
     }
 
-    let p = Command::new(args[0].as_slice())
+    let p = Command::new(&args[0])
                     .arg("child")
                     .spawn().unwrap().wait_with_output().unwrap();
     assert!(p.status.success());
-    let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines();
+    let mut lines = str::from_utf8(&p.error).unwrap().lines();
     assert!(lines.next().unwrap().contains("foo"));
     assert!(lines.next().unwrap().contains("bar"));
 }
index 686a9a002cebf1bb59942de3033699d430df18e2..d96ff869fa0ab06567d81b4d1a1f8b4c263cb99e 100644 (file)
@@ -13,7 +13,7 @@
 fn main() {
     let mut foo = Vec::new();
     'foo: for i in &[1, 2, 3] {
-        foo.push(i);
+        foo.push(*i);
     }
 }
 
index 60a5904cff31147391192a8a1ad03b045b7e2fcf..301d99a7e20b32b807b9dcce761162c782b01d47 100644 (file)
@@ -18,8 +18,8 @@ enum t { tag1(String), tag2, }
 
     match t::tag1("test".to_string()) {
       t::tag2 => panic!(),
-      t::tag1(ref s) if "test" != s.as_slice() => panic!(),
-      t::tag1(ref s) if "test" == s.as_slice() => (),
+      t::tag1(ref s) if "test" != &**s => panic!(),
+      t::tag1(ref s) if "test" == &**s => (),
       _ => panic!()
     }
 
index 76895af099d6d0109f9216c3ad9cd3bb975e0fbc..0ad600dd85d9338a1ed33c230053c369fa0098c7 100644 (file)
@@ -41,7 +41,7 @@ fn main() {
     let mut buf = [0_u8; 6];
 
     {
-        let mut writer = buf.as_mut_slice();
+        let mut writer: &mut [_] = &mut buf;
         writer.my_write(&[0, 1, 2]).unwrap();
         writer.my_write(&[3, 4, 5]).unwrap();
     }
index 92c5e025b9b2149692aa23bb41c73406015de143..cb487a34f338876dc9e60557be588322c8577b2c 100644 (file)
@@ -31,5 +31,5 @@ pub fn main() {
     sb.append("Hello, ");
     sb.append("World!");
     let str = to_string(sb);
-    assert_eq!(str.as_slice(), "Hello, World!");
+    assert_eq!(str, "Hello, World!");
 }
index 388b814b2af1068e18d75d78e801169f03bb2180..b1f7da17c8f80767bee34c713ab15627319fe355 100644 (file)
@@ -17,7 +17,7 @@ fn f(mut y: Box<int>) {
 }
 
 fn g() {
-    let frob = |&: mut q: Box<int>| { *q = 2; assert!(*q == 2); };
+    let frob = |mut q: Box<int>| { *q = 2; assert!(*q == 2); };
     let w = box 37;
     frob(w);
 
index 8be200d3bf32c852ae091d26ba04ad57540a1df2..d3ae80861f231c5f29aaa57ed211104b7c59c5b8 100644 (file)
@@ -75,6 +75,6 @@ struct A {
     x = 30;
     assert_eq!(x, 30);
 
-    (|&: A { x: mut t }: A| { t = t+1; t })(A { x: 34 });
+    (|A { x: mut t }: A| { t = t+1; t })(A { x: 34 });
 
 }
index 2888389bcceabfb4cce2b5f03b500e0f6baecf95..7430f730f3b17d0799c24873434ea9e184128053 100644 (file)
@@ -18,5 +18,5 @@ pub fn main() {
     let s = "\\{20}";
     let mut correct_s = String::from_str("\\");
     correct_s.push_str("{20}");
-    assert_eq!(s, correct_s.as_slice());
+    assert_eq!(s, correct_s);
 }
index dcafb5f451f3d892f22557ac55d3e749221fa87b..f5f34607aff7b8955a8e0081915c83604503c253 100644 (file)
@@ -16,6 +16,7 @@
 // This tests that libraries built with #[no_std] can be linked to crates with
 // #[no_std] and actually run.
 
+#![feature(no_std)]
 #![no_std]
 
 extern crate no_std_crate;
index a866be43a051473b5b8fcc9fe0921a10b8307414..3710f1b9d3052e2a27c08e3376a44f00f8649d80 100644 (file)
@@ -60,6 +60,6 @@ fn main() {
     }
     unsafe {
         let expected: &[_] = &[1, 2, 3];
-        assert_eq!(expected, ORDER.as_slice());
+        assert_eq!(expected, ORDER);
     }
 }
index c9e2f893c0f34e121775895423a45491802e3062..ca9ee469e38976ec8e49f729de97a428fb17db33 100644 (file)
@@ -35,13 +35,13 @@ fn recurse() {
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() > 1 && args[1].as_slice() == "recurse" {
+    let args = args;
+    if args.len() > 1 && args[1] == "recurse" {
         let _t = Thread::scoped(recurse);
     } else {
-        let recurse = Command::new(args[0].as_slice()).arg("recurse").output().unwrap();
+        let recurse = Command::new(&args[0]).arg("recurse").output().unwrap();
         assert!(!recurse.status.success());
-        let error = String::from_utf8_lossy(recurse.error.as_slice());
+        let error = String::from_utf8_lossy(&recurse.error);
         println!("wut");
         println!("`{}`", error);
         assert!(error.contains("has overflowed its stack"));
index 846fbd477e04edecbe2039b4b9e0075ce8360881..fba86d74816790438fe07d986d7ccf82c49f5ee4 100644 (file)
@@ -35,13 +35,12 @@ fn recurse() {
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() > 1 && args[1].as_slice() == "recurse" {
+    if args.len() > 1 && args[1] == "recurse" {
         recurse();
     } else {
-        let recurse = Command::new(args[0].as_slice()).arg("recurse").output().unwrap();
+        let recurse = Command::new(&args[0]).arg("recurse").output().unwrap();
         assert!(!recurse.status.success());
-        let error = String::from_utf8_lossy(recurse.error.as_slice());
+        let error = String::from_utf8_lossy(&recurse.error);
         assert!(error.contains("has overflowed its stack"));
     }
 }
index 97539a076ff1502c1da7169e49a0108c72f20362..7dfd46fb995a207706de5f9326a7c820b1e06275 100644 (file)
@@ -35,20 +35,20 @@ fn loud_recurse() {
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() > 1 && args[1].as_slice() == "silent" {
+    let args = args;
+    if args.len() > 1 && args[1] == "silent" {
         silent_recurse();
-    } else if args.len() > 1 && args[1].as_slice() == "loud" {
+    } else if args.len() > 1 && args[1] == "loud" {
         loud_recurse();
     } else {
-        let silent = Command::new(args[0].as_slice()).arg("silent").output().unwrap();
+        let silent = Command::new(&args[0]).arg("silent").output().unwrap();
         assert!(!silent.status.success());
-        let error = String::from_utf8_lossy(silent.error.as_slice());
+        let error = String::from_utf8_lossy(&silent.error);
         assert!(error.contains("has overflowed its stack"));
 
-        let loud = Command::new(args[0].as_slice()).arg("loud").output().unwrap();
+        let loud = Command::new(&args[0]).arg("loud").output().unwrap();
         assert!(!loud.status.success());
-        let error = String::from_utf8_lossy(silent.error.as_slice());
+        let error = String::from_utf8_lossy(&silent.error);
         assert!(error.contains("has overflowed its stack"));
     }
 }
index baa9709eb76427aafe406256b427f9491bc652ab..fcf0feb6e30d00652cfc4ca877bd6bd51fd51e7d 100644 (file)
@@ -34,13 +34,13 @@ pub fn main() {
     assert_eq!((i_value, *i.borrow()), (2, 5));
 
     let s = Rc::new("foo".to_string());
-    assert_eq!(s.as_slice(), "foo");
+    assert_eq!(&**s, "foo");
 
     let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
     mut_s.borrow_mut().push_str("bar");
     // HACK assert_eq! would panic here because it stores the LHS and RHS in two locals.
-    assert!(mut_s.borrow().as_slice() == "foobar");
-    assert!(mut_s.borrow_mut().as_slice() == "foobar");
+    assert!(&**mut_s.borrow() == "foobar");
+    assert!(&**mut_s.borrow_mut() == "foobar");
 
     let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
     p.borrow_mut().x = 3;
index 03fa64fb87fbd31dee4e30462d68ae20ed590bb7..f3091b53e8badc02e5223d2b4a30feb595f0889e 100644 (file)
@@ -82,5 +82,5 @@ pub fn main() {
     // Check the final states.
     assert_eq!(*n, 2);
     let expected: &[_] = &[1, 2];
-    assert_eq!((*v).as_slice(), expected);
+    assert_eq!((*v), expected);
 }
index fdaddca091f8f4995ebb90d6e32dd7c40ca63bb0..f56e7d56fe16aec00df2034f97375ea37f461eb2 100644 (file)
@@ -33,13 +33,13 @@ pub fn main() {
 
     let s = Rc::new("foo".to_string());
     assert_eq!(*s, "foo".to_string());
-    assert_eq!((*s).as_slice(), "foo");
+    assert_eq!((*s), "foo");
 
     let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
     (*(*mut_s).borrow_mut()).push_str("bar");
     // assert_eq! would panic here because it stores the LHS and RHS in two locals.
-    assert!((*(*mut_s).borrow()).as_slice() == "foobar");
-    assert!((*(*mut_s).borrow_mut()).as_slice() == "foobar");
+    assert!((*(*mut_s).borrow()) == "foobar");
+    assert!((*(*mut_s).borrow_mut()) == "foobar");
 
     let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
     (*(*p).borrow_mut()).x = 3;
index 637d2c94694455d84aa64eccca52791000e13061..d5ccf8cd2befb0f4f18e29fc0021ba49f4d814bf 100644 (file)
@@ -33,8 +33,6 @@ fn index(&self, z: &int) -> &int {
 }
 
 impl IndexMut<int> for Foo {
-    type Output = int;
-
     fn index_mut(&mut self, z: &int) -> &mut int {
         if *z == 0 {
             &mut self.x
index 0afdb24a81cc0dbf64dd86b437faeb4af54fa4bd..10ca3804eaedbc187ab128e619f45d20cd7c41dd 100644 (file)
@@ -28,8 +28,6 @@ fn index(&self, z: &int) -> &int {
 }
 
 impl IndexMut<int> for Foo {
-    type Output = int;
-
     fn index_mut(&mut self, z: &int) -> &mut int {
         if *z == 0 {
             &mut self.x
index c718b948f8dc07723f4dfe49a69f351af11775dd..e4f1df2d6376df916c553f21a2e8ec7abbaf7d17 100644 (file)
@@ -14,8 +14,8 @@ struct Foo {
 }
 
 pub fn main() {
-    let f = |&: (x, _): (int, int)| println!("{}", x + 1);
-    let g = |&: Foo { x: x, y: _y }: Foo| println!("{}", x + 1);
+    let f = |(x, _): (int, int)| println!("{}", x + 1);
+    let g = |Foo { x: x, y: _y }: Foo| println!("{}", x + 1);
     f((2, 3));
     g(Foo { x: 1, y: 2 });
 }
index dcaca667fbb4f315331eb54b6c73f7a6b3173704..8b99e8a947cf5877de567e44a0acad1870606c85 100644 (file)
@@ -41,12 +41,12 @@ fn main() {
     // restore original environment
     match old_env {
         None => os::unsetenv("RUN_TEST_NEW_ENV"),
-        Some(val) => os::setenv("RUN_TEST_NEW_ENV", val.as_slice())
+        Some(val) => os::setenv("RUN_TEST_NEW_ENV", val)
     }
 
     let prog = cmd.spawn().unwrap();
     let result = prog.wait_with_output().unwrap();
-    let output = String::from_utf8_lossy(result.output.as_slice());
+    let output = String::from_utf8_lossy(&result.output);
 
     assert!(!output.contains("RUN_TEST_NEW_ENV"),
             "found RUN_TEST_NEW_ENV inside of:\n\n{}", output);
index c6fd55272610957b83f1f05a1c11beb360f4f7f4..15cc128d380db4db7cb62aed971fe25ce7bfb5ce 100644 (file)
@@ -58,12 +58,12 @@ fn main() {
         let p = Command::new(&child_path)
                         .arg(arg)
                         .cwd(&cwd)
-                        .env_set_all(my_env.as_slice())
+                        .env_set_all(&my_env)
                         .spawn().unwrap().wait_with_output().unwrap();
 
         // display the output
-        assert!(old_io::stdout().write(p.output.as_slice()).is_ok());
-        assert!(old_io::stderr().write(p.error.as_slice()).is_ok());
+        assert!(old_io::stdout().write(&p.output).is_ok());
+        assert!(old_io::stderr().write(&p.error).is_ok());
 
         // make sure the child succeeded
         assert!(p.status.success());
@@ -74,7 +74,7 @@ fn main() {
         assert!(my_cwd.ends_with_path(&Path::new(child_dir)));
 
         // check arguments
-        assert_eq!(my_args[1].as_slice(), arg);
+        assert_eq!(&*my_args[1], arg);
 
         // check environment variable
         assert!(my_env.contains(&env));
index 11e8bfa48f694fd11f373dbdfd4fe4b9f8935a83..5d2337e3819aa925daa363d285530ec6c8df1947 100644 (file)
@@ -14,6 +14,7 @@ fn foo() -> int { 42 }
 
 // Test that range syntax works in return statements
 fn return_range_to() -> ::std::ops::RangeTo<i32> { return ..1; }
+fn return_full_range() -> ::std::ops::RangeFull { return ..; }
 
 pub fn main() {
     let mut count = 0;
index c947220f1f858886c19e93a6706db88dc1582c69..cd49094851695df64a5454475015023341ff0dd2 100644 (file)
@@ -55,5 +55,8 @@ fn main() {
 
     let x = [1]..[2];
     assert!(x == (([1])..([2])));
+
+    let y = ..;
+    assert!(y == (..));
 }
 
index 8682d18185fe41b0dbb4b62fec664e1b8e1243fe..6a5da0149947abd8225cc0b4bd02cdf745a4e480 100644 (file)
@@ -24,7 +24,7 @@ fn call_sum(x: &[int]) -> int { x.sum_() }
 
 pub fn main() {
     let x = vec!(1, 2, 3);
-    let y = call_sum(x.as_slice());
+    let y = call_sum(&x);
     println!("y=={}", y);
     assert_eq!(y, 6);
 
index c932116243bffc15bce07f8e5cd22b5094a35db7..441c9d79e79f3832c15a53942db8282068dc4fa1 100644 (file)
@@ -28,7 +28,7 @@ fn main() {
 unsafe fn test_triangle() -> bool {
     static COUNT : uint = 16;
     let mut ascend = repeat(ptr::null_mut()).take(COUNT).collect::<Vec<_>>();
-    let ascend = ascend.as_mut_slice();
+    let ascend = &mut *ascend;
     static ALIGN : uint = 1;
 
     // Checks that `ascend` forms triangle of ascending size formed
@@ -103,7 +103,7 @@ fn idx_to_size(i: uint) -> uint { (i+1) * 10 }
         }
     }
 
-    sanity_check(ascend.as_slice());
+    sanity_check(&*ascend);
     test_1(ascend); // triangle -> square
     test_2(ascend); // square -> triangle
     test_3(ascend); // triangle -> square
@@ -128,10 +128,10 @@ unsafe fn test_1(ascend: &mut [*mut u8]) {
             assert!(old_size < new_size);
 
             ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
-            sanity_check(ascend.as_slice());
+            sanity_check(&*ascend);
 
             ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN);
-            sanity_check(ascend.as_slice());
+            sanity_check(&*ascend);
         }
     }
 
@@ -143,10 +143,10 @@ unsafe fn test_2(ascend: &mut [*mut u8]) {
             assert!(new_size < old_size);
 
             ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
-            sanity_check(ascend.as_slice());
+            sanity_check(&*ascend);
 
             ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN);
-            sanity_check(ascend.as_slice());
+            sanity_check(&*ascend);
         }
     }
 
@@ -158,10 +158,10 @@ unsafe fn test_3(ascend: &mut [*mut u8]) {
             assert!(old_size < new_size);
 
             ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN);
-            sanity_check(ascend.as_slice());
+            sanity_check(&*ascend);
 
             ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
-            sanity_check(ascend.as_slice());
+            sanity_check(&*ascend);
         }
     }
 
@@ -173,10 +173,10 @@ unsafe fn test_4(ascend: &mut [*mut u8]) {
             assert!(new_size < old_size);
 
             ascend[2*i+1] = reallocate(p1, old_size, new_size, ALIGN);
-            sanity_check(ascend.as_slice());
+            sanity_check(&*ascend);
 
             ascend[2*i] = reallocate(p0, old_size, new_size, ALIGN);
-            sanity_check(ascend.as_slice());
+            sanity_check(&*ascend);
         }
     }
 }
index f5d46d4ce7c2b221a5c8b9315eb3c68713461a96..16eeb99982e91411c9504b861be391263683c8cd 100644 (file)
@@ -15,10 +15,10 @@ fn foo(x: &[int]) -> int {
 
 pub fn main() {
     let p = vec!(1,2,3,4,5);
-    let r = foo(p.as_slice());
+    let r = foo(&p);
     assert_eq!(r, 1);
 
     let p = vec!(5,4,3,2,1);
-    let r = foo(p.as_slice());
+    let r = foo(&p);
     assert_eq!(r, 5);
 }
index dc6f377e9b279ff6a535dcc1ec7e475ae66ca872..6ebef9f34ad6619d54bd1798288acd183bf532d1 100644 (file)
@@ -24,7 +24,7 @@ pub fn main() {
     let mut i = 3i32;
     assert_eq!(i, 3);
     {
-        let cl = |&mut:| i += 1;
+        let cl = || i += 1;
         let mut cl_box = box_it(box cl);
         cl_box.cl.call_mut(());
     }
index 2cee2ac58b39c4d22fb62d6c1172ae45fcc394e1..bcf74729fdbfba1acf7a3b7c2f5b7c6ea0c08b82 100644 (file)
@@ -20,5 +20,5 @@ fn both<'r>(v: &'r [uint]) -> &'r [uint] {
 
 pub fn main() {
     let v = vec!(1,2,3);
-    both(v.as_slice());
+    both(&v);
 }
index d247f864571067bee3803c527cf00701c9a24a90..1fdf3a92a3fdbdea5fbb4bd419e122374cd0ee9c 100644 (file)
@@ -13,7 +13,7 @@ fn view<T>(x: &[T]) -> &[T] {x}
 
 pub fn main() {
     let v = vec!(1, 2, 3);
-    let x = view(v.as_slice());
-    let y = view(x.as_slice());
+    let x = view(&v);
+    let y = view(x);
     assert!((v[0] == x[0]) && (v[0] == y[0]));
 }
index c4852c9162cab4cfa31ab039f3813d75800d6254..a2b6d569ac9a72f0937219612d86e43c47a0a1be 100644 (file)
 pub fn main() {
     fn explicit() {
         fn test<F>(_x: Option<Box<F>>) where F: FnMut(Box<for<'a> FnMut(&'a int)>) {}
-        test(Some(box |&mut: _f: Box<for<'a> FnMut(&'a int)>| {}));
+        test(Some(box |_f: Box<for<'a> FnMut(&'a int)>| {}));
     }
 
     // The code below is shorthand for the code above (and more likely
     // to represent what one encounters in practice).
     fn implicit() {
         fn test<F>(_x: Option<Box<F>>) where F: FnMut(Box<        FnMut(&   int)>) {}
-        test(Some(box |&mut: _f: Box<        FnMut(&   int)>| {}));
+        test(Some(box |_f: Box<        FnMut(&   int)>| {}));
     }
 
     explicit();
index be7db25201afd0c625394388d3bfca6021d39550..bf789d5364500df680752103028111dccdb92c33 100644 (file)
@@ -21,7 +21,7 @@
 
 use TypeStructure::{TypeInt, TypeFunction};
 use AstKind::{ExprInt, ExprVar, ExprLambda};
-use arena::Arena;
+use arena::TypedArena;
 use std::collections::HashMap;
 use std::mem;
 
@@ -45,17 +45,20 @@ fn eq(&self, other: &TypeStructure<'tcx>) -> bool {
 
 impl<'tcx> Eq for TypeStructure<'tcx> {}
 
+type TyArena<'tcx> = TypedArena<TypeStructure<'tcx>>;
+type AstArena<'ast> = TypedArena<AstStructure<'ast>>;
+
 struct TypeContext<'tcx, 'ast> {
-    ty_arena: &'tcx Arena,
+    ty_arena: &'tcx TyArena<'tcx>,
     types: Vec<Type<'tcx>> ,
     type_table: HashMap<NodeId, Type<'tcx>>,
 
-    ast_arena: &'ast Arena,
+    ast_arena: &'ast AstArena<'ast>,
     ast_counter: uint,
 }
 
 impl<'tcx,'ast> TypeContext<'tcx, 'ast> {
-    fn new(ty_arena: &'tcx Arena, ast_arena: &'ast Arena)
+    fn new(ty_arena: &'tcx TyArena<'tcx>, ast_arena: &'ast AstArena<'ast>)
            -> TypeContext<'tcx, 'ast> {
         TypeContext { ty_arena: ty_arena,
                       types: Vec::new(),
@@ -72,7 +75,7 @@ fn add_type(&mut self, s: TypeStructure<'tcx>) -> Type<'tcx> {
             }
         }
 
-        let ty = self.ty_arena.alloc(|| s);
+        let ty = self.ty_arena.alloc(s);
         self.types.push(ty);
         ty
     }
@@ -85,7 +88,7 @@ fn set_type(&mut self, id: NodeId, ty: Type<'tcx>) -> Type<'tcx> {
     fn ast(&mut self, a: AstKind<'ast>) -> Ast<'ast> {
         let id = self.ast_counter;
         self.ast_counter += 1;
-        self.ast_arena.alloc(|| AstStructure { id: NodeId {id:id}, kind: a })
+        self.ast_arena.alloc(AstStructure { id: NodeId {id:id}, kind: a })
     }
 }
 
@@ -127,8 +130,8 @@ fn compute_types<'tcx,'ast>(tcx: &mut TypeContext<'tcx,'ast>,
 }
 
 pub fn main() {
-    let ty_arena = arena::Arena::new();
-    let ast_arena = arena::Arena::new();
+    let ty_arena = TypedArena::new();
+    let ast_arena = TypedArena::new();
     let mut tcx = TypeContext::new(&ty_arena, &ast_arena);
     let ast = tcx.ast(ExprInt);
     let ty = compute_types(&mut tcx, ast);
index abd5789bb1f7639af518899318c6ddda0e39b152..7198c35944f9a0f5b0e764cb55108a5346375ca0 100644 (file)
@@ -25,6 +25,6 @@ fn call_static_closure(mut cl: closure_box<'static>) {
 }
 
 pub fn main() {
-    let cl_box = box_it(box |&mut:| println!("Hello, world!"));
+    let cl_box = box_it(box || println!("Hello, world!"));
     call_static_closure(cl_box);
 }
index 6a1384ff9339614ed4913f0bf329449eb8f88961..6d72e9774dca839b0982cb7d751f9c4a80ba36af 100644 (file)
@@ -13,9 +13,9 @@ pub fn main() {
     let y = [ 0; 1 ];
 
     print!("[");
-    for xi in &x[] {
-        print!("{:?}, ", &xi[]);
+    for xi in &x[..] {
+        print!("{:?}, ", &xi[..]);
     }
     println!("]");
-    println!("{:?}", &y[]);
+    println!("{:?}", &y[..]);
 }
index 899dc8ddbe90ddd597879cfe756f7d599f406c88..60856ee60425b310f1441f41b5960099f596b7ee 100644 (file)
@@ -13,7 +13,7 @@
 static mut calls: uint = 0;
 
 fn surrounding() {
-    let return_works = |&: n: int| {
+    let return_works = |n: int| {
         unsafe { calls += 1 }
 
         if n >= 0 { return; }
@@ -23,7 +23,7 @@ fn surrounding() {
     return_works(10);
     return_works(20);
 
-    let return_works_proc = |n: int| {
+    let return_works_proc = |n: int| {
         unsafe { calls += 1 }
 
         if n >= 0 { return; }
index efc1913a2055d160749bb40f41e6a6f8fa1dd7bf..ec033b74dd1cde1714b84dbf7b37636ed9aef1a7 100644 (file)
@@ -41,7 +41,7 @@ fn start(argc: int, argv: *const *const u8) -> int {
             ffi::c_str_to_bytes(&ptr).to_vec()
         }).collect::<Vec<_>>()
     };
-    let me = args[0].as_slice();
+    let me = &*args[0];
 
     let x: &[u8] = &[1u8];
     pass(Command::new(me).arg(x).output().unwrap());
@@ -59,7 +59,7 @@ fn start(argc: int, argv: *const *const u8) -> int {
 
 fn pass(output: ProcessOutput) {
     if !output.status.success() {
-        println!("{:?}", str::from_utf8(output.output.as_slice()));
-        println!("{:?}", str::from_utf8(output.error.as_slice()));
+        println!("{:?}", str::from_utf8(&output.output));
+        println!("{:?}", str::from_utf8(&output.error));
     }
 }
index f7fa204d4539cb47fa950e1913ff0d9255fa3f5c..5d6657c7e12e653e9a4bd837dfb4c47b23fb345a 100644 (file)
@@ -48,8 +48,8 @@ pub fn main() {
         info!("bar foo");
     });
 
-    assert_eq!(rx.recv().unwrap().as_slice(), "foo");
-    assert_eq!(rx.recv().unwrap().as_slice(), "foo bar");
-    assert_eq!(rx.recv().unwrap().as_slice(), "bar foo");
+    assert_eq!(rx.recv().unwrap(), "foo");
+    assert_eq!(rx.recv().unwrap(), "foo bar");
+    assert_eq!(rx.recv().unwrap(), "bar foo");
     assert!(rx.recv().is_err());
 }
index 2b2539fac0e2d59ccb13003ffea2e01ac1eb3665..a2706dca7d3ea3d0edb036e724e9f51479cb1c84 100644 (file)
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() > 1 && args[1].as_slice() == "segfault" {
+    if args.len() > 1 && args[1] == "segfault" {
         unsafe { *(0 as *mut int) = 1 }; // trigger a segfault
     } else {
-        let segfault = Command::new(args[0].as_slice()).arg("segfault").output().unwrap();
+        let segfault = Command::new(&args[0]).arg("segfault").output().unwrap();
         assert!(!segfault.status.success());
-        let error = String::from_utf8_lossy(segfault.error.as_slice());
+        let error = String::from_utf8_lossy(&segfault.error);
         assert!(!error.contains("has overflowed its stack"));
     }
 }
index 89624c3ac16a339fbb306c297740bd48dd6a36c5..6c9707103b9bb91d8026e11eeb7b73e3b807a44d 100644 (file)
@@ -21,7 +21,7 @@ fn test05_start<F:FnOnce(int)>(f: F) {
 
 fn test05() {
     let three = box 3;
-    let fn_to_send = move|n:int| {
+    let fn_to_send = move|n:int| {
         println!("{}", *three + n); // will copy x into the closure
         assert_eq!(*three, 3);
     };
index bf500bf041723068f43743630b574d942cecaeed..856eb241addc3279eb8131ffb554084ebec1c781 100644 (file)
 
 pub fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() >= 2 && args[1].as_slice() == "signal" {
+    let args = args;
+    if args.len() >= 2 && args[1] == "signal" {
         // Raise a segfault.
         unsafe { *(0 as *mut int) = 0; }
     } else {
-        let status = Command::new(args[0].as_slice()).arg("signal").status().unwrap();
+        let status = Command::new(&args[0]).arg("signal").status().unwrap();
         // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
         match status {
             ExitSignal(_) if cfg!(unix) => {},
index 23a928571766181cb31478bc9a6fcbbecc107ce3..de8f76518fc00c0cbdbe91f0230b2ccd8214dd91 100644 (file)
@@ -26,12 +26,12 @@ fn test() {
 
 fn main() {
     let args = os::args();
-    let args = args.as_slice();
-    if args.len() > 1 && args[1].as_slice() == "test" {
+    let args = args;
+    if args.len() > 1 && args[1] == "test" {
         return test();
     }
 
-    let mut p = Command::new(args[0].as_slice())
+    let mut p = Command::new(&args[0])
                         .arg("test").spawn().unwrap();
     assert!(p.wait().unwrap().success());
 }
index 43e517404cb09b3adc9414f17584d9da7cfae8b2..6e256be69dac74c1d463ebe30f493c2518e0c306 100644 (file)
@@ -13,7 +13,7 @@
 fn main() {
     let x: &[int] = &[1, 2, 3, 4, 5];
     let cmp: &[int] = &[1, 2, 3, 4, 5];
-    assert!(&x[] == cmp);
+    assert!(&x[..] == cmp);
     let cmp: &[int] = &[3, 4, 5];
     assert!(&x[2..] == cmp);
     let cmp: &[int] = &[1, 2, 3];
@@ -23,7 +23,7 @@ fn main() {
 
     let x: Vec<int> = vec![1, 2, 3, 4, 5];
     let cmp: &[int] = &[1, 2, 3, 4, 5];
-    assert!(&x[] == cmp);
+    assert!(&x[..] == cmp);
     let cmp: &[int] = &[3, 4, 5];
     assert!(&x[2..] == cmp);
     let cmp: &[int] = &[1, 2, 3];
@@ -34,7 +34,7 @@ fn main() {
     let x: &mut [int] = &mut [1, 2, 3, 4, 5];
     {
         let cmp: &mut [int] = &mut [1, 2, 3, 4, 5];
-        assert!(&mut x[] == cmp);
+        assert!(&mut x[..] == cmp);
     }
     {
         let cmp: &mut [int] = &mut [3, 4, 5];
@@ -52,7 +52,7 @@ fn main() {
     let mut x: Vec<int> = vec![1, 2, 3, 4, 5];
     {
         let cmp: &mut [int] = &mut [1, 2, 3, 4, 5];
-        assert!(&mut x[] == cmp);
+        assert!(&mut x[..] == cmp);
     }
     {
         let cmp: &mut [int] = &mut [3, 4, 5];
index 81db525db28a2a3d40c7053d4fe69785f0a3c31a..30b53dbb0ad5bea0bdf96b7ddb419345e2749ad6 100644 (file)
@@ -49,28 +49,24 @@ fn index(&self, _index: &RangeFull) -> &Foo {
 }
 
 impl IndexMut<Range<Foo>> for Foo {
-    type Output = Foo;
     fn index_mut(&mut self, index: &Range<Foo>) -> &mut Foo {
         unsafe { COUNT += 1; }
         self
     }
 }
 impl IndexMut<RangeTo<Foo>> for Foo {
-    type Output = Foo;
     fn index_mut(&mut self, index: &RangeTo<Foo>) -> &mut Foo {
         unsafe { COUNT += 1; }
         self
     }
 }
 impl IndexMut<RangeFrom<Foo>> for Foo {
-    type Output = Foo;
     fn index_mut(&mut self, index: &RangeFrom<Foo>) -> &mut Foo {
         unsafe { COUNT += 1; }
         self
     }
 }
 impl IndexMut<RangeFull> for Foo {
-    type Output = Foo;
     fn index_mut(&mut self, _index: &RangeFull) -> &mut Foo {
         unsafe { COUNT += 1; }
         self
@@ -80,11 +76,11 @@ fn index_mut(&mut self, _index: &RangeFull) -> &mut Foo {
 
 fn main() {
     let mut x = Foo;
-    &x[];
+    &x[..];
     &x[Foo..];
     &x[..Foo];
     &x[Foo..Foo];
-    &mut x[];
+    &mut x[..];
     &mut x[Foo..];
     &mut x[..Foo];
     &mut x[Foo..Foo];
index fc45e107bb0eb79d38643ee15c1e0bc104eee56e..475af8f2b8ef05fa70cc1f46c6013705024ac8c6 100644 (file)
@@ -20,8 +20,8 @@ macro_rules! check {
             static S: $t = $e;
             let v: $t = $e;
             assert_eq!(S, v);
-            assert_eq!(format!("{:?}", v).as_slice(), $s);
-            assert_eq!(format!("{:?}", S).as_slice(), $s);
+            assert_eq!(format!("{:?}", v), $s);
+            assert_eq!(format!("{:?}", S), $s);
         });*
     }}
 }
index 4913b34c4b311fff52b648392dba030cc5d90d94..197890c1277126c1e607c3d4e555dbd7012bdba5 100644 (file)
@@ -12,8 +12,8 @@
 
 // Smallest "hello world" with a libc runtime
 
+#![feature(intrinsics, lang_items, start, no_std)]
 #![no_std]
-#![feature(intrinsics, lang_items, start)]
 
 extern crate libc;
 
index 3c0f9505736a962a0bda461dec549b2b121d65f1..1dbd29a781effb127c488a3769c1a88a39dfbc5b 100644 (file)
@@ -12,7 +12,7 @@
 
 pub fn main() {
     let mut a: Vec<int> = vec!(0, 1, 2, 3, 4, 5, 6);
-    a.as_mut_slice().swap(2, 4);
+    a.swap(2, 4);
     assert_eq!(a[2], 4);
     assert_eq!(a[4], 2);
     let mut n = 42;
index 6695920723aefeb6692346f0e83ce22afc10c29a..4df1ff1481042a91b78430029642ee11b0505e09 100644 (file)
@@ -37,7 +37,7 @@ fn test_tempdir() {
 
 fn test_rm_tempdir() {
     let (tx, rx) = channel();
-    let f = move|:| -> () {
+    let f = move|| -> () {
         let tmp = TempDir::new("test_rm_tempdir").unwrap();
         tx.send(tmp.path().clone()).unwrap();
         panic!("panic to unwind past `tmp`");
@@ -48,7 +48,7 @@ fn test_rm_tempdir() {
 
     let tmp = TempDir::new("test_rm_tempdir").unwrap();
     let path = tmp.path().clone();
-    let f = move|:| -> () {
+    let f = move|| -> () {
         let _tmp = tmp;
         panic!("panic to unwind past `tmp`");
     };
@@ -57,10 +57,11 @@ fn test_rm_tempdir() {
 
     let path;
     {
-        let f = move|:| {
+        let f = move || {
             TempDir::new("test_rm_tempdir").unwrap()
         };
-        let tmp = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
+        // FIXME(#16640) `: TempDir` annotation shouldn't be necessary
+        let tmp: TempDir = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
         path = tmp.path().clone();
         assert!(path.exists());
     }
@@ -78,7 +79,7 @@ fn test_rm_tempdir() {
 
 fn test_rm_tempdir_close() {
     let (tx, rx) = channel();
-    let f = move|:| -> () {
+    let f = move|| -> () {
         let tmp = TempDir::new("test_rm_tempdir").unwrap();
         tx.send(tmp.path().clone()).unwrap();
         tmp.close();
@@ -90,7 +91,7 @@ fn test_rm_tempdir_close() {
 
     let tmp = TempDir::new("test_rm_tempdir").unwrap();
     let path = tmp.path().clone();
-    let f = move|:| -> () {
+    let f = move|| -> () {
         let tmp = tmp;
         tmp.close();
         panic!("panic when unwinding past `tmp`");
@@ -100,10 +101,11 @@ fn test_rm_tempdir_close() {
 
     let path;
     {
-        let f = move|:| {
+        let f = move || {
             TempDir::new("test_rm_tempdir").unwrap()
         };
-        let tmp = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
+        // FIXME(#16640) `: TempDir` annotation shouldn't be necessary
+        let tmp: TempDir = Thread::scoped(f).join().ok().expect("test_rm_tmdir");
         path = tmp.path().clone();
         assert!(path.exists());
         tmp.close();
index 0b650d97e4f55677406984f138c9978e8f903277..26772a5b22c076c140adb0244b7ff98a1e7e28d2 100644 (file)
@@ -44,19 +44,19 @@ struct Goldfyshe {
 }
 
 impl Pet for Catte {
-    fn name(&self, mut blk: Box<FnMut(&str)>) { blk(self.name.as_slice()) }
+    fn name(&self, mut blk: Box<FnMut(&str)>) { blk(&self.name) }
     fn num_legs(&self) -> uint { 4 }
     fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
 }
 impl Pet for Dogge {
-    fn name(&self, mut blk: Box<FnMut(&str)>) { blk(self.name.as_slice()) }
+    fn name(&self, mut blk: Box<FnMut(&str)>) { blk(&self.name) }
     fn num_legs(&self) -> uint { 4 }
     fn of_good_pedigree(&self) -> bool {
         self.bark_decibels < 70 || self.tricks_known > 20
     }
 }
 impl Pet for Goldfyshe {
-    fn name(&self, mut blk: Box<FnMut(&str)>) { blk(self.name.as_slice()) }
+    fn name(&self, mut blk: Box<FnMut(&str)>) { blk(&self.name) }
     fn num_legs(&self) -> uint { 0 }
     fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
 }
diff --git a/src/test/run-pass/traits-issue-22019.rs b/src/test/run-pass/traits-issue-22019.rs
new file mode 100644 (file)
index 0000000..5d3195e
--- /dev/null
@@ -0,0 +1,41 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test an issue where global caching was causing free regions from
+// distinct scopes to be compared (`'g` and `'h`). The only important
+// thing is that compilation succeeds here.
+
+#![allow(missing_copy_implementations)]
+#![allow(unused_variables)]
+
+use std::borrow::ToOwned;
+
+pub struct CFGNode;
+
+pub type Node<'a> = &'a CFGNode;
+
+pub trait GraphWalk<'c, N> {
+    /// Returns all the nodes in this graph.
+    fn nodes(&'c self) where [N]:ToOwned<Vec<N>>;
+}
+
+impl<'g> GraphWalk<'g, Node<'g>> for u32
+{
+    fn nodes(&'g self) where [Node<'g>]:ToOwned<Vec<Node<'g>>>
+    { loop { } }
+}
+
+impl<'h> GraphWalk<'h, Node<'h>> for u64
+{
+    fn nodes(&'h self) where [Node<'h>]:ToOwned<Vec<Node<'h>>>
+    { loop { } }
+}
+
+fn main()  { }
index b114391a36db0220d7074dbf64683765e21973c7..d33ebeadba86e7008e586df25ab1a99c366b3c96 100644 (file)
@@ -56,8 +56,8 @@ fn main() {
     // Note that every unboxed closure has its own anonymous type,
     // so no two IDs should equal each other, even when compatible
     {
-        let a = id(|&: _: &int, _: &int| {});
-        let b = id(|&: _: &int, _: &int| {});
+        let a = id(|_: &int, _: &int| {});
+        let b = id(|_: &int, _: &int| {});
         assert!(a != b);
     }
 
index b2f6dad998881b344501cbc7d6f30e2356865e75..d7748f247740c2457fd6febe3ef7634d42faaf1d 100644 (file)
@@ -23,10 +23,10 @@ unsafe impl Sync for TestStruct {}
 pub fn main() {
     let x: Vec<_> = (0u..5).collect();
     let expected: &[uint] = &[0,1,2,3,4];
-    assert_eq!(x.as_slice(), expected);
+    assert_eq!(x, expected);
 
     let x = (0u..5).collect::<Vec<_>>();
-    assert_eq!(x.as_slice(), expected);
+    assert_eq!(x, expected);
 
     let y: _ = "hello";
     assert_eq!(y.len(), 5);
index 635e1670aada1bd2be866634b7e3a41df878659d..7e71e1da462fd1efc71fc771507939ec6b21723d 100644 (file)
@@ -24,8 +24,8 @@ fn c<F:FnOnce(int, int) -> int>(f: F) -> int {
 
 fn main() {
     let z: int = 7;
-    assert_eq!(a(move |&: x: int, y| x + y + z), 10);
-    assert_eq!(b(move |&mut: x: int, y| x + y + z), 14);
-    assert_eq!(c(move |x: int, y| x + y + z), 18);
+    assert_eq!(a(move |x: int, y| x + y + z), 10);
+    assert_eq!(b(move |x: int, y| x + y + z), 14);
+    assert_eq!(c(move |x: int, y| x + y + z), 18);
 }
 
index 27528ca5d5663671c3a2fdfd4114385d6479b752..d515ccf2ec0a50ca8e4367210004e298b2850a05 100644 (file)
@@ -15,7 +15,7 @@
 use std::ops::FnMut;
 
  fn make_adder(x: i32) -> Box<FnMut(i32)->i32+'static> {
-    (box move |&mut: y: i32| -> i32 { x + y }) as
+    (box move |y: i32| -> i32 { x + y }) as
         Box<FnMut(i32)->i32+'static>
 }
 
index be955486dac33d75ce2a8f2939c844d2adc095c7..f1435b43f80179d6c0f2f4af7ae25b3ea781e624 100644 (file)
@@ -28,8 +28,8 @@ fn main() {
     let mut x = 0u;
     let y = 2u;
 
-    call_fn(|&:| assert_eq!(x, 0));
-    call_fn_mut(|&mut:| x += y);
-    call_fn_once(|:| x += y);
+    call_fn(|| assert_eq!(x, 0));
+    call_fn_mut(|| x += y);
+    call_fn_once(|| x += y);
     assert_eq!(x, y * 2);
 }
index 2854d64f6637b8dec6e8fd78b70637b7ea6efb06..0c49c8151708625ac095a0a639a9410240a6ffe4 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(unboxed_closures)]
 
 fn main() {
-    let mut unboxed = |&mut:| {};
+    let mut unboxed = || {};
     unboxed();
 }
 
index 8d4d7b4ecb5033ad8873d1b51e93163b3e1cf209..f4a24c17e6e99834736346f868bb66bd8a46df9b 100644 (file)
@@ -55,13 +55,13 @@ fn c<F:FnOnce(int, int) -> int>(f: F) -> int {
 
 fn test_fn() {
     {
-        a(move |&: a: int, b| { a + b });
+        a(move |a: int, b| { a + b });
     }
     assert_eq!(drop_count(), 0);
 
     {
         let z = &Droppable::new();
-        a(move |&: a: int, b| { z; a + b });
+        a(move |a: int, b| { z; a + b });
         assert_eq!(drop_count(), 0);
     }
     assert_eq!(drop_count(), 1);
@@ -69,7 +69,7 @@ fn test_fn() {
     {
         let z = &Droppable::new();
         let zz = &Droppable::new();
-        a(move |&: a: int, b| { z; zz; a + b });
+        a(move |a: int, b| { z; zz; a + b });
         assert_eq!(drop_count(), 1);
     }
     assert_eq!(drop_count(), 3);
@@ -77,13 +77,13 @@ fn test_fn() {
 
 fn test_fn_mut() {
     {
-        b(move |&mut: a: int, b| { a + b });
+        b(move |a: int, b| { a + b });
     }
     assert_eq!(drop_count(), 3);
 
     {
         let z = &Droppable::new();
-        b(move |&mut: a: int, b| { z; a + b });
+        b(move |a: int, b| { z; a + b });
         assert_eq!(drop_count(), 3);
     }
     assert_eq!(drop_count(), 4);
@@ -91,7 +91,7 @@ fn test_fn_mut() {
     {
         let z = &Droppable::new();
         let zz = &Droppable::new();
-        b(move |&mut: a: int, b| { z; zz; a + b });
+        b(move |a: int, b| { z; zz; a + b });
         assert_eq!(drop_count(), 4);
     }
     assert_eq!(drop_count(), 6);
@@ -99,13 +99,13 @@ fn test_fn_mut() {
 
 fn test_fn_once() {
     {
-        c(move |a: int, b| { a + b });
+        c(move |a: int, b| { a + b });
     }
     assert_eq!(drop_count(), 6);
 
     {
         let z = Droppable::new();
-        c(move |a: int, b| { z; a + b });
+        c(move |a: int, b| { z; a + b });
         assert_eq!(drop_count(), 7);
     }
     assert_eq!(drop_count(), 7);
@@ -113,7 +113,7 @@ fn test_fn_once() {
     {
         let z = Droppable::new();
         let zz = Droppable::new();
-        c(move |a: int, b| { z; zz; a + b });
+        c(move |a: int, b| { z; zz; a + b });
         assert_eq!(drop_count(), 9);
     }
     assert_eq!(drop_count(), 9);
index 04c124946c9a1edb28697a81b62d3205e871ba22..f4af42a866b6d6a83c478c60311f7b46165f3c2e 100644 (file)
@@ -17,7 +17,7 @@ fn call_it<F:FnMut(i32,i32)->i32>(y: i32, mut f: F) -> i32 {
 }
 
 pub fn main() {
-    let f = |&mut: x: i32, y: i32| -> i32 { x + y };
+    let f = |x: i32, y: i32| -> i32 { x + y };
     let z = call_it(3, f);
     println!("{}", z);
     assert_eq!(z, 5);
index 5bebc70ca542227ce259ff85792fbe94f81108e8..56de15961101f063f9da4785c6e6eb1c0086a919 100644 (file)
@@ -22,5 +22,5 @@ fn doit<T,F>(val: T, f: &F)
 }
 
 pub fn main() {
-    doit(0, &|&: x /*: int*/ | { x.to_int(); });
+    doit(0, &|x /*: int*/ | { x.to_int(); });
 }
index a678c7a852ff59263a9f6d182fd4ea73bf708409..c74ed665e7a071d9d70f6c98c306a5e44538245b 100644 (file)
@@ -18,5 +18,5 @@
 fn doit<T>(val: T, f: &Fn(T)) { f.call((val,)) }
 
 pub fn main() {
-    doit(0, &|&: x /*: int*/ | { x.to_int(); });
+    doit(0, &|x /*: int*/ | { x.to_int(); });
 }
index 6e0b3625a2ee5750b29bd3dab123f8347663523d..a61dd095a0d4da2e6792afcc1bfeef3bb8637e8a 100644 (file)
@@ -22,5 +22,5 @@ fn doit<T,F>(val: T, f: &F)
 }
 
 pub fn main() {
-    doit(0, &|&: x /*: int*/ | { x.to_int(); });
+    doit(0, &|x /*: int*/ | { x.to_int(); });
 }
index 29064f4805339aaa17b7575c75a1840364a68cec..535c4562362c0d3ba9620e768aa66a9855ba4ad3 100644 (file)
@@ -17,7 +17,7 @@
 
 fn main(){
     fn bar<'a, T:Clone+'a> (t: T) -> Box<FnMut()->T + 'a> {
-        box move |&mut:| t.clone()
+        box move || t.clone()
     }
 
     let mut f = bar(42_u32);
index 43a44eca2d05ef0682993107c53fdc8d90a656ae..0d04aee2a1519dc3e885b794416c7f4e3df4abce 100644 (file)
 fn main() {
     {
         let mut x = 0u;
-        move |&mut:| x += 1;
+        move || x += 1;
     }
     {
         let mut x = 0u;
-        move |:| x += 1;
+        move || x += 1;
     }
     {
         let mut x = 0u;
-        move |&mut:| set(&mut x);
+        move || set(&mut x);
     }
     {
         let mut x = 0u;
-        move |:| set(&mut x);
+        move || set(&mut x);
     }
 }
index f9fc5770a381426061eb0b903c928ff69010d8d8..c8f0d5fde45efea490bee262988152a5cd764987 100644 (file)
 #![feature(unboxed_closures)]
 
 fn main() {
-    let task: Box<Fn(int) -> int> = box |&: x| x;
+    let task: Box<Fn(int) -> int> = box |x| x;
     task.call((0, ));
 
-    let mut task: Box<FnMut(int) -> int> = box |&mut: x| x;
+    let mut task: Box<FnMut(int) -> int> = box |x| x;
     task(0);
 
-    call(|:x| x, 22);
+    call(|x| x, 22);
 }
 
 fn call<F:FnOnce(int) -> int>(f: F, x: int) -> int {
index c473db4586ff74283027b4873708ec42d9c0b244..9f29e75be7ccaec301935a0a4b14b38188291fec 100644 (file)
@@ -13,7 +13,7 @@
 use std::ops::FnMut;
 
 pub fn main() {
-    let mut f = |&mut: x: int, y: int| -> int { x + y };
+    let mut f = |x: int, y: int| -> int { x + y };
     let z = f(1, 2);
     assert_eq!(z, 3);
 }
index 61ceb5e140e32bcb102adc9f8ad46fba0a2e63ee..9e543f925f82e2acdc60e1f1f5e0eb6b9a8be197 100644 (file)
@@ -27,8 +27,8 @@ fn c<F:FnOnce(int, int) -> int>(f: F) -> int {
 
 fn main() {
     let z = 10;
-    assert_eq!(a(move |&: x: int, y| x + y + z), 13);
-    assert_eq!(b(move |&mut: x: int, y| x + y + z), 17);
-    assert_eq!(c(move |x: int, y| x + y + z), 21);
+    assert_eq!(a(move |x: int, y| x + y + z), 13);
+    assert_eq!(b(move |x: int, y| x + y + z), 17);
+    assert_eq!(c(move |x: int, y| x + y + z), 21);
 }
 
index e4b35aada9f6b8e7acfee656a2040c4f2096b2fd..7a6b68a5e09ec27113ad716f830cf6e5d120f68a 100644 (file)
@@ -11,7 +11,7 @@
 #![feature(unboxed_closures)]
 
 fn main() {
-    let onetime = |x| x;
+    let onetime = |x| x;
     onetime(0);
 }
 
index a04301931da6a941e03048046e977c3a0500565d..2871b5c68620396c9e1815e832084724bb30f9a2 100644 (file)
@@ -30,6 +30,6 @@ pub fn replace_map<'a, T, F>(src: &mut T, prod: F) where F: FnOnce(T) -> T {
 pub fn main() {
     let mut a = 7u;
     let b = &mut a;
-    replace_map(b, |x: uint| x * 2);
+    replace_map(b, |x: uint| x * 2);
     assert_eq!(*b, 14u);
 }
index 3c50712b4647f1d6c7c115468861cac7d0a40a72..0acf736e2ab5c5e8403c0bfd2269a57e8dfa5733 100644 (file)
@@ -27,5 +27,5 @@ pub fn main() {
     }).join();
 
     let s = x.err().unwrap().downcast::<&'static str>().ok().unwrap();
-    assert_eq!(s.as_slice(), "This panic should happen.");
+    assert_eq!(&**s, "This panic should happen.");
 }
index a2d1b8780aafffc856eb441707d4b24113530e58..4e8fdda95631185c9fc4541c41e4af2b947c3491 100644 (file)
@@ -13,6 +13,6 @@
 
 pub fn main() {
     let _x = box 1;
-    let lam_move = |&:| {};
+    let lam_move = || {};
     lam_move();
 }
index a2e1d8a567167d39394be81b71e88d562e0e9333..65a392e63c51001007737b1046f3dc31f692871f 100644 (file)
@@ -10,7 +10,7 @@
 // except according to those terms.
 
 #![allow(unused_imports)]
-#![feature(start)]
+#![feature(start, no_std)]
 #![no_std]
 
 extern crate std;
index 02a791e7975193c959852ede408dab245b8f8c59..64c4c17386b3253341153b4fff7a0312105d8435 100644 (file)
@@ -14,7 +14,7 @@ pub fn main() {
     let a: Vec<int> = vec!(1, 2, 3, 4, 5);
     let b: Vec<int> = vec!(6, 7, 8, 9, 0);
     let mut v: Vec<int> = a;
-    v.push_all(b.as_slice());
+    v.push_all(&b);
     println!("{}", v[9]);
     assert_eq!(v[0], 1);
     assert_eq!(v[7], 8);
index c6c370173497096172548739621beaa8c5f2cbc9..47b87fce2abaf7b6d0669241a75ad48902178a73 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-#![feature(lang_items, start)]
+#![feature(lang_items, start, no_std)]
 #![no_std]
 
 extern crate "std" as other;
index 9d83c0b007996cec77674df1b8d25e2d1547220a..d13369b1f5258f9d29dd0a08aa6bd8daa20c5575 100644 (file)
@@ -68,7 +68,7 @@ pub fn main() {
             // work out the total number of comparisons required to sort
             // this array...
             let mut count = 0us;
-            main.clone().as_mut_slice().sort_by(|a, b| { count += 1; a.cmp(b) });
+            main.clone().sort_by(|a, b| { count += 1; a.cmp(b) });
 
             // ... and then panic on each and every single one.
             for panic_countdown in 0..count {
@@ -82,7 +82,7 @@ pub fn main() {
                 let _ = Thread::scoped(move|| {
                     let mut v = v;
                     let mut panic_countdown = panic_countdown;
-                    v.as_mut_slice().sort_by(|a, b| {
+                    v.sort_by(|a, b| {
                         if panic_countdown == 0 {
                             panic!()
                         }
index 12de40129fd2ff28e0c5e10597d9af177320a92c..dcbecb859e53720eaee053499769b03c0fa66447 100644 (file)
@@ -35,7 +35,7 @@ fn find_zombies() {
 
     // http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ps.html
     let ps_cmd_output = Command::new("ps").args(&["-A", "-o", "pid,ppid,args"]).output().unwrap();
-    let ps_output = String::from_utf8_lossy(ps_cmd_output.output.as_slice());
+    let ps_output = String::from_utf8_lossy(&ps_cmd_output.output);
 
     for (line_no, line) in ps_output.split('\n').enumerate() {
         if 0 < line_no && 0 < line.len() &&
@@ -56,7 +56,7 @@ fn main() {
     let too_long = format!("/NoSuchCommand{:0300}", 0u8);
 
     let _failures = (0..100).map(|_| {
-        let cmd = Command::new(too_long.as_slice());
+        let cmd = Command::new(&too_long);
         let failed = cmd.spawn();
         assert!(failed.is_err(), "Make sure the command fails to spawn(): {:?}", cmd);
         failed
index 4080796b7a74114326772abee303409f8f8f8a8d..c9f070a279c76f30becf5bfe8aab65c151282de3 100644 (file)
@@ -26,7 +26,7 @@ fn the(x: &Cell<bool>) {
         return while !x.get() { x.set(true); };
     }
     let i = &Cell::new(false);
-    let dont = {|&:|the(i)};
+    let dont = {||the(i)};
     dont();
     assert!((i.get()));
 }
index 808e937bc72e3d1c0ad46a6b3a773d4ac50535fe..7edcdf6429223d960d5c09df113f4e1b259e8c74 100644 (file)
@@ -18,9 +18,9 @@ fn warm_up<'a, F>(f: F) where F: Fn(&'a mut Bencher) {
 
 fn main() {
     // ICE trigger
-    warm_up(|&: b: &mut Bencher| () );
+    warm_up(|b: &mut Bencher| () );
 
     // OK
-    warm_up(|&: b| () );
+    warm_up(|b| () );
 }
 
diff --git a/src/test/run-pass/where-for-self.rs b/src/test/run-pass/where-for-self.rs
new file mode 100644 (file)
index 0000000..5d42679
--- /dev/null
@@ -0,0 +1,59 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Test that we can quantify lifetimes outside a constraint (i.e., including
+// the self type) in a where clause.
+
+static mut COUNT: u32 = 1;
+
+trait Bar<'a> {
+    fn bar(&self);
+}
+
+trait Baz<'a> {
+    fn baz(&self);
+}
+
+impl<'a, 'b> Bar<'b> for &'a u32 {
+    fn bar(&self) {
+        unsafe { COUNT *= 2; }
+    }
+}
+
+impl<'a, 'b> Baz<'b> for &'a u32 {
+    fn baz(&self) {
+        unsafe { COUNT *= 3; }
+    }
+}
+
+// Test we can use the syntax for HRL including the self type.
+fn foo1<T>(x: &T)
+    where for<'a, 'b> &'a T: Bar<'b>
+{
+    x.bar()
+}
+
+// Test we can quantify multiple bounds (i.e., the precedence is sensible).
+fn foo2<T>(x: &T)
+    where for<'a, 'b> &'a T: Bar<'b> + Baz<'b>
+{
+    x.baz();
+    x.bar()
+}
+
+fn main() {
+    let x = 42u32;
+    foo1(&x);
+    foo2(&x);
+    unsafe {
+        assert!(COUNT == 12);
+    }
+}
+